Merge "Snap for 10900817 from 90693766af2cf6ad057d0c8e08275c87022c6301 to sdk-release" into sdk-release
diff --git a/ADPF_OWNERS b/ADPF_OWNERS
new file mode 100644
index 0000000..e6ca8f4
--- /dev/null
+++ b/ADPF_OWNERS
@@ -0,0 +1,3 @@
+lpy@google.com
+mattbuckley@google.com
+xwxw@google.com
diff --git a/AconfigFlags.bp b/AconfigFlags.bp
new file mode 100644
index 0000000..f0b7598
--- /dev/null
+++ b/AconfigFlags.bp
@@ -0,0 +1,159 @@
+// Copyright (C) 2023 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.
+
+aconfig_srcjars = [
+    ":android.hardware.biometrics.flags-aconfig-java{.generated_srcjars}",
+    ":android.nfc.flags-aconfig-java{.generated_srcjars}",
+    ":android.os.flags-aconfig-java{.generated_srcjars}",
+    ":android.security.flags-aconfig-java{.generated_srcjars}",
+    ":com.android.hardware.camera2-aconfig-java{.generated_srcjars}",
+    ":com.android.window.flags.window-aconfig-java{.generated_srcjars}",
+    ":com.android.hardware.input-aconfig-java{.generated_srcjars}",
+    ":com.android.text.flags-aconfig-java{.generated_srcjars}",
+]
+
+filegroup {
+    name: "framework-minus-apex-aconfig-srcjars",
+    srcs: aconfig_srcjars,
+}
+
+// Aconfig declarations and libraries for the core framework
+java_defaults {
+    name: "framework-minus-apex-aconfig-libraries",
+
+    // Add java_aconfig_libraries to here to add them to the core framework
+    // Add aconfig-annotations-lib as a dependency for the optimization
+    srcs: aconfig_srcjars,
+    libs: ["aconfig-annotations-lib"],
+}
+
+// Default flags for java_aconfig_libraries that go into framework-minus-apex
+// These libraries will not work standalone
+java_defaults {
+    name: "framework-minus-apex-aconfig-java-defaults",
+    sdk_version: "core_platform",
+    libs: ["fake_device_config"],
+}
+
+// Camera
+aconfig_declarations {
+    name: "com.android.hardware.camera2-aconfig",
+    package: "com.android.hardware.camera2",
+    srcs: ["core/java/android/hardware/camera2/camera_platform.aconfig"],
+}
+
+java_aconfig_library {
+    name: "com.android.hardware.camera2-aconfig-java",
+    aconfig_declarations: "com.android.hardware.camera2-aconfig",
+    defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
+// Window
+aconfig_declarations {
+    name: "com.android.window.flags.window-aconfig",
+    package: "com.android.window.flags",
+    srcs: ["core/java/android/window/flags/*.aconfig"],
+}
+
+java_aconfig_library {
+    name: "com.android.window.flags.window-aconfig-java",
+    aconfig_declarations: "com.android.window.flags.window-aconfig",
+    defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
+// Input
+aconfig_declarations {
+    name: "com.android.hardware.input.input-aconfig",
+    package: "com.android.hardware.input",
+    srcs: ["core/java/android/hardware/input/*.aconfig"],
+}
+
+java_aconfig_library {
+    name: "com.android.hardware.input-aconfig-java",
+    aconfig_declarations: "com.android.hardware.input.input-aconfig",
+    defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
+// Text
+aconfig_declarations {
+    name: "com.android.text.flags-aconfig",
+    package: "com.android.text.flags",
+    srcs: ["core/java/android/text/flags/*.aconfig"],
+}
+
+java_aconfig_library {
+    name: "com.android.text.flags-aconfig-java",
+    aconfig_declarations: "com.android.text.flags-aconfig",
+    defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
+// OS
+aconfig_declarations {
+    name: "android.os.flags-aconfig",
+    package: "android.os",
+    srcs: ["core/java/android/os/*.aconfig"],
+}
+
+java_aconfig_library {
+    name: "android.os.flags-aconfig-java",
+    aconfig_declarations: "android.os.flags-aconfig",
+    defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
+// NFC
+aconfig_declarations {
+    name: "android.nfc.flags-aconfig",
+    package: "android.nfc",
+    srcs: ["core/java/android/nfc/*.aconfig"],
+}
+
+java_aconfig_library {
+    name: "android.nfc.flags-aconfig-java",
+    aconfig_declarations: "android.nfc.flags-aconfig",
+    defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
+// Security
+aconfig_declarations {
+    name: "android.security.flags-aconfig",
+    package: "android.security",
+    srcs: ["core/java/android/security/*.aconfig"],
+}
+
+java_aconfig_library {
+    name: "android.security.flags-aconfig-java",
+    aconfig_declarations: "android.security.flags-aconfig",
+    defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
+java_aconfig_library {
+    name: "android.security.flags-aconfig-java-host",
+    aconfig_declarations: "android.security.flags-aconfig",
+    host_supported: true,
+    test: true,
+    defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
+
+// Biometrics
+aconfig_declarations {
+    name: "android.hardware.biometrics.flags-aconfig",
+    package: "android.hardware.biometrics",
+    srcs: ["core/java/android/hardware/biometrics/flags.aconfig"],
+}
+
+java_aconfig_library {
+    name: "android.hardware.biometrics.flags-aconfig-java",
+    aconfig_declarations: "android.hardware.biometrics.flags-aconfig",
+    defaults: ["framework-minus-apex-aconfig-java-defaults"],
+}
diff --git a/Android.bp b/Android.bp
index 94bcb3e..274c430 100644
--- a/Android.bp
+++ b/Android.bp
@@ -263,6 +263,7 @@
     defaults: [
         "framework-aidl-export-defaults",
         "latest_android_hardware_soundtrigger3_java_static",
+        "framework-minus-apex-aconfig-libraries",
     ],
     srcs: [
         ":framework-non-updatable-sources",
@@ -611,6 +612,7 @@
 }
 
 build = [
+    "AconfigFlags.bp",
     "ProtoLibraries.bp",
     "TestProtoLibraries.bp",
 ]
diff --git a/OWNERS b/OWNERS
index 4860acc..4e5c7d8 100644
--- a/OWNERS
+++ b/OWNERS
@@ -16,8 +16,6 @@
 ogunwale@google.com #{LAST_RESORT_SUGGESTION}
 roosa@google.com #{LAST_RESORT_SUGGESTION}
 smoreland@google.com #{LAST_RESORT_SUGGESTION}
-svetoslavganov@android.com #{LAST_RESORT_SUGGESTION}
-svetoslavganov@google.com #{LAST_RESORT_SUGGESTION}
 yamasani@google.com #{LAST_RESORT_SUGGESTION}
 
 # API changes are already covered by API-Review+1 (http://mdb/android-api-council)
@@ -30,10 +28,7 @@
 # Support bulk translation updates
 per-file */res*/values*/*.xml = byi@google.com, delphij@google.com
 
-per-file **.bp,**.mk = hansson@google.com
-per-file *.bp = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION}
-per-file Android.mk = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION}
-per-file framework-jarjar-rules.txt = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION}
+per-file **.bp,**.mk = hansson@google.com, joeo@google.com, lamontjones@google.com
 per-file TestProtoLibraries.bp = file:platform/platform_testing:/libraries/health/OWNERS
 per-file TestProtoLibraries.bp = file:platform/tools/tradefederation:/OWNERS
 
diff --git a/apct-tests/perftests/autofill/src/android/view/autofill/LoginTest.java b/apct-tests/perftests/autofill/src/android/view/autofill/LoginTest.java
index a5d1e00..59f08f6 100644
--- a/apct-tests/perftests/autofill/src/android/view/autofill/LoginTest.java
+++ b/apct-tests/perftests/autofill/src/android/view/autofill/LoginTest.java
@@ -140,7 +140,7 @@
                 state.resumeTiming();
             }
 
-            // Sanity check
+            // Check for no errors
             callback.assertNoAsyncErrors();
         } finally {
             mAfm.unregisterCallback(callback);
@@ -190,7 +190,7 @@
                 state.resumeTiming();
             }
 
-            // Sanity check
+            // Check for no errors
             callback.assertNoAsyncErrors();
         } finally {
             mAfm.unregisterCallback(callback);
@@ -303,7 +303,7 @@
                 callback.expectEvent(mPassword, EVENT_INPUT_SHOWN);
             }
 
-            // Sanity check
+            // Check for no errors
             callback.assertNoAsyncErrors();
         } finally {
             mAfm.unregisterCallback(callback);
diff --git a/apct-tests/perftests/core/src/android/os/OWNERS b/apct-tests/perftests/core/src/android/os/OWNERS
index a1719c9..76ab303 100644
--- a/apct-tests/perftests/core/src/android/os/OWNERS
+++ b/apct-tests/perftests/core/src/android/os/OWNERS
@@ -1 +1,4 @@
-per-file PackageParsingPerfTest.kt = file:/services/core/java/com/android/server/pm/OWNERS
\ No newline at end of file
+per-file PackageParsingPerfTest.kt = file:/services/core/java/com/android/server/pm/OWNERS
+
+# Bug component: 345036
+per-file VibratorPerfTest.java = file:/services/core/java/com/android/server/vibrator/OWNERS
\ No newline at end of file
diff --git a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
index a44d939..4d24c8c 100644
--- a/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
+++ b/apct-tests/perftests/multiuser/src/android/multiuser/UserLifecycleTests.java
@@ -97,16 +97,16 @@
     /** Name of users/profiles in the test. Users with this name may be freely removed. */
     private static final String TEST_USER_NAME = "UserLifecycleTests_test_user";
 
-    /** Name of dummy package used when timing how long app launches take. */
+    /** Name of placeholder package used when timing how long app launches take. */
     private static final String DUMMY_PACKAGE_NAME = "perftests.multiuser.apps.dummyapp";
 
-    // Copy of UserSystemPackageInstaller whitelist mode constants.
-    private static final String PACKAGE_WHITELIST_MODE_PROP =
+    // Copy of UserSystemPackageInstaller allowlist mode constants.
+    private static final String PACKAGE_ALLOWLIST_MODE_PROP =
             "persist.debug.user.package_whitelist_mode";
-    private static final int USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE = 0;
-    private static final int USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE = 0b001;
-    private static final int USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST = 0b100;
-    private static final int USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT = -1;
+    private static final int USER_TYPE_PACKAGE_ALLOWLIST_MODE_DISABLE = 0;
+    private static final int USER_TYPE_PACKAGE_ALLOWLIST_MODE_ENFORCE = 0b001;
+    private static final int USER_TYPE_PACKAGE_ALLOWLIST_MODE_IMPLICIT_ALLOWLIST = 0b100;
+    private static final int USER_TYPE_PACKAGE_ALLOWLIST_MODE_DEVICE_DEFAULT = -1;
 
     private UserManager mUm;
     private ActivityManager mAm;
@@ -563,13 +563,13 @@
     }
 
     // TODO: This is just a POC. Do this properly and add more.
-    /** Tests starting (unlocking) a newly-created profile using the user-type-pkg-whitelist. */
+    /** Tests starting (unlocking) a newly-created profile using the user-type-pkg-allowlist. */
     @Test(timeout = TIMEOUT_MAX_TEST_TIME_MS)
     public void managedProfileUnlock_usingWhitelist() {
         assumeTrue(mHasManagedUserFeature);
-        final int origMode = getUserTypePackageWhitelistMode();
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE
-                | USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST);
+        final int origMode = getUserTypePackageAllowlistMode();
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_ALLOWLIST_MODE_ENFORCE
+                | USER_TYPE_PACKAGE_ALLOWLIST_MODE_IMPLICIT_ALLOWLIST);
 
         try {
             while (mRunner.keepRunning()) {
@@ -586,15 +586,15 @@
                 mRunner.resumeTimingForNextIteration();
             }
         } finally {
-            setUserTypePackageWhitelistMode(origMode);
+            setUserTypePackageAllowlistMode(origMode);
         }
     }
-    /** Tests starting (unlocking) a newly-created profile NOT using the user-type-pkg-whitelist. */
+    /** Tests starting (unlocking) a newly-created profile NOT using the user-type-pkg-allowlist. */
     @Test(timeout = TIMEOUT_MAX_TEST_TIME_MS)
     public void managedProfileUnlock_notUsingWhitelist() {
         assumeTrue(mHasManagedUserFeature);
-        final int origMode = getUserTypePackageWhitelistMode();
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE);
+        final int origMode = getUserTypePackageAllowlistMode();
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_ALLOWLIST_MODE_DISABLE);
 
         try {
             while (mRunner.keepRunning()) {
@@ -611,7 +611,7 @@
                 mRunner.resumeTimingForNextIteration();
             }
         } finally {
-            setUserTypePackageWhitelistMode(origMode);
+            setUserTypePackageAllowlistMode(origMode);
         }
     }
 
@@ -822,17 +822,17 @@
         attestTrue(errMsg, success);
     }
 
-    /** Gets the PACKAGE_WHITELIST_MODE_PROP System Property. */
-    private int getUserTypePackageWhitelistMode() {
-        return SystemProperties.getInt(PACKAGE_WHITELIST_MODE_PROP,
-                USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT);
+    /** Gets the PACKAGE_ALLOWLIST_MODE_PROP System Property. */
+    private int getUserTypePackageAllowlistMode() {
+        return SystemProperties.getInt(PACKAGE_ALLOWLIST_MODE_PROP,
+                USER_TYPE_PACKAGE_ALLOWLIST_MODE_DEVICE_DEFAULT);
     }
 
-    /** Sets the PACKAGE_WHITELIST_MODE_PROP System Property to the given value. */
-    private void setUserTypePackageWhitelistMode(int mode) {
+    /** Sets the PACKAGE_ALLOWLIST_MODE_PROP System Property to the given value. */
+    private void setUserTypePackageAllowlistMode(int mode) {
         String result = ShellHelper.runShellCommand(
-                String.format("setprop %s %d", PACKAGE_WHITELIST_MODE_PROP, mode));
-        attestFalse("Failed to set sysprop " + PACKAGE_WHITELIST_MODE_PROP + ": " + result,
+                String.format("setprop %s %d", PACKAGE_ALLOWLIST_MODE_PROP, mode));
+        attestFalse("Failed to set sysprop " + PACKAGE_ALLOWLIST_MODE_PROP + ": " + result,
                 result != null && result.contains("Failed"));
     }
 
diff --git a/apct-tests/perftests/windowmanager/src/android/wm/RelayoutPerfTest.java b/apct-tests/perftests/windowmanager/src/android/wm/RelayoutPerfTest.java
index fb62920..9e29820 100644
--- a/apct-tests/perftests/windowmanager/src/android/wm/RelayoutPerfTest.java
+++ b/apct-tests/perftests/windowmanager/src/android/wm/RelayoutPerfTest.java
@@ -111,7 +111,7 @@
         stopProfiling();
     }
 
-    /** A dummy view to get IWindow. */
+    /** A placeholder view to get IWindow. */
     private static class ContentView extends LinearLayout {
         ContentView(Context context) {
             super(context);
diff --git a/apex/jobscheduler/framework/java/android/app/job/JobInfo.java b/apex/jobscheduler/framework/java/android/app/job/JobInfo.java
index f49cdbf..92320d3 100644
--- a/apex/jobscheduler/framework/java/android/app/job/JobInfo.java
+++ b/apex/jobscheduler/framework/java/android/app/job/JobInfo.java
@@ -360,7 +360,7 @@
 
     /**
      * Allows this job to run despite doze restrictions as long as the app is in the foreground
-     * or on the temporary whitelist
+     * or on the temporary allowlist
      * @hide
      */
     public static final int FLAG_IMPORTANT_WHILE_FOREGROUND = 1 << 1;
@@ -1803,13 +1803,13 @@
 
         /**
          * Setting this to true indicates that this job is important while the scheduling app
-         * is in the foreground or on the temporary whitelist for background restrictions.
+         * is in the foreground or on the temporary allowlist for background restrictions.
          * This means that the system will relax doze restrictions on this job during this time.
          *
          * Apps should use this flag only for short jobs that are essential for the app to function
          * properly in the foreground.
          *
-         * Note that once the scheduling app is no longer whitelisted from background restrictions
+         * Note that once the scheduling app is no longer allowlisted from background restrictions
          * and in the background, or the job failed due to unsatisfied constraints,
          * this job should be expected to behave like other jobs without this flag.
          *
diff --git a/apex/jobscheduler/framework/java/android/os/PowerWhitelistManager.java b/apex/jobscheduler/framework/java/android/os/PowerWhitelistManager.java
index 4ce31e9..20da171 100644
--- a/apex/jobscheduler/framework/java/android/os/PowerWhitelistManager.java
+++ b/apex/jobscheduler/framework/java/android/os/PowerWhitelistManager.java
@@ -29,10 +29,10 @@
 import java.util.List;
 
 /**
- * Interface to access and modify the permanent and temporary power save whitelist. The two lists
- * are kept separately. Apps placed on the permanent whitelist are only removed via an explicit
- * removeFromWhitelist call. Apps whitelisted by default by the system cannot be removed. Apps
- * placed on the temporary whitelist are removed from that whitelist after a predetermined amount of
+ * Interface to access and modify the permanent and temporary power save allowlist. The two lists
+ * are kept separately. Apps placed on the permanent allowlist are only removed via an explicit
+ * removeFromAllowlist call. Apps whitelisted by default by the system cannot be removed. Apps
+ * placed on the temporary allowlist are removed from that allowlist after a predetermined amount of
  * time.
  *
  * @deprecated Use {@link PowerExemptionManager} instead
@@ -50,18 +50,18 @@
     private final PowerExemptionManager mPowerExemptionManager;
 
     /**
-     * Indicates that an unforeseen event has occurred and the app should be whitelisted to handle
+     * Indicates that an unforeseen event has occurred and the app should be allowlisted to handle
      * it.
      */
     public static final int EVENT_UNSPECIFIED = PowerExemptionManager.EVENT_UNSPECIFIED;
 
     /**
-     * Indicates that an SMS event has occurred and the app should be whitelisted to handle it.
+     * Indicates that an SMS event has occurred and the app should be allowlisted to handle it.
      */
     public static final int EVENT_SMS = PowerExemptionManager.EVENT_SMS;
 
     /**
-     * Indicates that an MMS event has occurred and the app should be whitelisted to handle it.
+     * Indicates that an MMS event has occurred and the app should be allowlisted to handle it.
      */
     public static final int EVENT_MMS = PowerExemptionManager.EVENT_MMS;
 
@@ -381,7 +381,7 @@
     }
 
     /**
-     * Add the specified package to the permanent power save whitelist.
+     * Add the specified package to the permanent power save allowlist.
      *
      * @deprecated Use {@link PowerExemptionManager#addToPermanentAllowList(String)} instead
      */
@@ -392,7 +392,7 @@
     }
 
     /**
-     * Add the specified packages to the permanent power save whitelist.
+     * Add the specified packages to the permanent power save allowlist.
      *
      * @deprecated Use {@link PowerExemptionManager#addToPermanentAllowList(List)} instead
      */
@@ -403,10 +403,10 @@
     }
 
     /**
-     * Get a list of app IDs of app that are whitelisted. This does not include temporarily
-     * whitelisted apps.
+     * Get a list of app IDs of app that are allowlisted. This does not include temporarily
+     * allowlisted apps.
      *
-     * @param includingIdle Set to true if the app should be whitelisted from device idle as well
+     * @param includingIdle Set to true if the app should be allowlisted from device idle as well
      *                      as other power save restrictions
      * @deprecated Use {@link PowerExemptionManager#getAllowListedAppIds(boolean)} instead
      * @hide
@@ -418,10 +418,10 @@
     }
 
     /**
-     * Returns true if the app is whitelisted from power save restrictions. This does not include
-     * temporarily whitelisted apps.
+     * Returns true if the app is allowlisted from power save restrictions. This does not include
+     * temporarily allowlisted apps.
      *
-     * @param includingIdle Set to true if the app should be whitelisted from device
+     * @param includingIdle Set to true if the app should be allowlisted from device
      *                      idle as well as other power save restrictions
      * @deprecated Use {@link PowerExemptionManager#isAllowListed(String, boolean)} instead
      * @hide
@@ -432,11 +432,11 @@
     }
 
     /**
-     * Remove an app from the permanent power save whitelist. Only apps that were added via
+     * Remove an app from the permanent power save allowlist. Only apps that were added via
      * {@link #addToWhitelist(String)} or {@link #addToWhitelist(List)} will be removed. Apps
-     * whitelisted by default by the system cannot be removed.
+     * allowlisted by default by the system cannot be removed.
      *
-     * @param packageName The app to remove from the whitelist
+     * @param packageName The app to remove from the allowlist
      * @deprecated Use {@link PowerExemptionManager#removeFromPermanentAllowList(String)} instead
      */
     @Deprecated
@@ -446,10 +446,10 @@
     }
 
     /**
-     * Add an app to the temporary whitelist for a short amount of time.
+     * Add an app to the temporary allowlist for a short amount of time.
      *
-     * @param packageName The package to add to the temp whitelist
-     * @param durationMs  How long to keep the app on the temp whitelist for (in milliseconds)
+     * @param packageName The package to add to the temp allowlist
+     * @param durationMs  How long to keep the app on the temp allowlist for (in milliseconds)
      * @param reasonCode one of {@link ReasonCode}, use {@link #REASON_UNKNOWN} if not sure.
      * @param reason a optional human readable reason string, could be null or empty string.
      * @deprecated Use {@link PowerExemptionManager#addToTemporaryAllowList(
@@ -463,10 +463,10 @@
     }
 
     /**
-     * Add an app to the temporary whitelist for a short amount of time.
+     * Add an app to the temporary allowlist for a short amount of time.
      *
-     * @param packageName The package to add to the temp whitelist
-     * @param durationMs  How long to keep the app on the temp whitelist for (in milliseconds)
+     * @param packageName The package to add to the temp allowlist
+     * @param durationMs  How long to keep the app on the temp allowlist for (in milliseconds)
      * @deprecated Use {@link PowerExemptionManager#addToTemporaryAllowList(
      *             String, int, String, long)} instead
      */
@@ -478,15 +478,15 @@
     }
 
     /**
-     * Add an app to the temporary whitelist for a short amount of time for a specific reason. The
-     * temporary whitelist is kept separately from the permanent whitelist and apps are
-     * automatically removed from the temporary whitelist after a predetermined amount of time.
+     * Add an app to the temporary allowlist for a short amount of time for a specific reason. The
+     * temporary allowlist is kept separately from the permanent allowlist and apps are
+     * automatically removed from the temporary allowlist after a predetermined amount of time.
      *
-     * @param packageName The package to add to the temp whitelist
-     * @param event       The reason to add the app to the temp whitelist
-     * @param reason      A human-readable reason explaining why the app is temp whitelisted. Only
+     * @param packageName The package to add to the temp allowlist
+     * @param event       The reason to add the app to the temp allowlist
+     * @param reason      A human-readable reason explaining why the app is temp allowlisted. Only
      *                    used for logging purposes. Could be null or empty string.
-     * @return The duration (in milliseconds) that the app is whitelisted for
+     * @return The duration (in milliseconds) that the app is allowlisted for
      * @deprecated Use {@link PowerExemptionManager#addToTemporaryAllowListForEvent(
      *             String, int, String, int)} instead
      */
@@ -499,16 +499,16 @@
     }
 
     /**
-     * Add an app to the temporary whitelist for a short amount of time for a specific reason. The
-     * temporary whitelist is kept separately from the permanent whitelist and apps are
-     * automatically removed from the temporary whitelist after a predetermined amount of time.
+     * Add an app to the temporary allowlist for a short amount of time for a specific reason. The
+     * temporary allowlist is kept separately from the permanent allowlist and apps are
+     * automatically removed from the temporary allowlist after a predetermined amount of time.
      *
-     * @param packageName The package to add to the temp whitelist
-     * @param event       The reason to add the app to the temp whitelist
+     * @param packageName The package to add to the temp allowlist
+     * @param event       The reason to add the app to the temp allowlist
      * @param reasonCode  one of {@link ReasonCode}, use {@link #REASON_UNKNOWN} if not sure.
-     * @param reason      A human-readable reason explaining why the app is temp whitelisted. Only
+     * @param reason      A human-readable reason explaining why the app is temp allowlisted. Only
      *                    used for logging purposes. Could be null or empty string.
-     * @return The duration (in milliseconds) that the app is whitelisted for
+     * @return The duration (in milliseconds) that the app is allowlisted for
      * @deprecated Use {@link PowerExemptionManager#addToTemporaryAllowListForEvent(
      *             String, int, String, int)} instead
      */
diff --git a/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java b/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java
index 3424651..012da85 100644
--- a/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java
+++ b/apex/jobscheduler/service/java/com/android/server/alarm/AlarmManagerService.java
@@ -713,7 +713,7 @@
         private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
         private static final long DEFAULT_MAX_INTERVAL = 365 * INTERVAL_DAY;
         private static final long DEFAULT_MIN_WINDOW = 10 * 60 * 1000;
-        private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10 * 1000;
+        private static final long DEFAULT_ALLOW_WHILE_IDLE_ALLOWLIST_DURATION = 10 * 1000;
         private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
         private static final int DEFAULT_MAX_ALARMS_PER_UID = 500;
         private static final long DEFAULT_APP_STANDBY_WINDOW = 60 * 60 * 1000;  // 1 hr
@@ -768,7 +768,7 @@
 
         // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
         public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
-                = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
+                = DEFAULT_ALLOW_WHILE_IDLE_ALLOWLIST_DURATION;
 
         // Direct alarm listener callback timeout
         public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
@@ -970,7 +970,7 @@
                         case KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION:
                             ALLOW_WHILE_IDLE_WHITELIST_DURATION = properties.getLong(
                                     KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
-                                    DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
+                                    DEFAULT_ALLOW_WHILE_IDLE_ALLOWLIST_DURATION);
                             updateAllowWhileIdleWhitelistDurationLocked();
                             break;
                         case KEY_LISTENER_TIMEOUT:
@@ -1593,7 +1593,7 @@
      * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
      * restricted.
      *
-     * This is only called when the power save whitelist changes, so it's okay to be slow.
+     * This is only called when the power save allowlist changes, so it's okay to be slow.
      */
     @GuardedBy("mLock")
     void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
@@ -2235,7 +2235,7 @@
             }
         }
 
-        // Sanity check the recurrence interval.  This will catch people who supply
+        // Validate the recurrence interval.  This will catch people who supply
         // seconds when the API expects milliseconds, or apps trying shenanigans
         // around intentional period overflow, etc.
         final long minInterval = mConstants.MIN_INTERVAL;
diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobServiceContext.java b/apex/jobscheduler/service/java/com/android/server/job/JobServiceContext.java
index 58953c4..2994cf2 100644
--- a/apex/jobscheduler/service/java/com/android/server/job/JobServiceContext.java
+++ b/apex/jobscheduler/service/java/com/android/server/job/JobServiceContext.java
@@ -331,6 +331,7 @@
                 if (DEBUG) {
                     Slog.d(TAG, job.getServiceComponent().getShortClassName() + " unavailable.");
                 }
+                mContext.unbindService(this);
                 mRunningJob = null;
                 mRunningJobWorkType = WORK_TYPE_NONE;
                 mRunningCallback = null;
diff --git a/apex/jobscheduler/service/java/com/android/server/usage/AppIdleHistory.java b/apex/jobscheduler/service/java/com/android/server/usage/AppIdleHistory.java
index fb342b9..913a76a 100644
--- a/apex/jobscheduler/service/java/com/android/server/usage/AppIdleHistory.java
+++ b/apex/jobscheduler/service/java/com/android/server/usage/AppIdleHistory.java
@@ -61,6 +61,7 @@
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.IOException;
@@ -802,6 +803,9 @@
                     }
                 }
             }
+        } catch (FileNotFoundException e) {
+            // Expected on first boot
+            Slog.d(TAG, "App idle file for user " + userId + " does not exist");
         } catch (IOException | XmlPullParserException e) {
             Slog.e(TAG, "Unable to read app idle file for user " + userId, e);
         } finally {
diff --git a/api/Android.bp b/api/Android.bp
index f40f0c9..4f14c377 100644
--- a/api/Android.bp
+++ b/api/Android.bp
@@ -60,14 +60,14 @@
 metalava_cmd = "$(location metalava)"
 // Silence reflection warnings. See b/168689341
 metalava_cmd += " -J--add-opens=java.base/java.util=ALL-UNNAMED "
-metalava_cmd += " --quiet --no-banner --format=v2 "
+metalava_cmd += " --quiet "
 
 genrule {
     name: "current-api-xml",
     tools: ["metalava"],
     srcs: [":frameworks-base-api-current.txt"],
     out: ["current.api"],
-    cmd: metalava_cmd + "-convert2xmlnostrip $(in) $(out)",
+    cmd: metalava_cmd + "signature-to-jdiff $(in) $(out)",
     visibility: ["//visibility:public"],
 }
 
@@ -86,6 +86,7 @@
         "framework-media",
         "framework-mediaprovider",
         "framework-ondevicepersonalization",
+        "framework-pdf",
         "framework-permission",
         "framework-permission-s",
         "framework-scheduling",
diff --git a/api/OWNERS b/api/OWNERS
index bf6216c..965093c 100644
--- a/api/OWNERS
+++ b/api/OWNERS
@@ -3,7 +3,10 @@
 # Modularization team
 file:platform/packages/modules/common:/OWNERS
 
+# Soong plugin owned by Soong team.
+per-file *.go,go.mod,go.work,go.work.sum = file:platform/build/soong:/OWNERS
+
 per-file Android.bp = file:platform/build/soong:/OWNERS #{LAST_RESORT_SUGGESTION}
 
 # For metalava team to disable lint checks in platform
-per-file Android.bp = aurimas@google.com,emberrose@google.com,sjgilbert@google.com
+per-file Android.bp = aurimas@google.com,emberrose@google.com
diff --git a/api/StubLibraries.bp b/api/StubLibraries.bp
index 9a0053f..180a41c 100644
--- a/api/StubLibraries.bp
+++ b/api/StubLibraries.bp
@@ -29,6 +29,9 @@
 
 droidstubs {
     name: "api-stubs-docs-non-updatable",
+    srcs: [
+        ":framework-minus-apex-aconfig-srcjars",
+    ],
     defaults: [
         "android-non-updatable-stubs-defaults",
         "module-classpath-stubs-defaults",
@@ -63,6 +66,7 @@
             tag: ".removed-api.txt",
         },
     ],
+    api_surface: "public",
 }
 
 priv_apps = " --show-annotation android.annotation.SystemApi\\(" +
@@ -81,6 +85,9 @@
 
 droidstubs {
     name: "system-api-stubs-docs-non-updatable",
+    srcs: [
+        ":framework-minus-apex-aconfig-srcjars",
+    ],
     defaults: [
         "android-non-updatable-stubs-defaults",
         "module-classpath-stubs-defaults",
@@ -116,10 +123,14 @@
             tag: ".removed-api.txt",
         },
     ],
+    api_surface: "system",
 }
 
 droidstubs {
     name: "test-api-stubs-docs-non-updatable",
+    srcs: [
+        ":framework-minus-apex-aconfig-srcjars",
+    ],
     defaults: [
         "android-non-updatable-stubs-defaults",
         "module-classpath-stubs-defaults",
@@ -161,10 +172,14 @@
             tag: ".removed-api.txt",
         },
     ],
+    api_surface: "test",
 }
 
 droidstubs {
     name: "module-lib-api-stubs-docs-non-updatable",
+    srcs: [
+        ":framework-minus-apex-aconfig-srcjars",
+    ],
     defaults: [
         "android-non-updatable-stubs-defaults",
         "module-classpath-stubs-defaults",
@@ -200,6 +215,7 @@
             tag: ".removed-api.txt",
         },
     ],
+    api_surface: "module-lib",
 }
 
 /////////////////////////////////////////////////////////////////////
@@ -341,13 +357,15 @@
     ],
     srcs: [":module-lib-api-stubs-docs-non-updatable"],
     libs: [
+        // We cannot depend on all-modules-module-lib-stubs, because the module-lib stubs
+        // depend on this stub. We resolve dependencies on APIs in modules by depending
+        // on a prebuilt of the whole platform (sdk_system_current_android).
+        // That prebuilt does not include module-lib APIs, so use the prebuilt module-lib
+        // stubs for modules that export module-lib stubs that the non-updatable part
+        // depends on.
         "sdk_module-lib_current_framework-tethering",
         "sdk_module-lib_current_framework-connectivity-t",
-        "sdk_public_current_framework-bluetooth",
-        // NOTE: The below can be removed once the prebuilt stub contains bluetooth.
         "sdk_system_current_android",
-        // NOTE: The below can be removed once the prebuilt stub contains IKE.
-        "sdk_system_current_android.net.ipsec.ike",
     ],
     dist: {
         dir: "apistubs/android/module-lib",
@@ -376,8 +394,8 @@
 java_api_library {
     name: "android-non-updatable.stubs.from-text",
     api_surface: "public",
-    api_files: [
-        ":non-updatable-current.txt",
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
     ],
     defaults: ["android-non-updatable_from_text_defaults"],
     full_api_surface_stub: "android_stubs_current.from-text",
@@ -386,9 +404,9 @@
 java_api_library {
     name: "android-non-updatable.stubs.system.from-text",
     api_surface: "system",
-    api_files: [
-        ":non-updatable-current.txt",
-        ":non-updatable-system-current.txt",
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
     ],
     defaults: ["android-non-updatable_from_text_defaults"],
     full_api_surface_stub: "android_system_stubs_current.from-text",
@@ -397,10 +415,10 @@
 java_api_library {
     name: "android-non-updatable.stubs.test.from-text",
     api_surface: "test",
-    api_files: [
-        ":non-updatable-current.txt",
-        ":non-updatable-system-current.txt",
-        ":non-updatable-test-current.txt",
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+        "test-api-stubs-docs-non-updatable.api.contribution",
     ],
     defaults: ["android-non-updatable_from_text_defaults"],
     full_api_surface_stub: "android_test_stubs_current.from-text",
@@ -409,10 +427,10 @@
 java_api_library {
     name: "android-non-updatable.stubs.module_lib.from-text",
     api_surface: "module_lib",
-    api_files: [
-        ":non-updatable-current.txt",
-        ":non-updatable-system-current.txt",
-        ":non-updatable-module-lib-current.txt",
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+        "module-lib-api-stubs-docs-non-updatable.api.contribution",
     ],
     defaults: ["android-non-updatable_from_text_defaults"],
     full_api_surface_stub: "android_module_lib_stubs_current_full.from-text",
@@ -572,6 +590,147 @@
     },
 }
 
+//
+// Java API defaults and libraries for single tree build
+//
+
+java_defaults {
+    name: "stub-annotation-defaults",
+    libs: [
+        "stub-annotations",
+    ],
+    static_libs: [
+        // stub annotations do not contribute to the API surfaces but are statically
+        // linked in the stubs for API surfaces (see frameworks/base/StubLibraries.bp).
+        // This is because annotation processors insist on loading the classes for any
+        // annotations found, thus should exist inside android.jar.
+        "private-stub-annotations-jar",
+    ],
+}
+
+// Listing of API domains contribution and dependencies per API surfaces
+java_defaults {
+    name: "android_test_stubs_current_contributions",
+    api_surface: "test",
+    api_contributions: [
+        "framework-virtualization.stubs.source.test.api.contribution",
+    ],
+}
+
+java_defaults {
+    name: "android_module_lib_stubs_current_contributions",
+    api_surface: "module-lib",
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+        "module-lib-api-stubs-docs-non-updatable.api.contribution",
+        "art.module.public.api.stubs.source.api.contribution",
+        "art.module.public.api.stubs.source.system.api.contribution",
+        "art.module.public.api.stubs.source.module_lib.api.contribution",
+        "i18n.module.public.api.stubs.source.api.contribution",
+        "i18n.module.public.api.stubs.source.system.api.contribution",
+        "i18n.module.public.api.stubs.source.module_lib.api.contribution",
+    ],
+}
+
+// Java API library definitions per API surface
+java_api_library {
+    name: "android_stubs_current.from-text",
+    api_surface: "public",
+    defaults: [
+        // This module is dynamically created at frameworks/base/api/api.go
+        // instead of being written out, in order to minimize edits in the codebase
+        // when there is a change in the list of modules.
+        // that contributes to an api surface.
+        "android_stubs_current_contributions",
+        "stub-annotation-defaults",
+    ],
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_system_stubs_current.from-text",
+    api_surface: "system",
+    defaults: [
+        "android_stubs_current_contributions",
+        "android_system_stubs_current_contributions",
+        "stub-annotation-defaults",
+    ],
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_test_stubs_current.from-text",
+    api_surface: "test",
+    defaults: [
+        "android_stubs_current_contributions",
+        "android_system_stubs_current_contributions",
+        "android_test_stubs_current_contributions",
+        "stub-annotation-defaults",
+    ],
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+        "test-api-stubs-docs-non-updatable.api.contribution",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_module_lib_stubs_current_full.from-text",
+    api_surface: "module-lib",
+    defaults: [
+        "android_stubs_current_contributions",
+        "android_system_stubs_current_contributions",
+        "android_module_lib_stubs_current_contributions_full",
+    ],
+    libs: [
+        "stub-annotations",
+    ],
+    api_contributions: [
+        "api-stubs-docs-non-updatable.api.contribution",
+        "system-api-stubs-docs-non-updatable.api.contribution",
+        "module-lib-api-stubs-docs-non-updatable.api.contribution",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_module_lib_stubs_current.from-text",
+    api_surface: "module-lib",
+    defaults: [
+        "android_module_lib_stubs_current_contributions",
+    ],
+    libs: [
+        "android_module_lib_stubs_current_full.from-text",
+        "stub-annotations",
+    ],
+    visibility: ["//visibility:public"],
+}
+
+java_api_library {
+    name: "android_system_server_stubs_current.from-text",
+    api_surface: "system-server",
+    api_contributions: [
+        "services-non-updatable-stubs.api.contribution",
+    ],
+    libs: [
+        "android_module_lib_stubs_current.from-text",
+        "stub-annotations",
+    ],
+    static_libs: [
+        "android_module_lib_stubs_current.from-text",
+    ],
+    visibility: ["//visibility:public"],
+}
+
 ////////////////////////////////////////////////////////////////////////
 // api-versions.xml generation, for public and system. This API database
 // also contains the android.test.* APIs.
diff --git a/api/api.go b/api/api.go
index c568a45..431d6d8 100644
--- a/api/api.go
+++ b/api/api.go
@@ -110,6 +110,7 @@
 	Api_surface         *string
 	Api_contributions   []string
 	Defaults_visibility []string
+	Previous_api        *string
 }
 
 type Bazel_module struct {
@@ -145,7 +146,7 @@
 	metalavaCmd := "$(location metalava)"
 	// Silence reflection warnings. See b/168689341
 	metalavaCmd += " -J--add-opens=java.base/java.util=ALL-UNNAMED "
-	metalavaCmd += " --quiet --no-banner --format=v2 "
+	metalavaCmd += " --quiet merge-signatures --format=v2 "
 
 	filename := txt.TxtFilename
 	if txt.Scope != "public" {
@@ -155,7 +156,7 @@
 	props.Name = proptools.StringPtr(ctx.ModuleName() + "-" + filename)
 	props.Tools = []string{"metalava"}
 	props.Out = []string{filename}
-	props.Cmd = proptools.StringPtr(metalavaCmd + "$(in) --api $(out)")
+	props.Cmd = proptools.StringPtr(metalavaCmd + "$(in) --out $(out)")
 	props.Srcs = append([]string{txt.BaseTxt}, createSrcs(txt.Modules, txt.ModuleTag)...)
 	props.Dists = []android.Dist{
 		{
@@ -359,6 +360,7 @@
 		props.Api_contributions = transformArray(
 			modules, "", fmt.Sprintf(".stubs.source%s.api.contribution", apiSuffix))
 		props.Defaults_visibility = []string{"//visibility:public"}
+		props.Previous_api = proptools.StringPtr(":android.api.public.latest")
 		ctx.CreateModule(java.DefaultsFactory, &props)
 	}
 }
@@ -427,7 +429,7 @@
 }
 
 // combined_apis bp2build converter
-func (a *CombinedApis) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
+func (a *CombinedApis) ConvertWithBp2build(ctx android.Bp2buildMutatorContext) {
 	basePrefix := "non-updatable"
 	scopeToSuffix := map[string]string{
 		"public":        "-current.txt",
diff --git a/api/gen_combined_removed_dex.sh b/api/gen_combined_removed_dex.sh
index 9225fe8..71f366a 100755
--- a/api/gen_combined_removed_dex.sh
+++ b/api/gen_combined_removed_dex.sh
@@ -6,6 +6,6 @@
 
 # Convert each removed.txt to the "dex format" equivalent, and print all output.
 for f in "$@"; do
-    "$metalava_path" --no-banner "$f" --dex-api "${tmp_dir}/tmp"
+    "$metalava_path" "$f" --dex-api "${tmp_dir}/tmp"
     cat "${tmp_dir}/tmp"
 done
diff --git a/api/go.mod b/api/go.mod
new file mode 100644
index 0000000..f8bb1c0
--- /dev/null
+++ b/api/go.mod
@@ -0,0 +1,12 @@
+module android/soong/aidl
+
+go 1.18
+
+require (
+	android/soong v0.0.0
+	github.com/google/blueprint v0.0.0
+	google.golang.org/protobuf v0.0.0
+	prebuilts/bazel/common/proto/analysis_v2 v0.0.0
+	prebuilts/bazel/common/proto/build v0.0.0
+	go.starlark.net v0.0.0
+)
diff --git a/api/go.work b/api/go.work
new file mode 100644
index 0000000..aa2d2b1
--- /dev/null
+++ b/api/go.work
@@ -0,0 +1,19 @@
+go 1.18
+
+use (
+	.
+	../../../build/soong
+	../../../build/blueprint
+	../../../external/go-cmp
+	../../../external/golang-protobuf
+)
+
+replace (
+	android/soong v0.0.0 => ../../../build/soong
+	google.golang.org/protobuf v0.0.0 => ../../../external/golang-protobuf
+	github.com/google/blueprint v0.0.0 => ../../../build/blueprint
+	github.com/google/go-cmp v0.0.0 => ../../../external/go-cmp
+	prebuilts/bazel/common/proto/analysis_v2 v0.0.0 => ../../../prebuilts/bazel/common/proto/analysis_v2
+	prebuilts/bazel/common/proto/build v0.0.0 => ../../../prebuilts/bazel/common/proto/build
+	go.starlark.net v0.0.0 => ../../../external/starlark-go
+)
diff --git a/api/go.work.sum b/api/go.work.sum
new file mode 100644
index 0000000..d00184f
--- /dev/null
+++ b/api/go.work.sum
@@ -0,0 +1,66 @@
+cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
+github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
+github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
+github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
+github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
+github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
+github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
+github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
+github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
+github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
+github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
+github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
+github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
+github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
+github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
+github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
+github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
+github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
+github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
+golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
+golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
+golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
+golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
+golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
+golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
+golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
+google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
+google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
+google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
+google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
+google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
+google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
+google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
+google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
+google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
+google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
+google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
+google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
+google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
+google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
+google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
+honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
diff --git a/boot/Android.bp b/boot/Android.bp
index 851294c..6b90f10 100644
--- a/boot/Android.bp
+++ b/boot/Android.bp
@@ -192,6 +192,13 @@
     ],
 }
 
+genrule { // This module exists to make the srcjar output available to Make.
+    name: "platform-bootclasspath.srcjar",
+    srcs: [":platform-bootclasspath{.srcjar}"],
+    out: ["platform-bootclasspath.srcjar"],
+    cmd: "cp $(in) $(out)",
+}
+
 platform_systemserverclasspath {
     name: "platform-systemserverclasspath",
 }
diff --git a/cmds/app_process/app_main.cpp b/cmds/app_process/app_main.cpp
index 28db61f..4e41f2c 100644
--- a/cmds/app_process/app_main.cpp
+++ b/cmds/app_process/app_main.cpp
@@ -49,7 +49,7 @@
 
     virtual void onVmCreated(JNIEnv* env)
     {
-        if (mClassName.isEmpty()) {
+        if (mClassName.empty()) {
             return; // Zygote. Nothing to do here.
         }
 
@@ -66,10 +66,10 @@
          * executing boot class Java code and thereby deny ourselves access to
          * non-boot classes.
          */
-        char* slashClassName = toSlashClassName(mClassName.string());
+        char* slashClassName = toSlashClassName(mClassName.c_str());
         mClass = env->FindClass(slashClassName);
         if (mClass == NULL) {
-            ALOGE("ERROR: could not find class '%s'\n", mClassName.string());
+            ALOGE("ERROR: could not find class '%s'\n", mClassName.c_str());
         }
         free(slashClassName);
 
@@ -98,7 +98,7 @@
 
     virtual void onExit(int code)
     {
-        if (mClassName.isEmpty()) {
+        if (mClassName.empty()) {
             // if zygote
             IPCThreadState::self()->stopProcess();
             hardware::IPCThreadState::self()->stopProcess();
@@ -179,7 +179,7 @@
         argv_String.append(argv[i]);
         argv_String.append("\" ");
       }
-      ALOGV("app_process main with argv: %s", argv_String.string());
+      ALOGV("app_process main with argv: %s", argv_String.c_str());
     }
 
     AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
@@ -271,9 +271,9 @@
         } else if (strcmp(arg, "--application") == 0) {
             application = true;
         } else if (strncmp(arg, "--nice-name=", 12) == 0) {
-            niceName.setTo(arg + 12);
+            niceName = (arg + 12);
         } else if (strncmp(arg, "--", 2) != 0) {
-            className.setTo(arg);
+            className = arg;
             break;
         } else {
             --i;
@@ -282,7 +282,7 @@
     }
 
     Vector<String8> args;
-    if (!className.isEmpty()) {
+    if (!className.empty()) {
         // We're not in zygote mode, the only argument we need to pass
         // to RuntimeInit is the application argument.
         //
@@ -300,7 +300,7 @@
             restOfArgs.append(argv_new[k]);
             restOfArgs.append("\" ");
           }
-          ALOGV("Class name = %s, args = %s", className.string(), restOfArgs.string());
+          ALOGV("Class name = %s, args = %s", className.c_str(), restOfArgs.c_str());
         }
     } else {
         // We're in zygote mode.
@@ -328,13 +328,13 @@
         }
     }
 
-    if (!niceName.isEmpty()) {
-        runtime.setArgv0(niceName.string(), true /* setProcName */);
+    if (!niceName.empty()) {
+        runtime.setArgv0(niceName.c_str(), true /* setProcName */);
     }
 
     if (zygote) {
         runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
-    } else if (!className.isEmpty()) {
+    } else if (!className.empty()) {
         runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
     } else {
         fprintf(stderr, "Error: no class name or --zygote supplied.\n");
diff --git a/cmds/backup/backup.cpp b/cmds/backup/backup.cpp
index 8d9b528..c2ce690 100644
--- a/cmds/backup/backup.cpp
+++ b/cmds/backup/backup.cpp
@@ -75,7 +75,7 @@
                 size_t dataSize;
                 err = reader.ReadEntityHeader(&key, &dataSize);
                 if (err == 0) {
-                    printf("   entity: %s (%zu bytes)\n", key.string(), dataSize);
+                    printf("   entity: %s (%zu bytes)\n", key.c_str(), dataSize);
                 } else {
                     printf("   Error reading entity header\n");
                 }
diff --git a/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java b/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
index ed717c4..81be44a 100644
--- a/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
+++ b/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
@@ -191,7 +191,7 @@
         }
 
         if ("whitelist".equals(op)) {
-            doPrintWhitelist();
+            doPrintAllowlist();
             return;
         }
 
@@ -873,7 +873,7 @@
         }
     }
 
-    private void doPrintWhitelist() {
+    private void doPrintAllowlist() {
         try {
             final String[] whitelist = mBmgr.getTransportWhitelist();
             if (whitelist != null) {
diff --git a/cmds/bootanimation/Android.bp b/cmds/bootanimation/Android.bp
index 3534624..98767ee 100644
--- a/cmds/bootanimation/Android.bp
+++ b/cmds/bootanimation/Android.bp
@@ -74,4 +74,7 @@
         "libGLESv2",
         "libgui",
     ],
+    whole_static_libs: [
+        "libc++fs",
+    ],
 }
diff --git a/cmds/bootanimation/BootAnimation.cpp b/cmds/bootanimation/BootAnimation.cpp
index 27dadda..0ed47e7 100644
--- a/cmds/bootanimation/BootAnimation.cpp
+++ b/cmds/bootanimation/BootAnimation.cpp
@@ -17,6 +17,7 @@
 #define LOG_NDEBUG 0
 #define LOG_TAG "BootAnimation"
 
+#include <filesystem>
 #include <vector>
 
 #include <stdint.h>
@@ -690,7 +691,7 @@
 
 bool BootAnimation::preloadAnimation() {
     findBootAnimationFile();
-    if (!mZipFileName.isEmpty()) {
+    if (!mZipFileName.empty()) {
         mAnimation = loadAnimation(mZipFileName);
         return (mAnimation != nullptr);
     }
@@ -820,7 +821,7 @@
 
     // We have no bootanimation file, so we use the stock android logo
     // animation.
-    if (mZipFileName.isEmpty()) {
+    if (mZipFileName.empty()) {
         ALOGD("No animation file");
         result = android();
     } else {
@@ -1011,7 +1012,7 @@
         return false;
     }
 
-    outString.setTo((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
+    outString = String8((char const*)entryMap->getDataPtr(), entryMap->getDataLength());
     delete entryMap;
     return true;
 }
@@ -1136,7 +1137,7 @@
     if (!readFile(animation.zip, "desc.txt", desString)) {
         return false;
     }
-    char const* s = desString.string();
+    char const* s = desString.c_str();
     std::string dynamicColoringPartName = "";
     bool postDynamicColoring = false;
 
@@ -1145,7 +1146,7 @@
         const char* endl = strstr(s, "\n");
         if (endl == nullptr) break;
         String8 line(s, endl - s);
-        const char* l = line.string();
+        const char* l = line.c_str();
         int fps = 0;
         int width = 0;
         int height = 0;
@@ -1271,10 +1272,10 @@
             continue;
         }
 
-        const String8 entryName(name);
-        const String8 path(entryName.getPathDir());
-        const String8 leaf(entryName.getPathLeaf());
-        if (leaf.size() > 0) {
+        const std::filesystem::path entryName(name);
+        const std::filesystem::path path(entryName.parent_path());
+        const std::filesystem::path leaf(entryName.filename());
+        if (!leaf.empty()) {
             if (entryName == CLOCK_FONT_ZIP_NAME) {
                 FileMap* map = zip->createEntryFileMap(entry);
                 if (map) {
@@ -1292,7 +1293,7 @@
             }
 
             for (size_t j = 0; j < pcount; j++) {
-                if (path == animation.parts[j].path) {
+                if (path.string() == animation.parts[j].path.c_str()) {
                     uint16_t method;
                     // supports only stored png files
                     if (zip->getEntryInfo(entry, &method, nullptr, nullptr, nullptr, nullptr, nullptr)) {
@@ -1305,11 +1306,11 @@
                                     part.audioData = (uint8_t *)map->getDataPtr();
                                     part.audioLength = map->getDataLength();
                                 } else if (leaf == "trim.txt") {
-                                    part.trimData.setTo((char const*)map->getDataPtr(),
+                                    part.trimData = String8((char const*)map->getDataPtr(),
                                                         map->getDataLength());
                                 } else {
                                     Animation::Frame frame;
-                                    frame.name = leaf;
+                                    frame.name = leaf.c_str();
                                     frame.map = map;
                                     frame.trimWidth = animation.width;
                                     frame.trimHeight = animation.height;
@@ -1329,7 +1330,7 @@
 
     // If there is trimData present, override the positioning defaults.
     for (Animation::Part& part : animation.parts) {
-        const char* trimDataStr = part.trimData.string();
+        const char* trimDataStr = part.trimData.c_str();
         for (size_t frameIdx = 0; frameIdx < part.frames.size(); frameIdx++) {
             const char* endl = strstr(trimDataStr, "\n");
             // No more trimData for this part.
@@ -1337,7 +1338,7 @@
                 break;
             }
             String8 line(trimDataStr, endl - trimDataStr);
-            const char* lineStr = line.string();
+            const char* lineStr = line.c_str();
             trimDataStr = ++endl;
             int width = 0, height = 0, x = 0, y = 0;
             if (sscanf(lineStr, "%dx%d+%d+%d", &width, &height, &x, &y) == 4) {
@@ -1395,7 +1396,7 @@
     if (!exts) {
         glGetError();
     } else {
-        gl_extensions.setTo(exts);
+        gl_extensions = exts;
         if ((gl_extensions.find("GL_ARB_texture_non_power_of_two") != -1) ||
             (gl_extensions.find("GL_OES_texture_npot") != -1)) {
             mUseNpotTextures = true;
@@ -1525,6 +1526,7 @@
     for (size_t i=0 ; i<pcount ; i++) {
         const Animation::Part& part(animation.parts[i]);
         const size_t fcount = part.frames.size();
+        glBindTexture(GL_TEXTURE_2D, 0);
 
         // Handle animation package
         if (part.animation != nullptr) {
@@ -1564,7 +1566,7 @@
                     1.0f);
 
             ALOGD("Playing files = %s/%s, Requested repeat = %d, playUntilComplete = %s",
-                    animation.fileName.string(), part.path.string(), part.count,
+                    animation.fileName.c_str(), part.path.c_str(), part.count,
                     part.playUntilComplete ? "true" : "false");
 
             // For the last animation, if we have progress indicator from
@@ -1601,8 +1603,10 @@
                 if (r > 0) {
                     glBindTexture(GL_TEXTURE_2D, frame.tid);
                 } else {
-                    glGenTextures(1, &frame.tid);
-                    glBindTexture(GL_TEXTURE_2D, frame.tid);
+                    if (part.count != 1) {
+                        glGenTextures(1, &frame.tid);
+                        glBindTexture(GL_TEXTURE_2D, frame.tid);
+                    }
                     int w, h;
                     // Set decoding option to alpha unpremultiplied so that the R, G, B channels
                     // of transparent pixels are preserved.
@@ -1783,17 +1787,17 @@
 BootAnimation::Animation* BootAnimation::loadAnimation(const String8& fn) {
     if (mLoadedFiles.indexOf(fn) >= 0) {
         SLOGE("File \"%s\" is already loaded. Cyclic ref is not allowed",
-            fn.string());
+            fn.c_str());
         return nullptr;
     }
-    ZipFileRO *zip = ZipFileRO::open(fn);
+    ZipFileRO *zip = ZipFileRO::open(fn.c_str());
     if (zip == nullptr) {
         SLOGE("Failed to open animation zip \"%s\": %s",
-            fn.string(), strerror(errno));
+            fn.c_str(), strerror(errno));
         return nullptr;
     }
 
-    ALOGD("%s is loaded successfully", fn.string());
+    ALOGD("%s is loaded successfully", fn.c_str());
 
     Animation *animation =  new Animation;
     animation->fileName = fn;
diff --git a/cmds/idmap2/idmap2/Lookup.cpp b/cmds/idmap2/idmap2/Lookup.cpp
index f41e57c..0862fbe 100644
--- a/cmds/idmap2/idmap2/Lookup.cpp
+++ b/cmds/idmap2/idmap2/Lookup.cpp
@@ -94,7 +94,7 @@
       const ResStringPool* pool = am->GetStringPoolForCookie(value.cookie);
       out->append("\"");
       if (auto str = pool->string8ObjectAt(value.data); str.ok()) {
-        out->append(*str);
+        out->append(str->c_str());
       }
     } break;
     default:
diff --git a/cmds/idmap2/libidmap2/CommandLineOptions.cpp b/cmds/idmap2/libidmap2/CommandLineOptions.cpp
index 8129d99..b1edc18 100644
--- a/cmds/idmap2/libidmap2/CommandLineOptions.cpp
+++ b/cmds/idmap2/libidmap2/CommandLineOptions.cpp
@@ -20,6 +20,7 @@
 #include <cassert>
 #include <iomanip>
 #include <iostream>
+#include <iterator>
 #include <memory>
 #include <set>
 #include <sstream>
diff --git a/cmds/idmap2/libidmap2/XmlParser.cpp b/cmds/idmap2/libidmap2/XmlParser.cpp
index 70822c8..f71e6b9 100644
--- a/cmds/idmap2/libidmap2/XmlParser.cpp
+++ b/cmds/idmap2/libidmap2/XmlParser.cpp
@@ -111,7 +111,7 @@
   switch (value.dataType) {
     case Res_value::TYPE_STRING: {
       if (auto str = parser.getStrings().string8ObjectAt(value.data); str.ok()) {
-        return std::string(str->string());
+        return std::string(str->c_str());
       }
       break;
     }
diff --git a/cmds/incident/main.cpp b/cmds/incident/main.cpp
index 6e0bd06..0d9f4e9 100644
--- a/cmds/incident/main.cpp
+++ b/cmds/incident/main.cpp
@@ -83,8 +83,8 @@
 Status
 StatusListener::onReportServiceStatus(const String16& service, int32_t status)
 {
-    fprintf(stderr, "service '%s' status %d\n", String8(service).string(), status);
-    ALOGD("service '%s' status %d\n", String8(service).string(), status);
+    fprintf(stderr, "service '%s' status %d\n", String8(service).c_str(), status);
+    ALOGD("service '%s' status %d\n", String8(service).c_str(), status);
     return Status::ok();
 }
 
@@ -384,7 +384,7 @@
         status = service->reportIncidentToStream(args, listener, std::move(writeEnd));
 
         if (!status.isOk()) {
-            fprintf(stderr, "reportIncident returned \"%s\"\n", status.toString8().string());
+            fprintf(stderr, "reportIncident returned \"%s\"\n", status.toString8().c_str());
             return 1;
         }
 
@@ -396,14 +396,14 @@
         sp<StatusListener> listener(new StatusListener());
         status = service->reportIncidentToDumpstate(std::move(writeEnd), listener);
         if (!status.isOk()) {
-            fprintf(stderr, "reportIncident returned \"%s\"\n", status.toString8().string());
+            fprintf(stderr, "reportIncident returned \"%s\"\n", status.toString8().c_str());
             return 1;
         }
         return listener->getExitCodeOrElse(stream_output(fds[0], STDOUT_FILENO));
     } else {
         status = service->reportIncident(args);
         if (!status.isOk()) {
-            fprintf(stderr, "reportIncident returned \"%s\"\n", status.toString8().string());
+            fprintf(stderr, "reportIncident returned \"%s\"\n", status.toString8().c_str());
             return 1;
         } else {
             return 0;
diff --git a/cmds/incident_helper/src/TextParserBase.cpp b/cmds/incident_helper/src/TextParserBase.cpp
index e9bc70f..e625afa 100644
--- a/cmds/incident_helper/src/TextParserBase.cpp
+++ b/cmds/incident_helper/src/TextParserBase.cpp
@@ -27,11 +27,11 @@
 {
     string content;
     if (!ReadFdToString(in, &content)) {
-        fprintf(stderr, "[%s]Failed to read data from incidentd\n", this->name.string());
+        fprintf(stderr, "[%s]Failed to read data from incidentd\n", this->name.c_str());
         return -1;
     }
     if (!WriteStringToFd(content, out)) {
-        fprintf(stderr, "[%s]Failed to write data to incidentd\n", this->name.string());
+        fprintf(stderr, "[%s]Failed to write data to incidentd\n", this->name.c_str());
         return -1;
     }
     return NO_ERROR;
@@ -42,13 +42,13 @@
 {
     string content;
     if (!ReadFdToString(in, &content)) {
-        fprintf(stderr, "[%s]Failed to read data from incidentd\n", this->name.string());
+        fprintf(stderr, "[%s]Failed to read data from incidentd\n", this->name.c_str());
         return -1;
     }
     // reverse the content
     reverse(content.begin(), content.end());
     if (!WriteStringToFd(content, out)) {
-        fprintf(stderr, "[%s]Failed to write data to incidentd\n", this->name.string());
+        fprintf(stderr, "[%s]Failed to write data to incidentd\n", this->name.c_str());
         return -1;
     }
     return NO_ERROR;
diff --git a/cmds/incident_helper/src/main.cpp b/cmds/incident_helper/src/main.cpp
index ff5fd86..cc03d4a 100644
--- a/cmds/incident_helper/src/main.cpp
+++ b/cmds/incident_helper/src/main.cpp
@@ -101,7 +101,7 @@
     fprintf(stderr, "Pasring section %d...\n", sectionID);
     TextParserBase* parser = selectParser(sectionID);
     if (parser != nullptr) {
-        fprintf(stderr, "Running parser: %s\n", parser->name.string());
+        fprintf(stderr, "Running parser: %s\n", parser->name.c_str());
         status_t err = parser->Parse(STDIN_FILENO, STDOUT_FILENO);
         if (err != NO_ERROR) {
             fprintf(stderr, "Parse error in section %d: %s\n", sectionID, strerror(-err));
diff --git a/cmds/incident_helper/src/parsers/BatteryTypeParser.cpp b/cmds/incident_helper/src/parsers/BatteryTypeParser.cpp
index ced6cf8..2a032fb 100644
--- a/cmds/incident_helper/src/parsers/BatteryTypeParser.cpp
+++ b/cmds/incident_helper/src/parsers/BatteryTypeParser.cpp
@@ -52,9 +52,9 @@
     }
 
     if (!proto.flush(out)) {
-        fprintf(stderr, "[%s]Error writing proto back\n", this->name.string());
+        fprintf(stderr, "[%s]Error writing proto back\n", this->name.c_str());
         return -1;
     }
-    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.string(), proto.size());
+    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.c_str(), proto.size());
     return NO_ERROR;
 }
diff --git a/cmds/incident_helper/src/parsers/CpuFreqParser.cpp b/cmds/incident_helper/src/parsers/CpuFreqParser.cpp
index 43a12f6..c9bf4c5 100644
--- a/cmds/incident_helper/src/parsers/CpuFreqParser.cpp
+++ b/cmds/incident_helper/src/parsers/CpuFreqParser.cpp
@@ -82,9 +82,9 @@
     }
 
     if (!proto.flush(out)) {
-        fprintf(stderr, "[%s]Error writing proto back\n", this->name.string());
+        fprintf(stderr, "[%s]Error writing proto back\n", this->name.c_str());
         return -1;
     }
-    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.string(), proto.size());
+    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.c_str(), proto.size());
     return NO_ERROR;
 }
diff --git a/cmds/incident_helper/src/parsers/CpuInfoParser.cpp b/cmds/incident_helper/src/parsers/CpuInfoParser.cpp
index 5d525e6..77751a2f 100644
--- a/cmds/incident_helper/src/parsers/CpuInfoParser.cpp
+++ b/cmds/incident_helper/src/parsers/CpuInfoParser.cpp
@@ -130,11 +130,11 @@
         record = parseRecordByColumns(line, columnIndices);
         diff = record.size() - header.size();
         if (diff < 0) {
-            fprintf(stderr, "[%s]Line %d has %d missing fields\n%s\n", this->name.string(), nline, -diff, line.c_str());
+            fprintf(stderr, "[%s]Line %d has %d missing fields\n%s\n", this->name.c_str(), nline, -diff, line.c_str());
             printRecord(record);
             continue;
         } else if (diff > 0) {
-            fprintf(stderr, "[%s]Line %d has %d extra fields\n%s\n", this->name.string(), nline, diff, line.c_str());
+            fprintf(stderr, "[%s]Line %d has %d extra fields\n%s\n", this->name.c_str(), nline, diff, line.c_str());
             printRecord(record);
             continue;
         }
@@ -143,7 +143,7 @@
         for (int i=0; i<(int)record.size(); i++) {
             if (!table.insertField(&proto, header[i], record[i])) {
                 fprintf(stderr, "[%s]Line %d fails to insert field %s with value %s\n",
-                        this->name.string(), nline, header[i].c_str(), record[i].c_str());
+                        this->name.c_str(), nline, header[i].c_str(), record[i].c_str());
             }
         }
         proto.end(token);
@@ -155,9 +155,9 @@
     }
 
     if (!proto.flush(out)) {
-        fprintf(stderr, "[%s]Error writing proto back\n", this->name.string());
+        fprintf(stderr, "[%s]Error writing proto back\n", this->name.c_str());
         return -1;
     }
-    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.string(), proto.size());
+    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.c_str(), proto.size());
     return NO_ERROR;
 }
diff --git a/cmds/incident_helper/src/parsers/EventLogTagsParser.cpp b/cmds/incident_helper/src/parsers/EventLogTagsParser.cpp
index 4fd6b06..0474a50 100644
--- a/cmds/incident_helper/src/parsers/EventLogTagsParser.cpp
+++ b/cmds/incident_helper/src/parsers/EventLogTagsParser.cpp
@@ -76,9 +76,9 @@
     }
 
     if (!proto.flush(out)) {
-        fprintf(stderr, "[%s]Error writing proto back\n", this->name.string());
+        fprintf(stderr, "[%s]Error writing proto back\n", this->name.c_str());
         return -1;
     }
-    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.string(), proto.size());
+    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.c_str(), proto.size());
     return NO_ERROR;
 }
diff --git a/cmds/incident_helper/src/parsers/KernelWakesParser.cpp b/cmds/incident_helper/src/parsers/KernelWakesParser.cpp
index 85beaf0..d16c23c 100644
--- a/cmds/incident_helper/src/parsers/KernelWakesParser.cpp
+++ b/cmds/incident_helper/src/parsers/KernelWakesParser.cpp
@@ -51,11 +51,11 @@
 
         if (record.size() < header.size()) {
             // TODO: log this to incident report!
-            fprintf(stderr, "[%s]Line %d has missing fields\n%s\n", this->name.string(), nline, line.c_str());
+            fprintf(stderr, "[%s]Line %d has missing fields\n%s\n", this->name.c_str(), nline, line.c_str());
             continue;
         } else if (record.size() > header.size()) {
             // TODO: log this to incident report!
-            fprintf(stderr, "[%s]Line %d has extra fields\n%s\n", this->name.string(), nline, line.c_str());
+            fprintf(stderr, "[%s]Line %d has extra fields\n%s\n", this->name.c_str(), nline, line.c_str());
             continue;
         }
 
@@ -63,7 +63,7 @@
         for (int i=0; i<(int)record.size(); i++) {
             if (!table.insertField(&proto, header[i], record[i])) {
                 fprintf(stderr, "[%s]Line %d has bad value %s of %s\n",
-                        this->name.string(), nline, header[i].c_str(), record[i].c_str());
+                        this->name.c_str(), nline, header[i].c_str(), record[i].c_str());
             }
         }
         proto.end(token);
@@ -75,9 +75,9 @@
     }
 
     if (!proto.flush(out)) {
-        fprintf(stderr, "[%s]Error writing proto back\n", this->name.string());
+        fprintf(stderr, "[%s]Error writing proto back\n", this->name.c_str());
         return -1;
     }
-    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.string(), proto.size());
+    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.c_str(), proto.size());
     return NO_ERROR;
 }
diff --git a/cmds/incident_helper/src/parsers/PageTypeInfoParser.cpp b/cmds/incident_helper/src/parsers/PageTypeInfoParser.cpp
index 2a89c920..36710df 100644
--- a/cmds/incident_helper/src/parsers/PageTypeInfoParser.cpp
+++ b/cmds/incident_helper/src/parsers/PageTypeInfoParser.cpp
@@ -114,10 +114,10 @@
     }
 
     if (!proto.flush(out)) {
-        fprintf(stderr, "[%s]Error writing proto back\n", this->name.string());
+        fprintf(stderr, "[%s]Error writing proto back\n", this->name.c_str());
         return -1;
     }
 
-    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.string(), proto.size());
+    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.c_str(), proto.size());
     return NO_ERROR;
 }
diff --git a/cmds/incident_helper/src/parsers/ProcrankParser.cpp b/cmds/incident_helper/src/parsers/ProcrankParser.cpp
index 4763b48..997d2e5 100644
--- a/cmds/incident_helper/src/parsers/ProcrankParser.cpp
+++ b/cmds/incident_helper/src/parsers/ProcrankParser.cpp
@@ -60,7 +60,7 @@
             if (record[record.size() - 1] == "TOTAL") { // TOTAL record
                 total = line;
             } else {
-                fprintf(stderr, "[%s]Line %d has missing fields\n%s\n", this->name.string(), nline,
+                fprintf(stderr, "[%s]Line %d has missing fields\n%s\n", this->name.c_str(), nline,
                     line.c_str());
             }
             continue;
@@ -70,7 +70,7 @@
         for (int i=0; i<(int)record.size(); i++) {
             if (!table.insertField(&proto, header[i], record[i])) {
                 fprintf(stderr, "[%s]Line %d has bad value %s of %s\n",
-                        this->name.string(), nline, header[i].c_str(), record[i].c_str());
+                        this->name.c_str(), nline, header[i].c_str(), record[i].c_str());
             }
         }
         proto.end(token);
@@ -104,9 +104,9 @@
     }
 
     if (!proto.flush(out)) {
-        fprintf(stderr, "[%s]Error writing proto back\n", this->name.string());
+        fprintf(stderr, "[%s]Error writing proto back\n", this->name.c_str());
         return -1;
     }
-    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.string(), proto.size());
+    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.c_str(), proto.size());
     return NO_ERROR;
 }
diff --git a/cmds/incident_helper/src/parsers/PsParser.cpp b/cmds/incident_helper/src/parsers/PsParser.cpp
index d3cb4be..55aa555 100644
--- a/cmds/incident_helper/src/parsers/PsParser.cpp
+++ b/cmds/incident_helper/src/parsers/PsParser.cpp
@@ -61,12 +61,12 @@
         diff = record.size() - header.size();
         if (diff < 0) {
             // TODO: log this to incident report!
-            fprintf(stderr, "[%s]Line %d has %d missing fields\n%s\n", this->name.string(), nline, -diff, line.c_str());
+            fprintf(stderr, "[%s]Line %d has %d missing fields\n%s\n", this->name.c_str(), nline, -diff, line.c_str());
             printRecord(record);
             continue;
         } else if (diff > 0) {
             // TODO: log this to incident report!
-            fprintf(stderr, "[%s]Line %d has %d extra fields\n%s\n", this->name.string(), nline, diff, line.c_str());
+            fprintf(stderr, "[%s]Line %d has %d extra fields\n%s\n", this->name.c_str(), nline, diff, line.c_str());
             printRecord(record);
             continue;
         }
@@ -75,7 +75,7 @@
         for (int i=0; i<(int)record.size(); i++) {
             if (!table.insertField(&proto, header[i], record[i])) {
                 fprintf(stderr, "[%s]Line %d has bad value %s of %s\n",
-                        this->name.string(), nline, header[i].c_str(), record[i].c_str());
+                        this->name.c_str(), nline, header[i].c_str(), record[i].c_str());
             }
         }
         proto.end(token);
@@ -87,9 +87,9 @@
     }
 
     if (!proto.flush(out)) {
-        fprintf(stderr, "[%s]Error writing proto back\n", this->name.string());
+        fprintf(stderr, "[%s]Error writing proto back\n", this->name.c_str());
         return -1;
     }
-    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.string(), proto.size());
+    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.c_str(), proto.size());
     return NO_ERROR;
 }
diff --git a/cmds/incident_helper/src/parsers/SystemPropertiesParser.cpp b/cmds/incident_helper/src/parsers/SystemPropertiesParser.cpp
index eba536b..86c34bc 100644
--- a/cmds/incident_helper/src/parsers/SystemPropertiesParser.cpp
+++ b/cmds/incident_helper/src/parsers/SystemPropertiesParser.cpp
@@ -219,9 +219,9 @@
     }
 
     if (!proto.flush(out)) {
-        fprintf(stderr, "[%s]Error writing proto back\n", this->name.string());
+        fprintf(stderr, "[%s]Error writing proto back\n", this->name.c_str());
         return -1;
     }
-    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.string(), proto.size());
+    fprintf(stderr, "[%s]Proto size: %zu bytes\n", this->name.c_str(), proto.size());
     return NO_ERROR;
 }
diff --git a/cmds/incidentd/src/IncidentService.cpp b/cmds/incidentd/src/IncidentService.cpp
index 05a43ad..82c8707 100644
--- a/cmds/incidentd/src/IncidentService.cpp
+++ b/cmds/incidentd/src/IncidentService.cpp
@@ -407,8 +407,8 @@
 Status IncidentService::getIncidentReportList(const String16& pkg16, const String16& cls16,
             vector<String16>* result) {
     status_t err;
-    const string pkg(String8(pkg16).string());
-    const string cls(String8(cls16).string());
+    const string pkg(String8(pkg16).c_str());
+    const string cls(String8(cls16).c_str());
 
     // List the reports
     vector<sp<ReportFile>> all;
@@ -441,9 +441,9 @@
             const String16& id16, IncidentManager::IncidentReport* result) {
     status_t err;
 
-    const string pkg(String8(pkg16).string());
-    const string cls(String8(cls16).string());
-    const string id(String8(id16).string());
+    const string pkg(String8(pkg16).c_str());
+    const string cls(String8(cls16).c_str());
+    const string id(String8(id16).c_str());
 
     IncidentReportArgs args;
     sp<ReportFile> file = mWorkDirectory->getReport(pkg, cls, id, &args);
@@ -470,9 +470,9 @@
 
 Status IncidentService::deleteIncidentReports(const String16& pkg16, const String16& cls16,
             const String16& id16) {
-    const string pkg(String8(pkg16).string());
-    const string cls(String8(cls16).string());
-    const string id(String8(id16).string());
+    const string pkg(String8(pkg16).c_str());
+    const string cls(String8(cls16).c_str());
+    const string id(String8(id16).c_str());
 
     sp<ReportFile> file = mWorkDirectory->getReport(pkg, cls, id, nullptr);
     if (file != nullptr) {
@@ -484,7 +484,7 @@
 }
 
 Status IncidentService::deleteAllIncidentReports(const String16& pkg16) {
-    const string pkg(String8(pkg16).string());
+    const string pkg(String8(pkg16).c_str());
 
     mWorkDirectory->commitAll(pkg);
     mBroadcaster->clearPackageBroadcasts(pkg);
@@ -563,12 +563,12 @@
                 fprintf(out, "Not enough arguments for section\n");
                 return NO_ERROR;
             }
-            int id = atoi(args[1]);
+            int id = atoi(args[1].c_str());
             int idx = 0;
             while (SECTION_LIST[idx] != NULL) {
                 const Section* section = SECTION_LIST[idx];
                 if (section->id == id) {
-                    fprintf(out, "Section[%d] %s\n", id, section->name.string());
+                    fprintf(out, "Section[%d] %s\n", id, section->name.c_str());
                     break;
                 }
                 idx++;
@@ -592,7 +592,7 @@
 
 static void printPrivacy(const Privacy* p, FILE* out, String8 indent) {
     if (p == NULL) return;
-    fprintf(out, "%sid:%d, type:%d, dest:%d\n", indent.string(), p->field_id, p->type, p->policy);
+    fprintf(out, "%sid:%d, type:%d, dest:%d\n", indent.c_str(), p->field_id, p->type, p->policy);
     if (p->children == NULL) return;
     for (int i = 0; p->children[i] != NULL; i++) {  // NULL-terminated.
         printPrivacy(p->children[i], out, indent + "  ");
@@ -605,7 +605,7 @@
     const int argCount = args.size();
     if (argCount >= 3) {
         String8 opt = args[1];
-        int sectionId = atoi(args[2].string());
+        int sectionId = atoi(args[2].c_str());
 
         const Privacy* p = get_privacy_of_section(sectionId);
         if (p == NULL) {
diff --git a/cmds/incidentd/src/Reporter.cpp b/cmds/incidentd/src/Reporter.cpp
index 86a78f09..c9cf727 100644
--- a/cmds/incidentd/src/Reporter.cpp
+++ b/cmds/incidentd/src/Reporter.cpp
@@ -711,7 +711,7 @@
         return NO_ERROR;
     }
 
-    ALOGD("Start incident report section %d '%s'", sectionId, section->name.string());
+    ALOGD("Start incident report section %d '%s'", sectionId, section->name.c_str());
     IncidentMetadata::SectionStats* sectionMetadata = metadata->add_sections();
 
     // Notify listener of starting
@@ -747,7 +747,7 @@
                     sectionId, IIncidentReportStatusListener::STATUS_FINISHED);
     });
 
-    ALOGD("Finish incident report section %d '%s'", sectionId, section->name.string());
+    ALOGD("Finish incident report section %d '%s'", sectionId, section->name.c_str());
     return NO_ERROR;
 }
 
diff --git a/cmds/incidentd/src/Section.cpp b/cmds/incidentd/src/Section.cpp
index 581367a..c2aa269 100644
--- a/cmds/incidentd/src/Section.cpp
+++ b/cmds/incidentd/src/Section.cpp
@@ -60,7 +60,7 @@
 const char* GZIP[] = {"/system/bin/gzip", NULL};
 
 static pid_t fork_execute_incident_helper(const int id, Fpipe* p2cPipe, Fpipe* c2pPipe) {
-    const char* ihArgs[]{INCIDENT_HELPER, "-s", String8::format("%d", id).string(), NULL};
+    const char* ihArgs[]{INCIDENT_HELPER, "-s", String8::format("%d", id).c_str(), NULL};
     return fork_execute_cmd(const_cast<char**>(ihArgs), p2cPipe, c2pPipe);
 }
 
@@ -100,7 +100,7 @@
     // add O_CLOEXEC to make sure it is closed when exec incident helper
     unique_fd fd(open(mFilename, O_RDONLY | O_CLOEXEC));
     if (fd.get() == -1) {
-        ALOGW("[%s] failed to open file", this->name.string());
+        ALOGW("[%s] failed to open file", this->name.c_str());
         // There may be some devices/architectures that won't have the file.
         // Just return here without an error.
         return NO_ERROR;
@@ -110,13 +110,13 @@
     Fpipe c2pPipe;
     // initiate pipes to pass data to/from incident_helper
     if (!p2cPipe.init() || !c2pPipe.init()) {
-        ALOGW("[%s] failed to setup pipes", this->name.string());
+        ALOGW("[%s] failed to setup pipes", this->name.c_str());
         return -errno;
     }
 
     pid_t pid = fork_execute_incident_helper(this->id, &p2cPipe, &c2pPipe);
     if (pid == -1) {
-        ALOGW("[%s] failed to fork", this->name.string());
+        ALOGW("[%s] failed to fork", this->name.c_str());
         return -errno;
     }
 
@@ -128,14 +128,14 @@
     writer->setSectionStats(buffer);
     if (readStatus != NO_ERROR || buffer.timedOut()) {
         ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
-              this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
+              this->name.c_str(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
         kill_child(pid);
         return readStatus;
     }
 
     status_t ihStatus = wait_child(pid);
     if (ihStatus != NO_ERROR) {
-        ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-ihStatus));
+        ALOGW("[%s] abnormal child process: %s", this->name.c_str(), strerror(-ihStatus));
         return OK; // Not a fatal error.
     }
 
@@ -169,7 +169,7 @@
         index++;  // look at the next file.
     }
     if (fd.get() == -1) {
-        ALOGW("[%s] can't open all the files", this->name.string());
+        ALOGW("[%s] can't open all the files", this->name.c_str());
         return NO_ERROR;  // e.g. LAST_KMSG will reach here in user build.
     }
     FdBuffer buffer;
@@ -177,13 +177,13 @@
     Fpipe c2pPipe;
     // initiate pipes to pass data to/from gzip
     if (!p2cPipe.init() || !c2pPipe.init()) {
-        ALOGW("[%s] failed to setup pipes", this->name.string());
+        ALOGW("[%s] failed to setup pipes", this->name.c_str());
         return -errno;
     }
 
     pid_t pid = fork_execute_cmd((char* const*)GZIP, &p2cPipe, &c2pPipe);
     if (pid == -1) {
-        ALOGW("[%s] failed to fork", this->name.string());
+        ALOGW("[%s] failed to fork", this->name.c_str());
         return -errno;
     }
     // parent process
@@ -202,14 +202,14 @@
     size_t editPos = internalBuffer->wp()->pos();
     internalBuffer->wp()->move(8);  // reserve 8 bytes for the varint of the data size.
     size_t dataBeginAt = internalBuffer->wp()->pos();
-    VLOG("[%s] editPos=%zu, dataBeginAt=%zu", this->name.string(), editPos, dataBeginAt);
+    VLOG("[%s] editPos=%zu, dataBeginAt=%zu", this->name.c_str(), editPos, dataBeginAt);
 
     status_t readStatus = buffer.readProcessedDataInStream(
             fd.get(), std::move(p2cPipe.writeFd()), std::move(c2pPipe.readFd()), this->timeoutMs,
             isSysfs(mFilenames[index]));
     writer->setSectionStats(buffer);
     if (readStatus != NO_ERROR || buffer.timedOut()) {
-        ALOGW("[%s] failed to read data from gzip: %s, timedout: %s", this->name.string(),
+        ALOGW("[%s] failed to read data from gzip: %s, timedout: %s", this->name.c_str(),
               strerror(-readStatus), buffer.timedOut() ? "true" : "false");
         kill_child(pid);
         return readStatus;
@@ -217,7 +217,7 @@
 
     status_t gzipStatus = wait_child(pid);
     if (gzipStatus != NO_ERROR) {
-        ALOGW("[%s] abnormal child process: %s", this->name.string(), strerror(-gzipStatus));
+        ALOGW("[%s] abnormal child process: %s", this->name.c_str(), strerror(-gzipStatus));
         return gzipStatus;
     }
     // Revisit the actual size from gzip result and edit the internal buffer accordingly.
@@ -290,7 +290,7 @@
     FdBuffer buffer;
     err = buffer.read(data->pipe.readFd().get(), this->timeoutMs);
     if (err != NO_ERROR) {
-        ALOGE("[%s] reader failed with error '%s'", this->name.string(), strerror(-err));
+        ALOGE("[%s] reader failed with error '%s'", this->name.c_str(), strerror(-err));
     }
 
     // If the worker side is finished, then return its error (which may overwrite
@@ -300,7 +300,7 @@
         data->pipe.close();
         if (data->workerError != NO_ERROR) {
             err = data->workerError;
-            ALOGE("[%s] worker failed with error '%s'", this->name.string(), strerror(-err));
+            ALOGE("[%s] worker failed with error '%s'", this->name.c_str(), strerror(-err));
         }
         workerDone = data->workerDone;
     }
@@ -309,17 +309,17 @@
     if (err != NO_ERROR) {
         char errMsg[128];
         snprintf(errMsg, 128, "[%s] failed with error '%s'",
-            this->name.string(), strerror(-err));
+            this->name.c_str(), strerror(-err));
         writer->error(this, err, "WorkerThreadSection failed.");
         return NO_ERROR;
     }
     if (buffer.truncated()) {
-        ALOGW("[%s] too large, truncating", this->name.string());
+        ALOGW("[%s] too large, truncating", this->name.c_str());
         // Do not write a truncated section. It won't pass through the PrivacyFilter.
         return NO_ERROR;
     }
     if (!workerDone || buffer.timedOut()) {
-        ALOGW("[%s] timed out", this->name.string());
+        ALOGW("[%s] timed out", this->name.c_str());
         return NO_ERROR;
     }
 
@@ -360,18 +360,18 @@
     Fpipe ihPipe;
 
     if (!cmdPipe.init() || !ihPipe.init()) {
-        ALOGW("[%s] failed to setup pipes", this->name.string());
+        ALOGW("[%s] failed to setup pipes", this->name.c_str());
         return -errno;
     }
 
     pid_t cmdPid = fork_execute_cmd((char* const*)mCommand, NULL, &cmdPipe);
     if (cmdPid == -1) {
-        ALOGW("[%s] failed to fork", this->name.string());
+        ALOGW("[%s] failed to fork", this->name.c_str());
         return -errno;
     }
     pid_t ihPid = fork_execute_incident_helper(this->id, &cmdPipe, &ihPipe);
     if (ihPid == -1) {
-        ALOGW("[%s] failed to fork", this->name.string());
+        ALOGW("[%s] failed to fork", this->name.c_str());
         return -errno;
     }
 
@@ -381,7 +381,7 @@
     writer->setSectionStats(buffer);
     if (readStatus != NO_ERROR || buffer.timedOut()) {
         ALOGW("[%s] failed to read data from incident helper: %s, timedout: %s",
-              this->name.string(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
+              this->name.c_str(), strerror(-readStatus), buffer.timedOut() ? "true" : "false");
         kill_child(cmdPid);
         kill_child(ihPid);
         return readStatus;
@@ -393,7 +393,7 @@
     status_t ihStatus = wait_child(ihPid);
     if (cmdStatus != NO_ERROR || ihStatus != NO_ERROR) {
         ALOGW("[%s] abnormal child processes, return status: command: %s, incident helper: %s",
-              this->name.string(), strerror(-cmdStatus), strerror(-ihStatus));
+              this->name.c_str(), strerror(-cmdStatus), strerror(-ihStatus));
         // Not a fatal error.
         return NO_ERROR;
     }
@@ -428,7 +428,7 @@
     sp<IBinder> service = defaultServiceManager()->checkService(mService);
 
     if (service == NULL) {
-        ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).string());
+        ALOGW("DumpsysSection: Can't lookup service: %s", String8(mService).c_str());
         return NAME_NOT_FOUND;
     }
 
@@ -463,14 +463,14 @@
     // checkService won't wait for the service to show up like getService will.
     sp<IBinder> service = defaultServiceManager()->checkService(mService);
     if (service == NULL) {
-        ALOGW("TextDumpsysSection: Can't lookup service: %s", String8(mService).string());
+        ALOGW("TextDumpsysSection: Can't lookup service: %s", String8(mService).c_str());
         return NAME_NOT_FOUND;
     }
 
     // Create pipe
     Fpipe dumpPipe;
     if (!dumpPipe.init()) {
-        ALOGW("[%s] failed to setup pipe", this->name.string());
+        ALOGW("[%s] failed to setup pipe", this->name.c_str());
         return -errno;
     }
 
@@ -482,7 +482,7 @@
         signal(SIGPIPE, sigpipe_handler);
         status_t err = service->dump(write_fd.get(), this->mArgs);
         if (err != OK) {
-            ALOGW("[%s] dump thread failed. Error: %s", this->name.string(), strerror(-err));
+            ALOGW("[%s] dump thread failed. Error: %s", this->name.c_str(), strerror(-err));
         }
         write_fd.reset();
     });
@@ -490,7 +490,7 @@
     // Collect dump content
     FdBuffer buffer;
     ProtoOutputStream proto;
-    proto.write(TextDumpProto::COMMAND, std::string(name.string()));
+    proto.write(TextDumpProto::COMMAND, std::string(name.c_str()));
     proto.write(TextDumpProto::DUMP_DURATION_NS, int64_t(Nanotime() - start));
     buffer.write(proto.data());
 
@@ -504,7 +504,7 @@
     dumpPipe.readFd().reset();
     writer->setSectionStats(buffer);
     if (readStatus != OK || buffer.timedOut()) {
-        ALOGW("[%s] failed to read from dumpsys: %s, timedout: %s", this->name.string(),
+        ALOGW("[%s] failed to read from dumpsys: %s, timedout: %s", this->name.c_str(),
               strerror(-readStatus), buffer.timedOut() ? "true" : "false");
         worker.detach();
         return readStatus;
@@ -579,7 +579,7 @@
     // Hence forking a new process to prevent memory fragmentation.
     pid_t pid = fork();
     if (pid < 0) {
-        ALOGW("[%s] failed to fork", this->name.string());
+        ALOGW("[%s] failed to fork", this->name.c_str());
         return errno;
     }
     if (pid > 0) {
@@ -593,7 +593,7 @@
             android_logger_list_free);
 
     if (android_logger_open(loggers.get(), mLogID) == NULL) {
-        ALOGE("[%s] Can't get logger.", this->name.string());
+        ALOGE("[%s] Can't get logger.", this->name.c_str());
         _exit(EXIT_FAILURE);
     }
 
@@ -610,7 +610,7 @@
         // status = -EAGAIN, graceful indication for ANDRODI_LOG_NONBLOCK that this is the end.
         if (status <= 0) {
             if (status != -EAGAIN) {
-                ALOGW("[%s] fails to read a log_msg.\n", this->name.string());
+                ALOGW("[%s] fails to read a log_msg.\n", this->name.c_str());
                 err = -status;
             }
             break;
@@ -680,7 +680,7 @@
             AndroidLogEntry entry;
             status = android_log_processLogBuffer(&msg.entry, &entry);
             if (status != OK) {
-                ALOGW("[%s] fails to process to an entry.\n", this->name.string());
+                ALOGW("[%s] fails to process to an entry.\n", this->name.c_str());
                 err = status;
                 break;
             }
@@ -702,7 +702,7 @@
         }
         if (!proto.flush(pipeWriteFd.get())) {
             if (errno == EPIPE) {
-                ALOGW("[%s] wrote to a broken pipe\n", this->name.string());
+                ALOGW("[%s] wrote to a broken pipe\n", this->name.c_str());
             }
             err = errno;
             break;
@@ -757,7 +757,7 @@
         }
         ssize_t exe_name_len = readlink(link_name, exe_name, EXE_NAME_LEN);
         if (exe_name_len < 0 || exe_name_len >= EXE_NAME_LEN) {
-            ALOGE("[%s] Can't read '%s': %s", name.string(), link_name, strerror(errno));
+            ALOGE("[%s] Can't read '%s': %s", name.c_str(), link_name, strerror(errno));
             continue;
         }
         // readlink(2) does not put a null terminator at the end
@@ -788,7 +788,7 @@
 
         Fpipe dumpPipe;
         if (!dumpPipe.init()) {
-            ALOGW("[%s] failed to setup dump pipe", this->name.string());
+            ALOGW("[%s] failed to setup dump pipe", this->name.c_str());
             err = -errno;
             break;
         }
@@ -822,12 +822,12 @@
         // Wait on the child to avoid it becoming a zombie process.
         status_t cStatus = wait_child(child);
         if (err != NO_ERROR) {
-            ALOGW("[%s] failed to read stack dump: %d", this->name.string(), err);
+            ALOGW("[%s] failed to read stack dump: %d", this->name.c_str(), err);
             dumpPipe.readFd().reset();
             break;
         }
         if (cStatus != NO_ERROR) {
-            ALOGE("[%s] child had an issue: %s\n", this->name.string(), strerror(-cStatus));
+            ALOGE("[%s] child had an issue: %s\n", this->name.c_str(), strerror(-cStatus));
         }
 
         // Resize dump buffer
@@ -852,7 +852,7 @@
         dumpPipe.readFd().reset();
         if (!proto.flush(pipeWriteFd.get())) {
             if (errno == EPIPE) {
-                ALOGE("[%s] wrote to a broken pipe\n", this->name.string());
+                ALOGE("[%s] wrote to a broken pipe\n", this->name.c_str());
             }
             err = errno;
             break;
diff --git a/cmds/incidentd/src/report_directory.cpp b/cmds/incidentd/src/report_directory.cpp
index 7d20a74..6b2fb8e 100644
--- a/cmds/incidentd/src/report_directory.cpp
+++ b/cmds/incidentd/src/report_directory.cpp
@@ -62,8 +62,8 @@
             continue;
         }
         String8 filename = dirbase + entry->d_name;
-        if (stat(filename.string(), &st) != 0) {
-            ALOGE("Unable to stat file %s", filename.string());
+        if (stat(filename.c_str(), &st) != 0) {
+            ALOGE("Unable to stat file %s", filename.c_str());
             continue;
         }
         if (!S_ISREG(st.st_mode)) {
@@ -88,7 +88,7 @@
     // Remove files until we're under our limits.
     for (std::vector<std::pair<String8, struct stat>>::iterator it = files.begin();
          it != files.end() && totalSize >= maxSize && totalCount >= maxCount; it++) {
-        remove(it->first.string());
+        remove(it->first.c_str());
         totalSize -= it->second.st_size;
         totalCount--;
     }
diff --git a/cmds/locksettings/Android.bp b/cmds/locksettings/Android.bp
index 5ee5824..ee31aed 100644
--- a/cmds/locksettings/Android.bp
+++ b/cmds/locksettings/Android.bp
@@ -21,8 +21,7 @@
     default_applicable_licenses: ["frameworks_base_license"],
 }
 
-java_binary {
+sh_binary {
     name: "locksettings",
-    wrapper: "locksettings.sh",
-    srcs: ["**/*.java"],
+    src: "locksettings.sh",
 }
diff --git a/cmds/locksettings/locksettings.sh b/cmds/locksettings/locksettings.sh
index 0ef4fa9..2f8d868 100755
--- a/cmds/locksettings/locksettings.sh
+++ b/cmds/locksettings/locksettings.sh
@@ -1,6 +1,2 @@
 #!/system/bin/sh
-# Script to start "locksettings" on the device
-#
-base=/system
-export CLASSPATH=$base/framework/locksettings.jar
-exec app_process $base/bin com.android.commands.locksettings.LockSettingsCmd "$@"
+cmd lock_settings "$@"
diff --git a/cmds/locksettings/src/com/android/commands/locksettings/LockSettingsCmd.java b/cmds/locksettings/src/com/android/commands/locksettings/LockSettingsCmd.java
deleted file mode 100644
index 7d9260a..0000000
--- a/cmds/locksettings/src/com/android/commands/locksettings/LockSettingsCmd.java
+++ /dev/null
@@ -1,47 +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
- */
-
-package com.android.commands.locksettings;
-
-import android.os.ResultReceiver;
-import android.os.ServiceManager;
-import android.os.ShellCallback;
-
-import com.android.internal.os.BaseCommand;
-import com.android.internal.widget.ILockSettings;
-
-import java.io.FileDescriptor;
-import java.io.PrintStream;
-
-public final class LockSettingsCmd extends BaseCommand {
-
-    public static void main(String[] args) {
-        (new LockSettingsCmd()).run(args);
-    }
-
-    @Override
-    public void onShowUsage(PrintStream out) {
-        main(new String[] { "help" });
-    }
-
-    @Override
-    public void onRun() throws Exception {
-        ILockSettings lockSettings = ILockSettings.Stub.asInterface(
-                ServiceManager.getService("lock_settings"));
-        lockSettings.asBinder().shellCommand(FileDescriptor.in, FileDescriptor.out,
-                FileDescriptor.err, getRawArgs(), new ShellCallback(), new ResultReceiver(null) {});
-    }
-}
diff --git a/cmds/screencap/screencap.cpp b/cmds/screencap/screencap.cpp
index 7e6a521..e3c0d677 100644
--- a/cmds/screencap/screencap.cpp
+++ b/cmds/screencap/screencap.cpp
@@ -173,9 +173,6 @@
         return 1;
     }
 
-    void const* mapbase = MAP_FAILED;
-    ssize_t mapsize = -1;
-
     void* base = NULL;
 
     // setThreadPoolMaxThreadCount(0) actually tells the kernel it's
@@ -255,9 +252,6 @@
         }
     }
     close(fd);
-    if (mapbase != MAP_FAILED) {
-        munmap((void *)mapbase, mapsize);
-    }
 
     return 0;
 }
diff --git a/core/api/current.txt b/core/api/current.txt
index 44865b5..d399e34 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -12037,6 +12037,7 @@
     field public static final String FEATURE_TELEPHONY_RADIO_ACCESS = "android.hardware.telephony.radio.access";
     field public static final String FEATURE_TELEPHONY_SUBSCRIPTION = "android.hardware.telephony.subscription";
     field @Deprecated public static final String FEATURE_TELEVISION = "android.hardware.type.television";
+    field public static final String FEATURE_THREAD_NETWORK = "android.hardware.thread_network";
     field public static final String FEATURE_TOUCHSCREEN = "android.hardware.touchscreen";
     field public static final String FEATURE_TOUCHSCREEN_MULTITOUCH = "android.hardware.touchscreen.multitouch";
     field public static final String FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT = "android.hardware.touchscreen.multitouch.distinct";
@@ -31969,7 +31970,7 @@
     method public boolean isInteractive();
     method public boolean isLowPowerStandbyEnabled();
     method public boolean isPowerSaveMode();
-    method public boolean isRebootingUserspaceSupported();
+    method @Deprecated public boolean isRebootingUserspaceSupported();
     method @Deprecated public boolean isScreenOn();
     method public boolean isSustainedPerformanceModeSupported();
     method public boolean isWakeLockLevelSupported(int);
@@ -32370,6 +32371,7 @@
     field public static final String DISALLOW_MICROPHONE_TOGGLE = "disallow_microphone_toggle";
     field public static final String DISALLOW_MODIFY_ACCOUNTS = "no_modify_accounts";
     field public static final String DISALLOW_MOUNT_PHYSICAL_MEDIA = "no_physical_media";
+    field public static final String DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO = "no_near_field_communication_radio";
     field public static final String DISALLOW_NETWORK_RESET = "no_network_reset";
     field public static final String DISALLOW_OUTGOING_BEAM = "no_outgoing_beam";
     field public static final String DISALLOW_OUTGOING_CALLS = "no_outgoing_calls";
@@ -37933,6 +37935,7 @@
     method @Nullable public java.util.Date getKeyValidityStart();
     method @NonNull public String getKeystoreAlias();
     method public int getMaxUsageCount();
+    method @FlaggedApi("MGF1_DIGEST_SETTER") @NonNull public java.util.Set<java.lang.String> getMgf1Digests();
     method public int getPurposes();
     method @NonNull public String[] getSignaturePaddings();
     method public int getUserAuthenticationType();
@@ -37940,6 +37943,7 @@
     method public boolean isDevicePropertiesAttestationIncluded();
     method @NonNull public boolean isDigestsSpecified();
     method public boolean isInvalidatedByBiometricEnrollment();
+    method @FlaggedApi("MGF1_DIGEST_SETTER") @NonNull public boolean isMgf1DigestsSpecified();
     method public boolean isRandomizedEncryptionRequired();
     method public boolean isStrongBoxBacked();
     method public boolean isUnlockedDeviceRequired();
@@ -37971,6 +37975,7 @@
     method @NonNull public android.security.keystore.KeyGenParameterSpec.Builder setKeyValidityForOriginationEnd(java.util.Date);
     method @NonNull public android.security.keystore.KeyGenParameterSpec.Builder setKeyValidityStart(java.util.Date);
     method @NonNull public android.security.keystore.KeyGenParameterSpec.Builder setMaxUsageCount(int);
+    method @FlaggedApi("MGF1_DIGEST_SETTER") @NonNull public android.security.keystore.KeyGenParameterSpec.Builder setMgf1Digests(@Nullable java.lang.String...);
     method @NonNull public android.security.keystore.KeyGenParameterSpec.Builder setRandomizedEncryptionRequired(boolean);
     method @NonNull public android.security.keystore.KeyGenParameterSpec.Builder setSignaturePaddings(java.lang.String...);
     method @NonNull public android.security.keystore.KeyGenParameterSpec.Builder setUnlockedDeviceRequired(boolean);
@@ -38075,12 +38080,14 @@
     method @Nullable public java.util.Date getKeyValidityForOriginationEnd();
     method @Nullable public java.util.Date getKeyValidityStart();
     method public int getMaxUsageCount();
+    method @FlaggedApi("MGF1_DIGEST_SETTER") @NonNull public java.util.Set<java.lang.String> getMgf1Digests();
     method public int getPurposes();
     method @NonNull public String[] getSignaturePaddings();
     method public int getUserAuthenticationType();
     method public int getUserAuthenticationValidityDurationSeconds();
     method public boolean isDigestsSpecified();
     method public boolean isInvalidatedByBiometricEnrollment();
+    method @FlaggedApi("MGF1_DIGEST_SETTER") @NonNull public boolean isMgf1DigestsSpecified();
     method public boolean isRandomizedEncryptionRequired();
     method public boolean isUnlockedDeviceRequired();
     method public boolean isUserAuthenticationRequired();
@@ -38102,6 +38109,7 @@
     method @NonNull public android.security.keystore.KeyProtection.Builder setKeyValidityForOriginationEnd(java.util.Date);
     method @NonNull public android.security.keystore.KeyProtection.Builder setKeyValidityStart(java.util.Date);
     method @NonNull public android.security.keystore.KeyProtection.Builder setMaxUsageCount(int);
+    method @FlaggedApi("MGF1_DIGEST_SETTER") @NonNull public android.security.keystore.KeyProtection.Builder setMgf1Digests(@Nullable java.lang.String...);
     method @NonNull public android.security.keystore.KeyProtection.Builder setRandomizedEncryptionRequired(boolean);
     method @NonNull public android.security.keystore.KeyProtection.Builder setSignaturePaddings(java.lang.String...);
     method @NonNull public android.security.keystore.KeyProtection.Builder setUnlockedDeviceRequired(boolean);
@@ -41313,6 +41321,8 @@
     field public static final String KEY_5G_NR_SSRSRQ_THRESHOLDS_INT_ARRAY = "5g_nr_ssrsrq_thresholds_int_array";
     field public static final String KEY_5G_NR_SSSINR_THRESHOLDS_INT_ARRAY = "5g_nr_sssinr_thresholds_int_array";
     field public static final String KEY_ADDITIONAL_CALL_SETTING_BOOL = "additional_call_setting_bool";
+    field public static final String KEY_ADDITIONAL_SETTINGS_CALLER_ID_VISIBILITY_BOOL = "additional_settings_caller_id_visibility_bool";
+    field public static final String KEY_ADDITIONAL_SETTINGS_CALL_WAITING_VISIBILITY_BOOL = "additional_settings_call_waiting_visibility_bool";
     field public static final String KEY_ALLOW_ADDING_APNS_BOOL = "allow_adding_apns_bool";
     field public static final String KEY_ALLOW_ADD_CALL_DURING_VIDEO_CALL_BOOL = "allow_add_call_during_video_call";
     field public static final String KEY_ALLOW_EMERGENCY_NUMBERS_IN_CALL_LOG_BOOL = "allow_emergency_numbers_in_call_log_bool";
@@ -42929,9 +42939,9 @@
     field public static final int BAND_UNKNOWN = 0; // 0x0
     field public static final int CELL_BANDWIDTH_UNKNOWN = 0; // 0x0
     field public static final int CHANNEL_NUMBER_UNKNOWN = 2147483647; // 0x7fffffff
-    field public static final int CONNECTION_PRIMARY_SERVING = 1; // 0x1
-    field public static final int CONNECTION_SECONDARY_SERVING = 2; // 0x2
-    field public static final int CONNECTION_UNKNOWN = -1; // 0xffffffff
+    field @Deprecated public static final int CONNECTION_PRIMARY_SERVING = 1; // 0x1
+    field @Deprecated public static final int CONNECTION_SECONDARY_SERVING = 2; // 0x2
+    field @Deprecated public static final int CONNECTION_UNKNOWN = -1; // 0xffffffff
     field @NonNull public static final android.os.Parcelable.Creator<android.telephony.PhysicalChannelConfig> CREATOR;
     field public static final int FREQUENCY_UNKNOWN = -1; // 0xffffffff
     field public static final int PHYSICAL_CELL_ID_MAXIMUM_VALUE = 1007; // 0x3ef
diff --git a/core/api/module-lib-current.txt b/core/api/module-lib-current.txt
index 13a4899..5d59969 100644
--- a/core/api/module-lib-current.txt
+++ b/core/api/module-lib-current.txt
@@ -13,6 +13,7 @@
 
   @UiContext public class Activity extends android.view.ContextThemeWrapper implements android.content.ComponentCallbacks2 android.view.KeyEvent.Callback android.view.LayoutInflater.Factory2 android.view.View.OnCreateContextMenuListener android.view.Window.Callback {
     method public final boolean addDumpable(@NonNull android.util.Dumpable);
+    method public final boolean isResumed();
   }
 
   public class ActivityManager {
@@ -90,6 +91,7 @@
   public abstract class Context {
     method @NonNull public android.os.UserHandle getUser();
     field public static final String PAC_PROXY_SERVICE = "pac_proxy";
+    field public static final String REMOTE_AUTH_SERVICE = "remote_auth";
     field public static final String TEST_NETWORK_SERVICE = "test_network";
   }
 
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index 821944f..ebf5f5e 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -276,6 +276,7 @@
     field public static final String RECOVER_KEYSTORE = "android.permission.RECOVER_KEYSTORE";
     field public static final String REGISTER_CALL_PROVIDER = "android.permission.REGISTER_CALL_PROVIDER";
     field public static final String REGISTER_CONNECTION_MANAGER = "android.permission.REGISTER_CONNECTION_MANAGER";
+    field public static final String REGISTER_NSD_OFFLOAD_ENGINE = "android.permission.REGISTER_NSD_OFFLOAD_ENGINE";
     field public static final String REGISTER_SIM_SUBSCRIPTION = "android.permission.REGISTER_SIM_SUBSCRIPTION";
     field public static final String REGISTER_STATS_PULL_ATOM = "android.permission.REGISTER_STATS_PULL_ATOM";
     field public static final String REMOTE_DISPLAY_PROVIDER = "android.permission.REMOTE_DISPLAY_PROVIDER";
@@ -2975,6 +2976,7 @@
     field public static final String SYSTEM_CONFIG_SERVICE = "system_config";
     field public static final String SYSTEM_UPDATE_SERVICE = "system_update";
     field public static final String TETHERING_SERVICE = "tethering";
+    field public static final String THREAD_NETWORK_SERVICE = "thread_network";
     field public static final String TRANSLATION_MANAGER_SERVICE = "translation";
     field public static final String UI_TRANSLATION_SERVICE = "ui_translation";
     field public static final String UWB_SERVICE = "uwb";
@@ -3025,7 +3027,7 @@
     field public static final String ACTION_MANAGE_PERMISSION_APPS = "android.intent.action.MANAGE_PERMISSION_APPS";
     field @RequiresPermission(android.Manifest.permission.START_VIEW_PERMISSION_USAGE) public static final String ACTION_MANAGE_PERMISSION_USAGE = "android.intent.action.MANAGE_PERMISSION_USAGE";
     field @RequiresPermission(android.Manifest.permission.MANAGE_ROLE_HOLDERS) public static final String ACTION_MANAGE_SPECIAL_APP_ACCESSES = "android.intent.action.MANAGE_SPECIAL_APP_ACCESSES";
-    field public static final String ACTION_MASTER_CLEAR_NOTIFICATION = "android.intent.action.MASTER_CLEAR_NOTIFICATION";
+    field @RequiresPermission(android.Manifest.permission.MASTER_CLEAR) public static final String ACTION_MASTER_CLEAR_NOTIFICATION = "android.intent.action.MASTER_CLEAR_NOTIFICATION";
     field public static final String ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION = "android.intent.action.PACKAGE_NEEDS_INTEGRITY_VERIFICATION";
     field public static final String ACTION_PACKAGE_UNSUSPENDED_MANUALLY = "android.intent.action.PACKAGE_UNSUSPENDED_MANUALLY";
     field public static final String ACTION_PENDING_INCIDENT_REPORTS_CHANGED = "android.intent.action.PENDING_INCIDENT_REPORTS_CHANGED";
@@ -9138,6 +9140,73 @@
 
 }
 
+package android.nfc.cardemulation {
+
+  @FlaggedApi("android.nfc.enable_nfc_mainline") public final class AidGroup implements android.os.Parcelable {
+    ctor @FlaggedApi("android.nfc.enable_nfc_mainline") public AidGroup(@NonNull java.util.List<java.lang.String>, @Nullable String);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @Nullable public static android.nfc.cardemulation.AidGroup createFromXml(@NonNull org.xmlpull.v1.XmlPullParser) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException;
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public int describeContents();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void dump(@NonNull android.util.proto.ProtoOutputStream);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public java.util.List<java.lang.String> getAids();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public String getCategory();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void writeAsXml(@NonNull org.xmlpull.v1.XmlSerializer) throws java.io.IOException;
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void writeToParcel(@NonNull android.os.Parcel, int);
+    field @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public static final android.os.Parcelable.Creator<android.nfc.cardemulation.AidGroup> CREATOR;
+  }
+
+  @FlaggedApi("android.nfc.enable_nfc_mainline") public final class ApduServiceInfo implements android.os.Parcelable {
+    ctor @FlaggedApi("android.nfc.enable_nfc_mainline") public ApduServiceInfo(@NonNull android.content.pm.PackageManager, @NonNull android.content.pm.ResolveInfo, boolean) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException;
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public int describeContents();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void dump(@NonNull android.os.ParcelFileDescriptor, @NonNull java.io.PrintWriter, @NonNull String[]);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void dumpDebug(@NonNull android.util.proto.ProtoOutputStream);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public java.util.List<android.nfc.cardemulation.AidGroup> getAidGroups();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public java.util.List<java.lang.String> getAids();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public String getCategoryForAid(@NonNull String);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public android.content.ComponentName getComponent();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public String getDescription();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public android.nfc.cardemulation.AidGroup getDynamicAidGroupForCategory(@NonNull String);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @Nullable public String getOffHostSecureElement();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public java.util.List<java.lang.String> getPrefixAids();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public String getSettingsActivityName();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public java.util.List<java.lang.String> getSubsetAids();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public int getUid();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public boolean hasCategory(@NonNull String);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public boolean isOnHost();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public CharSequence loadAppLabel(@NonNull android.content.pm.PackageManager);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public android.graphics.drawable.Drawable loadBanner(@NonNull android.content.pm.PackageManager);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public android.graphics.drawable.Drawable loadIcon(@NonNull android.content.pm.PackageManager);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public CharSequence loadLabel(@NonNull android.content.pm.PackageManager);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public boolean removeDynamicAidGroupForCategory(@NonNull String);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public boolean requiresScreenOn();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public boolean requiresUnlock();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void resetOffHostSecureElement();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void setDynamicAidGroup(@NonNull android.nfc.cardemulation.AidGroup);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void setOffHostSecureElement(@NonNull String);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void writeToParcel(@NonNull android.os.Parcel, int);
+    field @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public static final android.os.Parcelable.Creator<android.nfc.cardemulation.ApduServiceInfo> CREATOR;
+  }
+
+  @FlaggedApi("android.nfc.enable_nfc_mainline") public final class NfcFServiceInfo implements android.os.Parcelable {
+    ctor @FlaggedApi("android.nfc.enable_nfc_mainline") public NfcFServiceInfo(@NonNull android.content.pm.PackageManager, @NonNull android.content.pm.ResolveInfo) throws java.io.IOException, org.xmlpull.v1.XmlPullParserException;
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public int describeContents();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void dump(@NonNull android.os.ParcelFileDescriptor, @NonNull java.io.PrintWriter, @NonNull String[]);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void dumpDebug(@NonNull android.util.proto.ProtoOutputStream);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public android.content.ComponentName getComponent();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public String getDescription();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public String getNfcid2();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public String getSystemCode();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public String getT3tPmm();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public int getUid();
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public android.graphics.drawable.Drawable loadIcon(@NonNull android.content.pm.PackageManager);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public CharSequence loadLabel(@NonNull android.content.pm.PackageManager);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void setDynamicNfcid2(@NonNull String);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void setDynamicSystemCode(@NonNull String);
+    method @FlaggedApi("android.nfc.enable_nfc_mainline") public void writeToParcel(@NonNull android.os.Parcel, int);
+    field @FlaggedApi("android.nfc.enable_nfc_mainline") @NonNull public static final android.os.Parcelable.Creator<android.nfc.cardemulation.NfcFServiceInfo> CREATOR;
+  }
+
+}
+
 package android.os {
 
   public class BatteryManager {
@@ -9627,7 +9696,7 @@
     method @RequiresPermission(anyOf={android.Manifest.permission.DEVICE_POWER, android.Manifest.permission.USER_ACTIVITY}) public void userActivity(long, int, int);
     field public static final int POWER_SAVE_MODE_TRIGGER_DYNAMIC = 1; // 0x1
     field public static final int POWER_SAVE_MODE_TRIGGER_PERCENTAGE = 0; // 0x0
-    field public static final String REBOOT_USERSPACE = "userspace";
+    field @Deprecated public static final String REBOOT_USERSPACE = "userspace";
     field public static final int SOUND_TRIGGER_MODE_ALL_DISABLED = 2; // 0x2
     field public static final int SOUND_TRIGGER_MODE_ALL_ENABLED = 0; // 0x0
     field public static final int SOUND_TRIGGER_MODE_CRITICAL_ONLY = 1; // 0x1
diff --git a/core/api/system-lint-baseline.txt b/core/api/system-lint-baseline.txt
index 0100f0e..71c02dc 100644
--- a/core/api/system-lint-baseline.txt
+++ b/core/api/system-lint-baseline.txt
@@ -225,3 +225,16 @@
     SAM-compatible parameters (such as parameter 1, "listener", in android.view.accessibility.AccessibilityManager.addTouchExplorationStateChangeListener) should be last to improve Kotlin interoperability; see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions
 SamShouldBeLast: android.webkit.WebChromeClient#onShowFileChooser(android.webkit.WebView, android.webkit.ValueCallback<android.net.Uri[]>, android.webkit.WebChromeClient.FileChooserParams):
     SAM-compatible parameters (such as parameter 2, "filePathCallback", in android.webkit.WebChromeClient.onShowFileChooser) should be last to improve Kotlin interoperability; see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions
+
+UnflaggedApi: android.nfc.cardemulation.AidGroup#CONTENTS_FILE_DESCRIPTOR:
+    New API must be flagged with @FlaggedApi: field android.nfc.cardemulation.AidGroup.CONTENTS_FILE_DESCRIPTOR
+UnflaggedApi: android.nfc.cardemulation.AidGroup#PARCELABLE_WRITE_RETURN_VALUE:
+    New API must be flagged with @FlaggedApi: field android.nfc.cardemulation.AidGroup.PARCELABLE_WRITE_RETURN_VALUE
+UnflaggedApi: android.nfc.cardemulation.ApduServiceInfo#CONTENTS_FILE_DESCRIPTOR:
+    New API must be flagged with @FlaggedApi: field android.nfc.cardemulation.ApduServiceInfo.CONTENTS_FILE_DESCRIPTOR
+UnflaggedApi: android.nfc.cardemulation.ApduServiceInfo#PARCELABLE_WRITE_RETURN_VALUE:
+    New API must be flagged with @FlaggedApi: field android.nfc.cardemulation.ApduServiceInfo.PARCELABLE_WRITE_RETURN_VALUE
+UnflaggedApi: android.nfc.cardemulation.NfcFServiceInfo#CONTENTS_FILE_DESCRIPTOR:
+    New API must be flagged with @FlaggedApi: field android.nfc.cardemulation.NfcFServiceInfo.CONTENTS_FILE_DESCRIPTOR
+UnflaggedApi: android.nfc.cardemulation.NfcFServiceInfo#PARCELABLE_WRITE_RETURN_VALUE:
+    New API must be flagged with @FlaggedApi: field android.nfc.cardemulation.NfcFServiceInfo.PARCELABLE_WRITE_RETURN_VALUE
diff --git a/core/api/test-current.txt b/core/api/test-current.txt
index 83bbf32..c8e55b92 100644
--- a/core/api/test-current.txt
+++ b/core/api/test-current.txt
@@ -2684,6 +2684,9 @@
     field @Deprecated protected int mCapabilities;
   }
 
+  public static class MmTelFeature.MmTelCapabilities extends android.telephony.ims.feature.ImsFeature.Capabilities {
+  }
+
 }
 
 package android.text {
diff --git a/core/java/Android.bp b/core/java/Android.bp
index 5d7d7ba..da6a6d4 100644
--- a/core/java/Android.bp
+++ b/core/java/Android.bp
@@ -9,6 +9,11 @@
     default_applicable_licenses: ["frameworks_base_license"],
 }
 
+aidl_library {
+    name: "HardwareBuffer_aidl",
+    hdrs: ["android/hardware/HardwareBuffer.aidl"],
+}
+
 filegroup {
     name: "framework-core-sources",
     srcs: [
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index cf11c5c..a24007e 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -1996,7 +1996,7 @@
      * indicator that the activity became active and ready to receive input. This sometimes could
      * also be a transit state toward another resting state. For instance, an activity may be
      * relaunched to {@link #onPause} due to configuration changes and the activity was visible,
-     * but wasn’t the top-most activity of an activity task. {@link #onResume} is guaranteed to be
+     * but wasn't the top-most activity of an activity task. {@link #onResume} is guaranteed to be
      * called before {@link #onPause} in this case which honors the activity lifecycle policy and
      * the activity eventually rests in {@link #onPause}.
      *
@@ -2215,9 +2215,9 @@
      *
      * <p>An activity can never receive a new intent in the resumed state. You can count on
      * {@link #onResume} being called after this method, though not necessarily immediately after
-     * the completion this callback. If the activity was resumed, it will be paused and new intent
-     * will be delivered, followed by {@link #onResume}. If the activity wasn't in the resumed
-     * state, then new intent can be delivered immediately, with {@link #onResume()} called
+     * the completion of this callback. If the activity was resumed, it will be paused and new
+     * intent will be delivered, followed by {@link #onResume}. If the activity wasn't in the
+     * resumed state, then new intent can be delivered immediately, with {@link #onResume()} called
      * sometime later when activity becomes active again.
      *
      * <p>Note that {@link #getIntent} still returns the original Intent.  You
@@ -8637,6 +8637,7 @@
      * @hide
      */
     @UnsupportedAppUsage
+    @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
     public final boolean isResumed() {
         return mResumed;
     }
diff --git a/core/java/android/app/ActivityOptions.java b/core/java/android/app/ActivityOptions.java
index 53e0a05..6706091 100644
--- a/core/java/android/app/ActivityOptions.java
+++ b/core/java/android/app/ActivityOptions.java
@@ -21,6 +21,8 @@
 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
+import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
+import static android.content.Intent.FLAG_RECEIVER_FOREGROUND;
 import static android.view.Display.INVALID_DISPLAY;
 import static android.window.DisplayAreaOrganizer.FEATURE_UNDEFINED;
 
@@ -1756,7 +1758,9 @@
      * @hide
      */
     public int getPendingIntentLaunchFlags() {
-        return mPendingIntentLaunchFlags;
+        // b/243794108: Ignore all flags except the new task flag, to be reconsidered in b/254490217
+        return mPendingIntentLaunchFlags &
+                (FLAG_ACTIVITY_NEW_TASK | FLAG_RECEIVER_FOREGROUND);
     }
 
     /**
diff --git a/core/java/android/app/KeyguardManager.java b/core/java/android/app/KeyguardManager.java
index c802d20..efbdd7e 100644
--- a/core/java/android/app/KeyguardManager.java
+++ b/core/java/android/app/KeyguardManager.java
@@ -48,7 +48,6 @@
 import android.util.Log;
 import android.view.IOnKeyguardExitResult;
 import android.view.IWindowManager;
-import android.view.WindowManager.LayoutParams;
 import android.view.WindowManagerGlobal;
 
 import com.android.internal.policy.IKeyguardDismissCallback;
@@ -68,9 +67,7 @@
 import java.util.concurrent.Executor;
 
 /**
- * Class that can be used to lock and unlock the keyguard. The
- * actual class to control the keyguard locking is
- * {@link android.app.KeyguardManager.KeyguardLock}.
+ * Class to manage and query the state of the lock screen (also known as Keyguard).
  */
 @SystemService(Context.KEYGUARD_SERVICE)
 public class KeyguardManager {
@@ -204,7 +201,9 @@
      * {@link android.app.Activity#RESULT_OK} if the user successfully completes the challenge.
      *
      * @return the intent for launching the activity or null if no password is required.
-     * @deprecated see BiometricPrompt.Builder#setDeviceCredentialAllowed(boolean)
+     *
+     * @deprecated see {@link
+     *   android.hardware.biometrics.BiometricPrompt.Builder#setAllowedAuthenticators(int)}
      */
     @Deprecated
     @RequiresFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN)
@@ -383,13 +382,12 @@
 
     /**
      * Handle returned by {@link KeyguardManager#newKeyguardLock} that allows
-     * you to disable / reenable the keyguard.
+     * you to temporarily disable / reenable the keyguard (lock screen).
      *
-     * @deprecated Use {@link LayoutParams#FLAG_DISMISS_KEYGUARD}
-     * and/or {@link LayoutParams#FLAG_SHOW_WHEN_LOCKED}
-     * instead; this allows you to seamlessly hide the keyguard as your application
-     * moves in and out of the foreground and does not require that any special
-     * permissions be requested.
+     * @deprecated Use {@link android.R.attr#showWhenLocked} or {@link
+     *   android.app.Activity#setShowWhenLocked(boolean)} instead. This allows you to seamlessly
+     *   occlude and unocclude the keyguard as your application moves in and out of the foreground
+     *   and does not require that any special permissions be requested.
      */
     @Deprecated
     public class KeyguardLock {
@@ -404,12 +402,12 @@
          * Disable the keyguard from showing.  If the keyguard is currently
          * showing, hide it.  The keyguard will be prevented from showing again
          * until {@link #reenableKeyguard()} is called.
-         *
+         * <p>
+         * This only works if the keyguard is not secure.
+         * <p>
          * A good place to call this is from {@link android.app.Activity#onResume()}
          *
-         * Note: This call has no effect while any {@link android.app.admin.DevicePolicyManager}
-         * is enabled that requires a password.
-         *
+         * @see KeyguardManager#isKeyguardSecure()
          * @see #reenableKeyguard()
          */
         @RequiresPermission(Manifest.permission.DISABLE_KEYGUARD)
@@ -426,9 +424,6 @@
          *
          * A good place to call this is from {@link android.app.Activity#onPause()}
          *
-         * Note: This call has no effect while any {@link android.app.admin.DevicePolicyManager}
-         * is enabled that requires a password.
-         *
          * @see #disableKeyguard()
          */
         @RequiresPermission(Manifest.permission.DISABLE_KEYGUARD)
@@ -527,20 +522,18 @@
     }
 
     /**
-     * Enables you to lock or unlock the keyguard. Get an instance of this class by
-     * calling {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
-     * This class is wrapped by {@link android.app.KeyguardManager KeyguardManager}.
+     * Enables you to temporarily disable / reenable the keyguard (lock screen).
+     *
      * @param tag A tag that informally identifies who you are (for debugging who
      *   is disabling the keyguard).
      *
      * @return A {@link KeyguardLock} handle to use to disable and reenable the
      *   keyguard.
      *
-     * @deprecated Use {@link LayoutParams#FLAG_DISMISS_KEYGUARD}
-     *   and/or {@link LayoutParams#FLAG_SHOW_WHEN_LOCKED}
-     *   instead; this allows you to seamlessly hide the keyguard as your application
-     *   moves in and out of the foreground and does not require that any special
-     *   permissions be requested.
+     * @deprecated Use {@link android.R.attr#showWhenLocked} or {@link
+     *   android.app.Activity#setShowWhenLocked(boolean)} instead. This allows you to seamlessly
+     *   occlude and unocclude the keyguard as your application moves in and out of the foreground
+     *   and does not require that any special permissions be requested.
      */
     @Deprecated
     public KeyguardLock newKeyguardLock(String tag) {
@@ -548,9 +541,36 @@
     }
 
     /**
-     * Return whether the keyguard is currently locked.
+     * Returns whether the lock screen (also known as Keyguard) is showing.
+     * <p>
+     * Specifically, this returns {@code true} in the following cases:
+     * <ul>
+     *   <li>The lock screen is showing in the foreground.</li>
+     *   <li>The lock screen is showing, but it is occluded by an activity that is showing on top of
+     *   it. A common example is the phone app receiving a call or making an emergency call.</li>
+     *   <li>The lock screen was showing but is temporarily disabled as a result of <a
+     *   href="https://developer.android.com/work/dpc/dedicated-devices/lock-task-mode">lock task
+     *   mode</a> or an app using the deprecated {@link KeyguardLock} API.</li>
+     * </ul>
+     * <p>
+     * "Showing" refers to a logical state of the UI, regardless of whether the screen happens to be
+     * on. When the power button is pressed on an unlocked device, the lock screen starts "showing"
+     * immediately when the screen turns off.
+     * <p>
+     * This method does not distinguish a lock screen that is requiring authentication (e.g. with
+     * PIN, pattern, password, or biometric) from a lock screen that is trivially dismissible (e.g.
+     * with swipe). It also does not distinguish a lock screen requesting a SIM card PIN from a
+     * normal device lock screen. Finally, it always returns the global lock screen state and does
+     * not consider the {@link Context}'s user specifically.
+     * <p>
+     * Note that {@code isKeyguardLocked()} is confusingly named and probably should be called
+     * {@code isKeyguardShowing()}. On many devices, the lock screen displays an <i>unlocked</i>
+     * padlock icon when it is trivially dismissible. As mentioned above, {@code isKeyguardLocked()}
+     * actually returns {@code true} in this case, not {@code false} as might be expected. {@link
+     * #isDeviceLocked()} is an alternative API that has slightly different semantics.
      *
-     * @return {@code true} if the keyguard is locked.
+     * @return {@code true} if the lock screen is showing
+     * @see #isDeviceLocked()
      */
     public boolean isKeyguardLocked() {
         try {
@@ -561,12 +581,23 @@
     }
 
     /**
-     * Return whether the keyguard is secured by a PIN, pattern or password or a SIM card
-     * is currently locked.
+     * Returns whether the user has a secure lock screen or there is a locked SIM card.
+     * <p>
+     * Specifically, this returns {@code true} if at least one of the following is true:
+     * <ul>
+     *   <li>The {@link Context}'s user has a secure lock screen. A full user has a secure lock
+     *   screen if its lock screen is set to PIN, pattern, or password, as opposed to swipe or none.
+     *   A profile that uses a unified challenge is considered to have a secure lock screen if and
+     *   only if its parent user has a secure lock screen.</li>
+     *   <li>At least one SIM card is currently locked and requires a PIN.</li>
+     * </ul>
+     * <p>
+     * This method does not consider whether the lock screen is currently showing or not.
+     * <p>
+     * See also {@link #isDeviceSecure()} which excludes locked SIM cards.
      *
-     * <p>See also {@link #isDeviceSecure()} which ignores SIM locked states.
-     *
-     * @return {@code true} if a PIN, pattern or password is set or a SIM card is locked.
+     * @return {@code true} if the user has a secure lock screen or there is a locked SIM card
+     * @see #isDeviceSecure()
      */
     public boolean isKeyguardSecure() {
         try {
@@ -577,11 +608,11 @@
     }
 
     /**
-     * If keyguard screen is showing or in restricted key input mode (i.e. in
-     * keyguard password emergency screen). When in such mode, certain keys,
-     * such as the Home key and the right soft keys, don't work.
+     * Returns whether the lock screen is showing.
+     * <p>
+     * This is exactly the same as {@link #isKeyguardLocked()}.
      *
-     * @return {@code true} if in keyguard restricted input mode.
+     * @return the value of {@link #isKeyguardLocked()}
      * @deprecated Use {@link #isKeyguardLocked()} instead.
      */
     public boolean inKeyguardRestrictedInputMode() {
@@ -589,11 +620,26 @@
     }
 
     /**
-     * Returns whether the device is currently locked and requires a PIN, pattern or
-     * password to unlock.
+     * Returns whether the device is currently locked for the user.
+     * <p>
+     * This returns the device locked state for the {@link Context}'s user. If this user is the
+     * current user, then the device is considered "locked" when the lock screen is showing (i.e.
+     * {@link #isKeyguardLocked()} returns {@code true}) and is not trivially dismissible (e.g. with
+     * swipe), and the user has a PIN, pattern, or password.
+     * <p>
+     * Note: the above definition implies that a user with no PIN, pattern, or password is never
+     * considered locked, even if the lock screen is showing and requesting a SIM card PIN. The
+     * device PIN and SIM PIN are separate. Also, the user is not considered locked if face
+     * authentication has just completed or a trust agent is keeping the device unlocked, since in
+     * these cases the lock screen is dismissible with swipe.
+     * <p>
+     * For a user that is not the current user but can be switched to (usually this means "another
+     * full user"), and that has a PIN, pattern, or password, the device is always considered
+     * locked. For a profile with a unified challenge, the device is considered locked if and only
+     * if the device is locked for the parent user.
      *
-     * @return {@code true} if unlocking the device currently requires a PIN, pattern or
-     * password.
+     * @return {@code true} if the device is currently locked for the user
+     * @see #isKeyguardLocked()
      */
     public boolean isDeviceLocked() {
         return isDeviceLocked(mContext.getUserId());
@@ -614,12 +660,19 @@
     }
 
     /**
-     * Returns whether the device is secured with a PIN, pattern or
-     * password.
+     * Returns whether the user has a secure lock screen.
+     * <p>
+     * This returns {@code true} if the {@link Context}'s user has a secure lock screen. A full user
+     * has a secure lock screen if its lock screen is set to PIN, pattern, or password, as opposed
+     * to swipe or none. A profile that uses a unified challenge is considered to have a secure lock
+     * screen if and only if its parent user has a secure lock screen.
+     * <p>
+     * This method does not consider whether the lock screen is currently showing or not.
+     * <p>
+     * See also {@link #isKeyguardSecure()} which includes locked SIM cards.
      *
-     * <p>See also {@link #isKeyguardSecure} which treats SIM locked states as secure.
-     *
-     * @return {@code true} if a PIN, pattern or password was set.
+     * @return {@code true} if the user has a secure lock screen
+     * @see #isKeyguardSecure()
      */
     public boolean isDeviceSecure() {
         return isDeviceSecure(mContext.getUserId());
@@ -640,8 +693,7 @@
     }
 
     /**
-     * If the device is currently locked (see {@link #isKeyguardLocked()}, requests the Keyguard to
-     * be dismissed.
+     * Requests that the Keyguard (lock screen) be dismissed if it is currently showing.
      * <p>
      * If the Keyguard is not secure or the device is currently in a trusted state, calling this
      * method will immediately dismiss the Keyguard without any user interaction.
@@ -652,8 +704,9 @@
      * If the value set for the {@link Activity} attr {@link android.R.attr#turnScreenOn} is true,
      * the screen will turn on when the keyguard is dismissed.
      *
-     * @param activity The activity requesting the dismissal. The activity must be either visible
-     *                 by using {@link LayoutParams#FLAG_SHOW_WHEN_LOCKED} or must be in a state in
+     * @param activity The activity requesting the dismissal. The activity must either be visible
+     *                 by using {@link android.R.attr#showWhenLocked} or {@link
+     *                 android.app.Activity#setShowWhenLocked(boolean)}, or must be in a state in
      *                 which it would be visible if Keyguard would not be hiding it. If that's not
      *                 the case, the request will fail immediately and
      *                 {@link KeyguardDismissCallback#onDismissError} will be invoked.
@@ -668,8 +721,7 @@
     }
 
     /**
-     * If the device is currently locked (see {@link #isKeyguardLocked()}, requests the Keyguard to
-     * be dismissed.
+     * Requests that the Keyguard (lock screen) be dismissed if it is currently showing.
      * <p>
      * If the Keyguard is not secure or the device is currently in a trusted state, calling this
      * method will immediately dismiss the Keyguard without any user interaction.
@@ -680,8 +732,9 @@
      * If the value set for the {@link Activity} attr {@link android.R.attr#turnScreenOn} is true,
      * the screen will turn on when the keyguard is dismissed.
      *
-     * @param activity The activity requesting the dismissal. The activity must be either visible
-     *                 by using {@link LayoutParams#FLAG_SHOW_WHEN_LOCKED} or must be in a state in
+     * @param activity The activity requesting the dismissal. The activity must either be visible
+     *                 by using {@link android.R.attr#showWhenLocked} or {@link
+     *                 android.app.Activity#setShowWhenLocked(boolean)}, or must be in a state in
      *                 which it would be visible if Keyguard would not be hiding it. If that's not
      *                 the case, the request will fail immediately and
      *                 {@link KeyguardDismissCallback#onDismissError} will be invoked.
@@ -735,12 +788,12 @@
      * @param callback Lets you know whether the operation was successful and
      *   it is safe to launch anything that would normally be considered safe
      *   once the user has gotten past the keyguard.
-
-     * @deprecated Use {@link LayoutParams#FLAG_DISMISS_KEYGUARD}
-     *   and/or {@link LayoutParams#FLAG_SHOW_WHEN_LOCKED}
-     *   instead; this allows you to seamlessly hide the keyguard as your application
-     *   moves in and out of the foreground and does not require that any special
-     *   permissions be requested.
+     *
+     * @deprecated Use {@link android.R.attr#showWhenLocked} or {@link
+     *   android.app.Activity#setShowWhenLocked(boolean)} to seamlessly occlude and unocclude the
+     *   keyguard as your application moves in and out of the foreground, without requiring any
+     *   special permissions. Use {@link #requestDismissKeyguard(android.app.Activity,
+     *   KeyguardDismissCallback)} to request dismissal of the keyguard.
      */
     @Deprecated
     @RequiresPermission(Manifest.permission.DISABLE_KEYGUARD)
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 90e3e9d..a4a3fdb 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -2857,6 +2857,17 @@
             if (person != null) {
                 visitor.accept(person.getIconUri());
             }
+
+            final RemoteInputHistoryItem[] history = (RemoteInputHistoryItem[])
+                    extras.getParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS);
+            if (history != null) {
+                for (int i = 0; i < history.length; i++) {
+                    RemoteInputHistoryItem item = history[i];
+                    if (item.getUri() != null) {
+                        visitor.accept(item.getUri());
+                    }
+                }
+            }
         }
 
         if (isStyle(MessagingStyle.class) && extras != null) {
@@ -2887,6 +2898,14 @@
             }
         }
 
+        if (isStyle(CallStyle.class) & extras != null) {
+            Person callPerson = extras.getParcelable(EXTRA_CALL_PERSON);
+            if (callPerson != null) {
+                visitor.accept(callPerson.getIconUri());
+            }
+            visitIconUri(visitor, extras.getParcelable(EXTRA_VERIFICATION_ICON));
+        }
+
         if (mBubbleMetadata != null) {
             visitIconUri(visitor, mBubbleMetadata.getIcon());
         }
diff --git a/core/java/android/app/OWNERS b/core/java/android/app/OWNERS
index 5894803..1e5a5fb 100644
--- a/core/java/android/app/OWNERS
+++ b/core/java/android/app/OWNERS
@@ -63,10 +63,11 @@
 # Multiuser
 per-file *User* = file:/MULTIUSER_OWNERS
 
-# Notification, DND, Status bar
+# Notification, DND, Status bar, UiModeManager
 per-file *Notification* = file:/packages/SystemUI/OWNERS
 per-file *Zen* = file:/packages/SystemUI/OWNERS
 per-file *StatusBar* = file:/packages/SystemUI/OWNERS
+per-file *UiModeManager* = file:/packages/SystemUI/OWNERS
 
 # PackageManager
 per-file ApplicationPackageManager.java = file:/services/core/java/com/android/server/pm/OWNERS
diff --git a/core/java/android/app/admin/EnterprisePlatformSecurity_OWNERS b/core/java/android/app/admin/EnterprisePlatformSecurity_OWNERS
index 38fee89..9aab167 100644
--- a/core/java/android/app/admin/EnterprisePlatformSecurity_OWNERS
+++ b/core/java/android/app/admin/EnterprisePlatformSecurity_OWNERS
@@ -1,5 +1,3 @@
+file:EnterprisePlatform_OWNERS
 rubinxu@google.com
-pgrafov@google.com
-ayushsha@google.com
-acjohnston@google.com #{LAST_RESORT_SUGGESTION}
-alexkershaw@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
+pgrafov@google.com
\ No newline at end of file
diff --git a/core/java/android/app/admin/EnterprisePlatformTest_OWNERS b/core/java/android/app/admin/EnterprisePlatformTest_OWNERS
new file mode 100644
index 0000000..eb23a03
--- /dev/null
+++ b/core/java/android/app/admin/EnterprisePlatformTest_OWNERS
@@ -0,0 +1,5 @@
+# Bug template url: https://b.corp.google.com/issues/new?component=1337891&template=1814288
+# Assign bugs to aep-automated-tests@google.com
+
+file:EnterprisePlatform_OWNERS
+scottjonathan@google.com
\ No newline at end of file
diff --git a/core/java/android/app/admin/EnterprisePlatform_OWNERS b/core/java/android/app/admin/EnterprisePlatform_OWNERS
index 6ce25cc..4d1ed590 100644
--- a/core/java/android/app/admin/EnterprisePlatform_OWNERS
+++ b/core/java/android/app/admin/EnterprisePlatform_OWNERS
@@ -1,5 +1,2 @@
-# Assign bugs to android-enterprise-triage@google.com
-file:WorkDeviceExperience_OWNERS
-file:Provisioning_OWNERS
-file:WorkProfile_OWNERS
-file:EnterprisePlatformSecurity_OWNERS
\ No newline at end of file
+sandness@google.com #{LAST_RESORT_SUGGESTION}
+scottjonathan@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
diff --git a/core/java/android/app/admin/OWNERS b/core/java/android/app/admin/OWNERS
index 10a5f14..308f1d6 100644
--- a/core/java/android/app/admin/OWNERS
+++ b/core/java/android/app/admin/OWNERS
@@ -1,5 +1,7 @@
 # Bug component: 142675
+# Assign bugs to device-policy-manager-triage@google.com
 
-file:EnterprisePlatform_OWNERS
+file:WorkDeviceExperience_OWNERS
+file:EnterprisePlatformSecurity_OWNERS
 
 yamasani@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
diff --git a/core/java/android/app/admin/Provisioning_OWNERS b/core/java/android/app/admin/Provisioning_OWNERS
index 2e5c2df..fa0a1f0 100644
--- a/core/java/android/app/admin/Provisioning_OWNERS
+++ b/core/java/android/app/admin/Provisioning_OWNERS
@@ -1,5 +1,4 @@
 # Assign bugs to android-enterprise-triage@google.com
 mdb.ae-provisioning-reviews@google.com
-petuska@google.com #{LAST_RESORT_SUGGESTION}
-nupursn@google.com #{LAST_RESORT_SUGGESTION}
-shreyacsingh@google.com #{LAST_RESORT_SUGGESTION}
+file:EnterprisePlatform_OWNERS
+petuska@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
diff --git a/core/java/android/app/admin/WorkDeviceExperience_OWNERS b/core/java/android/app/admin/WorkDeviceExperience_OWNERS
index b881de0..5e02016 100644
--- a/core/java/android/app/admin/WorkDeviceExperience_OWNERS
+++ b/core/java/android/app/admin/WorkDeviceExperience_OWNERS
@@ -1,7 +1,5 @@
 # Assign bugs to android-enterprise-triage@google.com
 work-device-experience+reviews@google.com
-scottjonathan@google.com #{LAST_RESORT_SUGGESTION}
-eliselliott@google.com #{LAST_RESORT_SUGGESTION}
+file:EnterprisePlatform_OWNERS
 kholoudm@google.com #{LAST_RESORT_SUGGESTION}
-acjohnston@google.com #{LAST_RESORT_SUGGESTION}
-alexkershaw@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
+acjohnston@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
diff --git a/core/java/android/app/admin/WorkProfile_OWNERS b/core/java/android/app/admin/WorkProfile_OWNERS
index 260b672..e9bcce2 100644
--- a/core/java/android/app/admin/WorkProfile_OWNERS
+++ b/core/java/android/app/admin/WorkProfile_OWNERS
@@ -1,5 +1,3 @@
 # Assign bugs to android-enterprise-triage@google.com
-liahav@google.com
-olit@google.com
-scottjonathan@google.com #{LAST_RESORT_SUGGESTION}
-alexkershaw@google.com #{LAST_RESORT_SUGGESTION}
\ No newline at end of file
+file:EnterprisePlatform_OWNERS
+liahav@google.com
\ No newline at end of file
diff --git a/core/java/android/app/search/SearchSession.java b/core/java/android/app/search/SearchSession.java
index 10db337..f7a26dc 100644
--- a/core/java/android/app/search/SearchSession.java
+++ b/core/java/android/app/search/SearchSession.java
@@ -99,7 +99,7 @@
         mInterface = android.app.search.ISearchUiManager.Stub.asInterface(b);
         mSessionId = new SearchSessionId(
                 context.getPackageName() + ":" + UUID.randomUUID().toString(), context.getUserId());
-        // b/175527717 whitelist possible clients of this API
+        // b/175527717 allowlist possible clients of this API
         searchContext.setPackageName(context.getPackageName());
         try {
             mInterface.createSearchSession(searchContext, mSessionId, mToken);
diff --git a/core/java/android/app/trust/ITrustListener.aidl b/core/java/android/app/trust/ITrustListener.aidl
index e4ac0119..8d44784 100644
--- a/core/java/android/app/trust/ITrustListener.aidl
+++ b/core/java/android/app/trust/ITrustListener.aidl
@@ -24,6 +24,7 @@
  * {@hide}
  */
 oneway interface ITrustListener {
+    void onEnabledTrustAgentsChanged(int userId);
     void onTrustChanged(boolean enabled, boolean newlyUnlocked, int userId, int flags,
         in List<String> trustGrantedMessages);
     void onTrustManagedChanged(boolean managed, int userId);
diff --git a/core/java/android/app/trust/TrustManager.java b/core/java/android/app/trust/TrustManager.java
index 62f755d..3552ce0 100644
--- a/core/java/android/app/trust/TrustManager.java
+++ b/core/java/android/app/trust/TrustManager.java
@@ -43,6 +43,7 @@
     private static final int MSG_TRUST_CHANGED = 1;
     private static final int MSG_TRUST_MANAGED_CHANGED = 2;
     private static final int MSG_TRUST_ERROR = 3;
+    private static final int MSG_ENABLED_TRUST_AGENTS_CHANGED = 4;
 
     private static final String TAG = "TrustManager";
     private static final String DATA_FLAGS = "initiatedByUser";
@@ -187,6 +188,13 @@
                 }
 
                 @Override
+                public void onEnabledTrustAgentsChanged(int userId) {
+                    final Message m = mHandler.obtainMessage(MSG_ENABLED_TRUST_AGENTS_CHANGED,
+                            userId, 0, trustListener);
+                    m.sendToTarget();
+                }
+
+                @Override
                 public void onTrustManagedChanged(boolean managed, int userId) {
                     mHandler.obtainMessage(MSG_TRUST_MANAGED_CHANGED, (managed ? 1 : 0), userId,
                             trustListener).sendToTarget();
@@ -283,6 +291,10 @@
                 case MSG_TRUST_ERROR:
                     final CharSequence message = msg.peekData().getCharSequence(DATA_MESSAGE);
                     ((TrustListener) msg.obj).onTrustError(message);
+                    break;
+                case MSG_ENABLED_TRUST_AGENTS_CHANGED:
+                    ((TrustListener) msg.obj).onEnabledTrustAgentsChanged(msg.arg1);
+                    break;
             }
         }
     };
@@ -316,5 +328,10 @@
          * @param message A message that should be displayed on the UI.
          */
         void onTrustError(CharSequence message);
+
+        /**
+         * Reports that the enabled trust agents for the specified user has changed.
+         */
+        void onEnabledTrustAgentsChanged(int userId);
     }
 }
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 7de7c67..518234f 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -473,7 +473,7 @@
     public static final int BIND_IMPORTANT_BACKGROUND = 0x00800000;
 
     /**
-     * @hide Flag for {@link #bindService}: allows application hosting service to manage whitelists
+     * @hide Flag for {@link #bindService}: allows application hosting service to manage allowlists
      * such as temporary allowing a {@code PendingIntent} to bypass Power Save mode.
      */
     public static final int BIND_ALLOW_WHITELIST_MANAGEMENT = 0x01000000;
@@ -3825,6 +3825,7 @@
             VIBRATOR_MANAGER_SERVICE,
             VIBRATOR_SERVICE,
             //@hide: STATUS_BAR_SERVICE,
+            THREAD_NETWORK_SERVICE,
             CONNECTIVITY_SERVICE,
             PAC_PROXY_SERVICE,
             VCN_MANAGEMENT_SERVICE,
@@ -4496,6 +4497,20 @@
 
     /**
      * Use with {@link #getSystemService(String)} to retrieve a
+     * {@link android.net.thread.ThreadNetworkManager}.
+     *
+     * <p>On devices without {@link PackageManager#FEATURE_THREAD_NETWORK} system feature
+     * the {@link #getSystemService(String)} will return {@code null}.
+     *
+     * @see #getSystemService(String)
+     * @see android.net.thread.ThreadNetworkManager
+     * @hide
+     */
+    @SystemApi
+    public static final String THREAD_NETWORK_SERVICE = "thread_network";
+
+    /**
+     * Use with {@link #getSystemService(String)} to retrieve a
      * {@link android.net.IpSecManager} for encrypting Sockets or Networks with
      * IPSec.
      *
@@ -6059,6 +6074,18 @@
 
     /**
      * Use with {@link #getSystemService(String)} to retrieve a
+     * {@link android.remoteauth.RemoteAuthManager} to discover,
+     * register and authenticate via remote authenticator  devices.
+     *
+     * @see #getSystemService(String)
+     * @see android.remoteauth.RemoteAuthManager
+     * @hide
+     */
+    @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
+    public static final String REMOTE_AUTH_SERVICE = "remote_auth";
+
+    /**
+     * Use with {@link #getSystemService(String)} to retrieve a
      * {@link android.app.ambientcontext.AmbientContextManager}.
      *
      * @see #getSystemService(String)
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index 809dc3c4..2e3f1c0 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -4356,6 +4356,7 @@
      */
     @SystemApi
     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+    @RequiresPermission(Manifest.permission.MASTER_CLEAR)
     public static final String ACTION_MASTER_CLEAR_NOTIFICATION
             = "android.intent.action.MASTER_CLEAR_NOTIFICATION";
 
@@ -4479,8 +4480,8 @@
      * @see #EXTRA_SIM_LOCKED_REASON
      * @see #EXTRA_REBROADCAST_ON_UNLOCK
      *
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED} or
-     * {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED} or
+     * {@link android.telephony.TelephonyManager#ACTION_SIM_APPLICATION_STATE_CHANGED}
      *
      * @hide
      */
@@ -4503,42 +4504,42 @@
      * @see #SIM_STATE_IMSI
      * @see #SIM_STATE_LOADED
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     public static final String EXTRA_SIM_STATE = "ss";
 
     /**
      * The intent value UNKNOWN represents the SIM state unknown
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     public static final String SIM_STATE_UNKNOWN = "UNKNOWN";
 
     /**
      * The intent value NOT_READY means that the SIM is not ready eg. radio is off or powering on
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     public static final String SIM_STATE_NOT_READY = "NOT_READY";
 
     /**
      * The intent value ABSENT means the SIM card is missing
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     public static final String SIM_STATE_ABSENT = "ABSENT";
 
     /**
      * The intent value PRESENT means the device has a SIM card inserted
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     public static final String SIM_STATE_PRESENT = "PRESENT";
 
     /**
      * The intent value CARD_IO_ERROR means for three consecutive times there was SIM IO error
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     static public final String SIM_STATE_CARD_IO_ERROR = "CARD_IO_ERROR";
 
@@ -4546,35 +4547,35 @@
      * The intent value CARD_RESTRICTED means card is present but not usable due to carrier
      * restrictions
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     static public final String SIM_STATE_CARD_RESTRICTED = "CARD_RESTRICTED";
 
     /**
      * The intent value LOCKED means the SIM is locked by PIN or by network
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     public static final String SIM_STATE_LOCKED = "LOCKED";
 
     /**
      * The intent value READY means the SIM is ready to be accessed
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     public static final String SIM_STATE_READY = "READY";
 
     /**
      * The intent value IMSI means the SIM IMSI is ready in property
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     public static final String SIM_STATE_IMSI = "IMSI";
 
     /**
      * The intent value LOADED means all SIM records, including IMSI, are loaded
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED}
      */
     public static final String SIM_STATE_LOADED = "LOADED";
 
@@ -4588,21 +4589,24 @@
      * @see #SIM_ABSENT_ON_PERM_DISABLED
      *
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+     * @deprecated Use
+     * {@link android.telephony.TelephonyManager#ACTION_SIM_APPLICATION_STATE_CHANGED}
      */
     public static final String EXTRA_SIM_LOCKED_REASON = "reason";
 
     /**
      * The intent value PIN means the SIM is locked on PIN1
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+     * @deprecated Use
+     * {@link android.telephony.TelephonyManager#ACTION_SIM_APPLICATION_STATE_CHANGED}
      */
     public static final String SIM_LOCKED_ON_PIN = "PIN";
 
     /**
      * The intent value PUK means the SIM is locked on PUK1
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+     * @deprecated Use
+     * {@link android.telephony.TelephonyManager#ACTION_SIM_APPLICATION_STATE_CHANGED}
      */
     /* PUK means ICC is locked on PUK1 */
     public static final String SIM_LOCKED_ON_PUK = "PUK";
@@ -4610,14 +4614,16 @@
     /**
      * The intent value NETWORK means the SIM is locked on NETWORK PERSONALIZATION
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+     * @deprecated Use
+     * {@link android.telephony.TelephonyManager#ACTION_SIM_APPLICATION_STATE_CHANGED}
      */
     public static final String SIM_LOCKED_NETWORK = "NETWORK";
 
     /**
      * The intent value PERM_DISABLED means SIM is permanently disabled due to puk fails
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+     * @deprecated Use
+     * {@link android.telephony.TelephonyManager#ACTION_SIM_APPLICATION_STATE_CHANGED}
      */
     public static final String SIM_ABSENT_ON_PERM_DISABLED = "PERM_DISABLED";
 
@@ -4626,8 +4632,8 @@
      * is a rebroadcast on unlock. Defaults to {@code false} if not specified.
      *
      * @hide
-     * @deprecated Use {@link #ACTION_SIM_CARD_STATE_CHANGED} or
-     * {@link #ACTION_SIM_APPLICATION_STATE_CHANGED}
+     * @deprecated Use {@link android.telephony.TelephonyManager#ACTION_SIM_CARD_STATE_CHANGED} or
+     * {@link android.telephony.TelephonyManager#ACTION_SIM_APPLICATION_STATE_CHANGED}
      */
     public static final String EXTRA_REBROADCAST_ON_UNLOCK = "rebroadcastOnUnlock";
 
diff --git a/core/java/android/content/IntentSender.java b/core/java/android/content/IntentSender.java
index 49d3cac..d4d9e47 100644
--- a/core/java/android/content/IntentSender.java
+++ b/core/java/android/content/IntentSender.java
@@ -392,9 +392,9 @@
     }
 
     /** @hide */
-    public IntentSender(IIntentSender target, IBinder whitelistToken) {
+    public IntentSender(IIntentSender target, IBinder allowlistToken) {
         mTarget = target;
-        mWhitelistToken = whitelistToken;
+        mWhitelistToken = allowlistToken;
     }
 
     /** @hide */
diff --git a/core/java/android/content/om/IOverlayManager.aidl b/core/java/android/content/om/IOverlayManager.aidl
index a0f3d7a..122ab48 100644
--- a/core/java/android/content/om/IOverlayManager.aidl
+++ b/core/java/android/content/om/IOverlayManager.aidl
@@ -190,4 +190,15 @@
      * @throws SecurityException if the transaction failed
      */
     void commit(in OverlayManagerTransaction transaction);
+
+    /**
+     * Returns a String of a list of partitions from low priority to high.
+     */
+    String getPartitionOrder();
+
+    /**
+     * Returns a boolean which represent whether the partition list is sorted by default.
+     * If not then it should be sorted by /product/overlay/partition_order.xml.
+     */
+    boolean isDefaultPartitionOrder();
 }
diff --git a/core/java/android/content/om/OWNERS b/core/java/android/content/om/OWNERS
index 3669817..72aed2d 100644
--- a/core/java/android/content/om/OWNERS
+++ b/core/java/android/content/om/OWNERS
@@ -1,6 +1,5 @@
 # Bug component: 568631
 
-toddke@android.com
-toddke@google.com
 patb@google.com
 zyy@google.com
+jakmcbane@google.com
\ No newline at end of file
diff --git a/core/java/android/content/pm/Checksum.java b/core/java/android/content/pm/Checksum.java
index ff17496..2096727 100644
--- a/core/java/android/content/pm/Checksum.java
+++ b/core/java/android/content/pm/Checksum.java
@@ -40,11 +40,11 @@
     /**
      * Root SHA256 hash of a 4K Merkle tree computed over all file bytes.
      * <a href="https://source.android.com/security/apksigning/v4">See APK Signature Scheme V4</a>.
-     * <a href="https://git.kernel.org/pub/scm/fs/fscrypt/fscrypt.git/tree/Documentation/filesystems/fsverity.rst">See fs-verity</a>.
+     * <a href="https://www.kernel.org/doc/html/latest/filesystems/fsverity.html">See fs-verity</a>.
      *
      * Recommended for all new applications.
      * Can be used by kernel to enforce authenticity and integrity of the APK.
-     * <a href="https://git.kernel.org/pub/scm/fs/fscrypt/fscrypt.git/tree/Documentation/filesystems/fsverity.rst#">See fs-verity for details</a>
+     * <a href="https://www.kernel.org/doc/html/latest/filesystems/fsverity.html">See fs-verity for details</a>
      *
      * @see PackageManager#requestChecksums
      */
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 4677026..0c7fa51 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -1561,6 +1561,14 @@
      */
     public static final int INSTALL_BYPASS_LOW_TARGET_SDK_BLOCK = 0x01000000;
 
+    /**
+     * Flag parameter for {@link #installPackage} to force a non-staged update of an APEX. This is
+     * a development-only feature and should not be used on end user devices.
+     *
+     * @hide
+     */
+    public static final int INSTALL_FORCE_NON_STAGED_APEX_UPDATE = 0x02000000;
+
     /** @hide */
     @IntDef(flag = true, value = {
             DONT_KILL_APP,
@@ -3446,6 +3454,14 @@
             "android.hardware.telephony.subscription";
 
     /**
+     * Feature for {@link #getSystemAvailableFeatures} and {@link #hasSystemFeature}:
+     * The device is capable of communicating with other devices via
+     * <a href="https://www.threadgroup.org">Thread</a> networking protocol.
+     */
+    @SdkConstant(SdkConstantType.FEATURE)
+    public static final String FEATURE_THREAD_NETWORK = "android.hardware.thread_network";
+
+    /**
      * Feature for {@link #getSystemAvailableFeatures} and
      * {@link #hasSystemFeature}: The device is capable of communicating with
      * other devices via ultra wideband.
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index c15b3e0..09b9bda 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -1949,6 +1949,8 @@
         int type;
         boolean foundApp = false;
 
+        String pkgName = (pkg != null) ? pkg.packageName : "<unknown>";
+
         TypedArray sa = res.obtainAttributes(parser,
                 com.android.internal.R.styleable.AndroidManifest);
 
@@ -2218,14 +2220,14 @@
                     sa.recycle();
 
                     final int minSdkVersion = PackageParser.computeMinSdkVersion(minVers, minCode,
-                            SDK_VERSION, SDK_CODENAMES, outError);
+                            SDK_VERSION, SDK_CODENAMES, outError, pkgName);
                     if (minSdkVersion < 0) {
                         mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
                         return null;
                     }
 
                     final int targetSdkVersion = PackageParser.computeTargetSdkVersion(targetVers,
-                            targetCode, SDK_CODENAMES, outError);
+                            targetCode, SDK_CODENAMES, outError, pkgName);
                     if (targetSdkVersion < 0) {
                         mParseError = PackageManager.INSTALL_FAILED_OLDER_SDK;
                         return null;
@@ -2610,13 +2612,15 @@
      * @param platformSdkCodenames array of allowed pre-release SDK codenames
      *                             for this platform
      * @param outError output array to populate with error, if applicable
+     * @param pkgName for debug logging
      * @return the targetSdkVersion to use at runtime, or -1 if the package is
      *         not compatible with this platform
      * @hide Exposed for unit testing only.
      */
     public static int computeTargetSdkVersion(@IntRange(from = 0) int targetVers,
             @Nullable String targetCode, @NonNull String[] platformSdkCodenames,
-            @NonNull String[] outError) {
+            @NonNull String[] outError,
+            String pkgName) {
         // If it's a release SDK, return the version number unmodified.
         if (targetCode == null) {
             return targetVers;
@@ -2628,6 +2632,15 @@
             return Build.VERSION_CODES.CUR_DEVELOPMENT;
         }
 
+        // TODO(b/294161396): add a check for a "true REL" flag.
+        if (platformSdkCodenames.length == 0
+                && Build.VERSION.KNOWN_CODENAMES.stream().max(String::compareTo).orElse("").equals(
+                targetCode)) {
+            Slog.w(TAG, "Package " + pkgName + " requires development platform " + targetCode
+                    + ", returning current version " + Build.VERSION.SDK_INT);
+            return Build.VERSION.SDK_INT;
+        }
+
         // Otherwise, we're looking at an incompatible pre-release SDK.
         if (platformSdkCodenames.length > 0) {
             outError[0] = "Requires development platform " + targetCode
@@ -2674,13 +2687,15 @@
      * @param platformSdkCodenames array of allowed prerelease SDK codenames
      *                             for this platform
      * @param outError output array to populate with error, if applicable
+     * @param pkgName for debug logging
      * @return the minSdkVersion to use at runtime, or -1 if the package is not
      *         compatible with this platform
      * @hide Exposed for unit testing only.
      */
     public static int computeMinSdkVersion(@IntRange(from = 1) int minVers,
             @Nullable String minCode, @IntRange(from = 1) int platformSdkVersion,
-            @NonNull String[] platformSdkCodenames, @NonNull String[] outError) {
+            @NonNull String[] platformSdkCodenames, @NonNull String[] outError,
+            String pkgName) {
         // If it's a release SDK, make sure we meet the minimum SDK requirement.
         if (minCode == null) {
             if (minVers <= platformSdkVersion) {
@@ -2699,6 +2714,15 @@
             return Build.VERSION_CODES.CUR_DEVELOPMENT;
         }
 
+        // TODO(b/294161396): add a check for a "true REL" flag.
+        if (platformSdkCodenames.length == 0
+                && Build.VERSION.KNOWN_CODENAMES.stream().max(String::compareTo).orElse("").equals(
+                minCode)) {
+            Slog.w(TAG, "Package " + pkgName + " requires min development platform " + minCode
+                    + ", returning current version " + Build.VERSION.SDK_INT);
+            return Build.VERSION.SDK_INT;
+        }
+
         // Otherwise, we're looking at an incompatible pre-release SDK.
         if (platformSdkCodenames.length > 0) {
             outError[0] = "Requires development platform " + minCode
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index 295df5c..b85ea36 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -285,6 +285,12 @@
      */
     public static final int DISABLED_REASON_OTHER_RESTORE_ISSUE = 103;
 
+    /**
+     * The maximum length of Shortcut ID. IDs will be truncated at this limit.
+     * @hide
+     */
+    public static final int MAX_ID_LENGTH = 1000;
+
     /** @hide */
     @IntDef(prefix = { "DISABLED_REASON_" }, value = {
             DISABLED_REASON_NOT_DISABLED,
@@ -477,8 +483,7 @@
 
     private ShortcutInfo(Builder b) {
         mUserId = b.mContext.getUserId();
-
-        mId = Preconditions.checkStringNotEmpty(b.mId, "Shortcut ID must be provided");
+        mId = getSafeId(Preconditions.checkStringNotEmpty(b.mId, "Shortcut ID must be provided"));
 
         // Note we can't do other null checks here because SM.updateShortcuts() takes partial
         // information.
@@ -584,6 +589,14 @@
         return ret;
     }
 
+    @NonNull
+    private static String getSafeId(@NonNull String id) {
+        if (id.length() > MAX_ID_LENGTH) {
+            return id.substring(0, MAX_ID_LENGTH);
+        }
+        return id;
+    }
+
     /**
      * Throws if any of the mandatory fields is not set.
      *
@@ -2342,7 +2355,8 @@
         final ClassLoader cl = getClass().getClassLoader();
 
         mUserId = source.readInt();
-        mId = source.readString8();
+        mId = getSafeId(Preconditions.checkStringNotEmpty(source.readString8(),
+                "Shortcut ID must be provided"));
         mPackageName = source.readString8();
         mActivity = source.readParcelable(cl, android.content.ComponentName.class);
         mFlags = source.readInt();
diff --git a/core/java/android/content/pm/parsing/ApkLiteParseUtils.java b/core/java/android/content/pm/parsing/ApkLiteParseUtils.java
index 10d6f2d..7d995d0 100644
--- a/core/java/android/content/pm/parsing/ApkLiteParseUtils.java
+++ b/core/java/android/content/pm/parsing/ApkLiteParseUtils.java
@@ -577,14 +577,14 @@
 
                 ParseResult<Integer> targetResult = FrameworkParsingPackageUtils.computeTargetSdkVersion(
                         targetVer, targetCode, SDK_CODENAMES, input,
-                        allowUnknownCodenames);
+                        allowUnknownCodenames, codePath);
                 if (targetResult.isError()) {
                     return input.error(targetResult);
                 }
                 targetSdkVersion = targetResult.getResult();
 
                 ParseResult<Integer> minResult = FrameworkParsingPackageUtils.computeMinSdkVersion(
-                        minVer, minCode, SDK_VERSION, SDK_CODENAMES, input);
+                        minVer, minCode, SDK_VERSION, SDK_CODENAMES, input, codePath);
                 if (minResult.isError()) {
                     return input.error(minResult);
                 }
diff --git a/core/java/android/content/pm/parsing/FrameworkParsingPackageUtils.java b/core/java/android/content/pm/parsing/FrameworkParsingPackageUtils.java
index 3e1c5bb..30e289f 100644
--- a/core/java/android/content/pm/parsing/FrameworkParsingPackageUtils.java
+++ b/core/java/android/content/pm/parsing/FrameworkParsingPackageUtils.java
@@ -293,11 +293,14 @@
      *                             {@code null} otherwise
      * @param platformSdkVersion   platform SDK version number, typically Build.VERSION.SDK_INT
      * @param platformSdkCodenames array of allowed prerelease SDK codenames for this platform
+     * @param input                parsing context
+     * @param pkgName              for debug logging
      * @return the minSdkVersion to use at runtime if successful
      */
     public static ParseResult<Integer> computeMinSdkVersion(@IntRange(from = 1) int minVers,
             @Nullable String minCode, @IntRange(from = 1) int platformSdkVersion,
-            @NonNull String[] platformSdkCodenames, @NonNull ParseInput input) {
+            @NonNull String[] platformSdkCodenames, @NonNull ParseInput input,
+            String pkgName) {
         // If it's a release SDK, make sure we meet the minimum SDK requirement.
         if (minCode == null) {
             if (minVers <= platformSdkVersion) {
@@ -316,6 +319,15 @@
             return input.success(Build.VERSION_CODES.CUR_DEVELOPMENT);
         }
 
+        // TODO(b/294161396): add a check for a "true REL" flag.
+        if (platformSdkCodenames.length == 0
+                && Build.VERSION.KNOWN_CODENAMES.stream().max(String::compareTo).orElse("").equals(
+                        minCode)) {
+            Slog.w(TAG, "Parsed package " + pkgName + " requires min development platform "
+                    + minCode + ", returning current version " + Build.VERSION.SDK_INT);
+            return input.success(Build.VERSION.SDK_INT);
+        }
+
         // Otherwise, we're looking at an incompatible pre-release SDK.
         if (platformSdkCodenames.length > 0) {
             return input.error(PackageManager.INSTALL_FAILED_OLDER_SDK,
@@ -358,29 +370,38 @@
      * @param platformSdkCodenames  array of allowed pre-release SDK codenames for this platform
      * @param allowUnknownCodenames allow unknown codenames, if true this method will accept unknown
      *                              (presumed to be future) codenames
+     * @param pkgName               for debug logging
      * @return the targetSdkVersion to use at runtime if successful
      */
     public static ParseResult<Integer> computeTargetSdkVersion(@IntRange(from = 0) int targetVers,
             @Nullable String targetCode, @NonNull String[] platformSdkCodenames,
-            @NonNull ParseInput input, boolean allowUnknownCodenames) {
+            @NonNull ParseInput input, boolean allowUnknownCodenames,
+            String pkgName) {
         // If it's a release SDK, return the version number unmodified.
         if (targetCode == null) {
             return input.success(targetVers);
         }
 
+        // TODO(b/294161396): add a check for a "true REL" flag.
+        // If it's a pre-release SDK and the codename matches this platform, it
+        // definitely targets this SDK.
+        if (matchTargetCode(platformSdkCodenames, targetCode)) {
+            return input.success(Build.VERSION_CODES.CUR_DEVELOPMENT);
+        }
+        if (platformSdkCodenames.length == 0
+                && Build.VERSION.KNOWN_CODENAMES.stream().max(String::compareTo).orElse("").equals(
+                        targetCode)) {
+            Slog.w(TAG, "Parsed package " + pkgName + " requires development platform " + targetCode
+                    + ", returning current version " + Build.VERSION.SDK_INT);
+            return input.success(Build.VERSION.SDK_INT);
+        }
+
         try {
             if (allowUnknownCodenames && UnboundedSdkLevel.isAtMost(targetCode)) {
                 return input.success(Build.VERSION_CODES.CUR_DEVELOPMENT);
             }
         } catch (IllegalArgumentException e) {
-            // isAtMost() throws it when encountering an older SDK codename
-            return input.error(PackageManager.INSTALL_FAILED_OLDER_SDK, e.getMessage());
-        }
-
-        // If it's a pre-release SDK and the codename matches this platform, it
-        // definitely targets this SDK.
-        if (matchTargetCode(platformSdkCodenames, targetCode)) {
-            return input.success(Build.VERSION_CODES.CUR_DEVELOPMENT);
+            return input.error(PackageManager.INSTALL_FAILED_OLDER_SDK, "Bad package SDK");
         }
 
         // Otherwise, we're looking at an incompatible pre-release SDK.
diff --git a/core/java/android/content/res/OWNERS b/core/java/android/content/res/OWNERS
index d12d920..6b128a9 100644
--- a/core/java/android/content/res/OWNERS
+++ b/core/java/android/content/res/OWNERS
@@ -1,6 +1,7 @@
 # Bug component: 568761
 
-toddke@android.com
-toddke@google.com
 patb@google.com
 zyy@google.com
+branliu@google.com
+
+per-file FontScaleConverter*=fuego@google.com
diff --git a/core/java/android/content/res/Resources.java b/core/java/android/content/res/Resources.java
index 9b16949..c8dbfc91 100644
--- a/core/java/android/content/res/Resources.java
+++ b/core/java/android/content/res/Resources.java
@@ -53,6 +53,7 @@
 import android.graphics.drawable.DrawableInflater;
 import android.os.Build;
 import android.os.Bundle;
+import android.os.SystemClock;
 import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.AttributeSet;
@@ -132,6 +133,11 @@
     private static final Object sSync = new Object();
     private final Object mUpdateLock = new Object();
 
+    /**
+     * Controls whether we should preload resources during zygote init.
+     */
+    private static final boolean PRELOAD_RESOURCES = true;
+
     // Used by BridgeResources in layoutlib
     @UnsupportedAppUsage
     static Resources mSystem = null;
@@ -2666,6 +2672,98 @@
         }
     }
 
+    /**
+     * Load in commonly used resources, so they can be shared across processes.
+     *
+     * These tend to be a few Kbytes, but are frequently in the 20-40K range, and occasionally even
+     * larger.
+     * @hide
+     */
+    @UnsupportedAppUsage
+    public static void preloadResources() {
+        try {
+            final Resources sysRes = Resources.getSystem();
+            sysRes.startPreloading();
+            if (PRELOAD_RESOURCES) {
+                Log.i(TAG, "Preloading resources...");
+
+                long startTime = SystemClock.uptimeMillis();
+                TypedArray ar = sysRes.obtainTypedArray(
+                        com.android.internal.R.array.preloaded_drawables);
+                int numberOfEntries = preloadDrawables(sysRes, ar);
+                ar.recycle();
+                Log.i(TAG, "...preloaded " + numberOfEntries + " resources in "
+                        + (SystemClock.uptimeMillis() - startTime) + "ms.");
+
+                startTime = SystemClock.uptimeMillis();
+                ar = sysRes.obtainTypedArray(
+                        com.android.internal.R.array.preloaded_color_state_lists);
+                numberOfEntries = preloadColorStateLists(sysRes, ar);
+                ar.recycle();
+                Log.i(TAG, "...preloaded " + numberOfEntries + " resources in "
+                        + (SystemClock.uptimeMillis() - startTime) + "ms.");
+
+                if (sysRes.getBoolean(
+                        com.android.internal.R.bool.config_freeformWindowManagement)) {
+                    startTime = SystemClock.uptimeMillis();
+                    ar = sysRes.obtainTypedArray(
+                            com.android.internal.R.array.preloaded_freeform_multi_window_drawables);
+                    numberOfEntries = preloadDrawables(sysRes, ar);
+                    ar.recycle();
+                    Log.i(TAG, "...preloaded " + numberOfEntries + " resource in "
+                            + (SystemClock.uptimeMillis() - startTime) + "ms.");
+                }
+            }
+            sysRes.finishPreloading();
+        } catch (RuntimeException e) {
+            Log.w(TAG, "Failure preloading resources", e);
+        }
+    }
+
+    private static int preloadColorStateLists(Resources resources, TypedArray ar) {
+        final int numberOfEntries = ar.length();
+        for (int i = 0; i < numberOfEntries; i++) {
+            int id = ar.getResourceId(i, 0);
+
+            if (id != 0) {
+                if (resources.getColorStateList(id, null) == null) {
+                    throw new IllegalArgumentException(
+                            "Unable to find preloaded color resource #0x"
+                                    + Integer.toHexString(id)
+                                    + " (" + ar.getString(i) + ")");
+                }
+            }
+        }
+        return numberOfEntries;
+    }
+
+    private static int preloadDrawables(Resources resources, TypedArray ar) {
+        final int numberOfEntries = ar.length();
+        for (int i = 0; i < numberOfEntries; i++) {
+            int id = ar.getResourceId(i, 0);
+
+            if (id != 0) {
+                if (resources.getDrawable(id, null) == null) {
+                    throw new IllegalArgumentException(
+                            "Unable to find preloaded drawable resource #0x"
+                                    + Integer.toHexString(id)
+                                    + " (" + ar.getString(i) + ")");
+                }
+            }
+        }
+        return numberOfEntries;
+    }
+
+    /**
+     * Clear the cache when the framework resources packages is changed.
+     * @hide
+     */
+    @VisibleForTesting
+    public static void resetPreloadDrawableStateCache() {
+        ResourcesImpl.resetDrawableStateCache();
+        preloadResources();
+    }
+
     /** @hide */
     public void dump(PrintWriter pw, String prefix) {
         pw.println(prefix + "class=" + getClass());
diff --git a/core/java/android/content/res/ResourcesImpl.java b/core/java/android/content/res/ResourcesImpl.java
index 3bb237a..480e43e 100644
--- a/core/java/android/content/res/ResourcesImpl.java
+++ b/core/java/android/content/res/ResourcesImpl.java
@@ -52,6 +52,7 @@
 import android.util.Xml;
 import android.view.DisplayAdjustments;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.util.GrowingArrayUtils;
 
 import libcore.util.NativeAllocationRegistry;
@@ -159,6 +160,23 @@
     }
 
     /**
+     * Clear the cache when the framework resources packages is changed.
+     *
+     * It's only used in the test initial function instead of regular app behaviors. It doesn't
+     * guarantee the thread-safety so mark this with @VisibleForTesting.
+     */
+    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
+    static void resetDrawableStateCache() {
+        synchronized (sSync) {
+            sPreloadedDrawables[0].clear();
+            sPreloadedDrawables[1].clear();
+            sPreloadedColorDrawables.clear();
+            sPreloadedComplexColors.clear();
+            sPreloaded = false;
+        }
+    }
+
+    /**
      * Creates a new ResourcesImpl object with CompatibilityInfo.
      *
      * @param assets Previously created AssetManager.
diff --git a/core/java/android/database/OWNERS b/core/java/android/database/OWNERS
index 7e19942..53f5bb0 100644
--- a/core/java/android/database/OWNERS
+++ b/core/java/android/database/OWNERS
@@ -1,3 +1,6 @@
+include /SQLITE_OWNERS
+
 omakoto@google.com
 jsharkey@android.com
 yamasani@google.com
+
diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java
index 0d0615a..7d095d8 100644
--- a/core/java/android/database/sqlite/SQLiteDatabase.java
+++ b/core/java/android/database/sqlite/SQLiteDatabase.java
@@ -888,7 +888,7 @@
      * Open the database according to the flags {@link #OPEN_READWRITE}
      * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
      *
-     * <p>Sets the locale of the database to the  the system's current locale.
+     * <p>Sets the locale of the database to the system's current locale.
      * Call {@link #setLocale} if you would like something else.</p>
      *
      * @param path to database file to open and/or create
@@ -934,7 +934,7 @@
      * Open the database according to the flags {@link #OPEN_READWRITE}
      * {@link #OPEN_READONLY} {@link #CREATE_IF_NECESSARY} and/or {@link #NO_LOCALIZED_COLLATORS}.
      *
-     * <p>Sets the locale of the database to the  the system's current locale.
+     * <p>Sets the locale of the database to the system's current locale.
      * Call {@link #setLocale} if you would like something else.</p>
      *
      * <p>Accepts input param: a concrete instance of {@link DatabaseErrorHandler} to be
@@ -1095,7 +1095,7 @@
      * Create a memory backed SQLite database.  Its contents will be destroyed
      * when the database is closed.
      *
-     * <p>Sets the locale of the database to the  the system's current locale.
+     * <p>Sets the locale of the database to the system's current locale.
      * Call {@link #setLocale} if you would like something else.</p>
      *
      * @param factory an optional factory class that is called to instantiate a
@@ -1114,7 +1114,7 @@
      * Create a memory backed SQLite database.  Its contents will be destroyed
      * when the database is closed.
      *
-     * <p>Sets the locale of the database to the  the system's current locale.
+     * <p>Sets the locale of the database to the system's current locale.
      * Call {@link #setLocale} if you would like something else.</p>
      * @param openParams configuration parameters that are used for opening SQLiteDatabase
      * @return a SQLiteDatabase instance
diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java
index ccc39b6..03964438 100644
--- a/core/java/android/hardware/Camera.java
+++ b/core/java/android/hardware/Camera.java
@@ -41,11 +41,6 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.ServiceManager;
-import android.renderscript.Allocation;
-import android.renderscript.Element;
-import android.renderscript.RSIllegalArgumentException;
-import android.renderscript.RenderScript;
-import android.renderscript.Type;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.Surface;
@@ -1007,132 +1002,6 @@
     private native final void _addCallbackBuffer(
                                 byte[] callbackBuffer, int msgType);
 
-    /**
-     * <p>Create a {@link android.renderscript RenderScript}
-     * {@link android.renderscript.Allocation Allocation} to use as a
-     * destination of preview callback frames. Use
-     * {@link #setPreviewCallbackAllocation setPreviewCallbackAllocation} to use
-     * the created Allocation as a destination for camera preview frames.</p>
-     *
-     * <p>The Allocation will be created with a YUV type, and its contents must
-     * be accessed within Renderscript with the {@code rsGetElementAtYuv_*}
-     * accessor methods. Its size will be based on the current
-     * {@link Parameters#getPreviewSize preview size} configured for this
-     * camera.</p>
-     *
-     * @param rs the RenderScript context for this Allocation.
-     * @param usage additional usage flags to set for the Allocation. The usage
-     *   flag {@link android.renderscript.Allocation#USAGE_IO_INPUT} will always
-     *   be set on the created Allocation, but additional flags may be provided
-     *   here.
-     * @return a new YUV-type Allocation with dimensions equal to the current
-     *   preview size.
-     * @throws RSIllegalArgumentException if the usage flags are not compatible
-     *   with an YUV Allocation.
-     * @see #setPreviewCallbackAllocation
-     * @hide
-     */
-    public final Allocation createPreviewAllocation(RenderScript rs, int usage)
-            throws RSIllegalArgumentException {
-        Parameters p = getParameters();
-        Size previewSize = p.getPreviewSize();
-        Type.Builder yuvBuilder = new Type.Builder(rs,
-                Element.createPixel(rs,
-                        Element.DataType.UNSIGNED_8,
-                        Element.DataKind.PIXEL_YUV));
-        // Use YV12 for wide compatibility. Changing this requires also
-        // adjusting camera service's format selection.
-        yuvBuilder.setYuvFormat(ImageFormat.YV12);
-        yuvBuilder.setX(previewSize.width);
-        yuvBuilder.setY(previewSize.height);
-
-        Allocation a = Allocation.createTyped(rs, yuvBuilder.create(),
-                usage | Allocation.USAGE_IO_INPUT);
-
-        return a;
-    }
-
-    /**
-     * <p>Set an {@link android.renderscript.Allocation Allocation} as the
-     * target of preview callback data. Use this method for efficient processing
-     * of camera preview data with RenderScript. The Allocation must be created
-     * with the {@link #createPreviewAllocation createPreviewAllocation }
-     * method.</p>
-     *
-     * <p>Setting a preview allocation will disable any active preview callbacks
-     * set by {@link #setPreviewCallback setPreviewCallback} or
-     * {@link #setPreviewCallbackWithBuffer setPreviewCallbackWithBuffer}, and
-     * vice versa. Using a preview allocation still requires an active standard
-     * preview target to be set, either with
-     * {@link #setPreviewTexture setPreviewTexture} or
-     * {@link #setPreviewDisplay setPreviewDisplay}.</p>
-     *
-     * <p>To be notified when new frames are available to the Allocation, use
-     * {@link android.renderscript.Allocation#setIoInputNotificationHandler Allocation.setIoInputNotificationHandler}. To
-     * update the frame currently accessible from the Allocation to the latest
-     * preview frame, call
-     * {@link android.renderscript.Allocation#ioReceive Allocation.ioReceive}.</p>
-     *
-     * <p>To disable preview into the Allocation, call this method with a
-     * {@code null} parameter.</p>
-     *
-     * <p>Once a preview allocation is set, the preview size set by
-     * {@link Parameters#setPreviewSize setPreviewSize} cannot be changed. If
-     * you wish to change the preview size, first remove the preview allocation
-     * by calling {@code setPreviewCallbackAllocation(null)}, then change the
-     * preview size, create a new preview Allocation with
-     * {@link #createPreviewAllocation createPreviewAllocation}, and set it as
-     * the new preview callback allocation target.</p>
-     *
-     * <p>If you are using the preview data to create video or still images,
-     * strongly consider using {@link android.media.MediaActionSound} to
-     * properly indicate image capture or recording start/stop to the user.</p>
-     *
-     * @param previewAllocation the allocation to use as destination for preview
-     * @throws IOException if configuring the camera to use the Allocation for
-     *   preview fails.
-     * @throws IllegalArgumentException if the Allocation's dimensions or other
-     *   parameters don't meet the requirements.
-     * @see #createPreviewAllocation
-     * @see #setPreviewCallback
-     * @see #setPreviewCallbackWithBuffer
-     * @hide
-     */
-    public final void setPreviewCallbackAllocation(Allocation previewAllocation)
-            throws IOException {
-        Surface previewSurface = null;
-        if (previewAllocation != null) {
-             Parameters p = getParameters();
-             Size previewSize = p.getPreviewSize();
-             if (previewSize.width != previewAllocation.getType().getX() ||
-                     previewSize.height != previewAllocation.getType().getY()) {
-                 throw new IllegalArgumentException(
-                     "Allocation dimensions don't match preview dimensions: " +
-                     "Allocation is " +
-                     previewAllocation.getType().getX() +
-                     ", " +
-                     previewAllocation.getType().getY() +
-                     ". Preview is " + previewSize.width + ", " +
-                     previewSize.height);
-             }
-             if ((previewAllocation.getUsage() &
-                             Allocation.USAGE_IO_INPUT) == 0) {
-                 throw new IllegalArgumentException(
-                     "Allocation usage does not include USAGE_IO_INPUT");
-             }
-             if (previewAllocation.getType().getElement().getDataKind() !=
-                     Element.DataKind.PIXEL_YUV) {
-                 throw new IllegalArgumentException(
-                     "Allocation is not of a YUV type");
-             }
-             previewSurface = previewAllocation.getSurface();
-             mUsingPreviewAllocation = true;
-         } else {
-             mUsingPreviewAllocation = false;
-         }
-         setPreviewCallbackSurface(previewSurface);
-    }
-
     private native final void setPreviewCallbackSurface(Surface s);
 
     private class EventHandler extends Handler
diff --git a/core/java/android/hardware/SensorAdditionalInfo.java b/core/java/android/hardware/SensorAdditionalInfo.java
index 59def9f..d1e101d 100644
--- a/core/java/android/hardware/SensorAdditionalInfo.java
+++ b/core/java/android/hardware/SensorAdditionalInfo.java
@@ -257,7 +257,7 @@
     public static SensorAdditionalInfo createLocalGeomagneticField(
             float strength, float declination, float inclination) {
         if (strength < 10 || strength > 100 // much beyond extreme values on earth
-                || declination < 0 || declination > Math.PI
+                || declination < -Math.PI / 2 || declination > Math.PI / 2
                 || inclination < -Math.PI / 2 || inclination > Math.PI / 2) {
             throw new IllegalArgumentException("Geomagnetic field info out of range");
         }
diff --git a/core/java/android/hardware/biometrics/flags.aconfig b/core/java/android/hardware/biometrics/flags.aconfig
new file mode 100644
index 0000000..0924e0d1
--- /dev/null
+++ b/core/java/android/hardware/biometrics/flags.aconfig
@@ -0,0 +1,8 @@
+package: "android.hardware.biometrics"
+
+flag {
+  name: "add_key_agreement_crypto_object"
+  namespace: "biometrics"
+  description: "Feature flag for adding KeyAgreement api to CryptoObject."
+  bug: "282058146"
+}
diff --git a/core/java/android/hardware/camera2/CameraDevice.java b/core/java/android/hardware/camera2/CameraDevice.java
index 2f81e0c..106b7d4 100644
--- a/core/java/android/hardware/camera2/CameraDevice.java
+++ b/core/java/android/hardware/camera2/CameraDevice.java
@@ -540,14 +540,6 @@
      *   or configuring it to use one of the supported
      *   {@link android.media.CamcorderProfile CamcorderProfiles}.</li>
      *
-     * <li>For efficient YUV processing with {@link android.renderscript}:
-     *   Create a RenderScript
-     *   {@link android.renderscript.Allocation Allocation} with a supported YUV
-     *   type, the IO_INPUT flag, and one of the sizes returned by
-     *   {@link StreamConfigurationMap#getOutputSizes(Class) getOutputSizes(Allocation.class)},
-     *   Then obtain the Surface with
-     *   {@link android.renderscript.Allocation#getSurface}.</li>
-     *
      * <li>For access to RAW, uncompressed YUV, or compressed JPEG data in the application: Create an
      *   {@link android.media.ImageReader} object with one of the supported output formats given by
      *   {@link StreamConfigurationMap#getOutputFormats()}, setting its size to one of the
diff --git a/core/java/android/hardware/camera2/camera_platform.aconfig b/core/java/android/hardware/camera2/camera_platform.aconfig
new file mode 100644
index 0000000..67f6300
--- /dev/null
+++ b/core/java/android/hardware/camera2/camera_platform.aconfig
@@ -0,0 +1,8 @@
+package: "com.android.hardware.camera2"
+
+flag {
+     namespace: "camera_platform"
+     name: "initial_test_flag"
+     description: "Flag infrastructure test flag"
+     bug: "292631208"
+}
diff --git a/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java
index 02e7f60..c8e2ccc 100644
--- a/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraAdvancedExtensionSessionImpl.java
@@ -221,7 +221,7 @@
         List<CameraOutputConfig> outputConfigs = sessionConfig.outputConfigs;
         ArrayList<OutputConfiguration> outputList = new ArrayList<>();
         for (CameraOutputConfig output : outputConfigs) {
-            Surface outputSurface = initializeSurfrace(output);
+            Surface outputSurface = initializeSurface(output);
             if (outputSurface == null) {
                 continue;
             }
@@ -234,7 +234,7 @@
             if ((output.sharedSurfaceConfigs != null) && !output.sharedSurfaceConfigs.isEmpty()) {
                 cameraOutput.enableSurfaceSharing();
                 for (CameraOutputConfig sharedOutputConfig : output.sharedSurfaceConfigs) {
-                    Surface sharedSurface = initializeSurfrace(sharedOutputConfig);
+                    Surface sharedSurface = initializeSurface(sharedOutputConfig);
                     if (sharedSurface == null) {
                         continue;
                     }
@@ -989,7 +989,7 @@
         return ret;
     }
 
-    private Surface initializeSurfrace(CameraOutputConfig output) {
+    private Surface initializeSurface(CameraOutputConfig output) {
         switch(output.type) {
             case CameraOutputConfig.TYPE_SURFACE:
                 if (output.surface == null) {
diff --git a/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java
index 2156c12..efb3510 100644
--- a/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraExtensionSessionImpl.java
@@ -1942,10 +1942,10 @@
             HashMap<Integer, Pair<Image, TotalCaptureResult>> captureMap, Integer jpegOrientation,
             Byte jpegQuality) {
         ArrayList<CaptureBundle> ret = new ArrayList<>();
-        for (Integer stagetId : captureMap.keySet()) {
-            Pair<Image, TotalCaptureResult> entry = captureMap.get(stagetId);
+        for (Integer stageId : captureMap.keySet()) {
+            Pair<Image, TotalCaptureResult> entry = captureMap.get(stageId);
             CaptureBundle bundle = new CaptureBundle();
-            bundle.stage = stagetId;
+            bundle.stage = stageId;
             bundle.captureImage = initializeParcelImage(entry.first);
             bundle.sequenceId = entry.second.getSequenceId();
             bundle.captureResult = entry.second.getNativeMetadata();
diff --git a/core/java/android/hardware/camera2/params/StreamConfigurationMap.java b/core/java/android/hardware/camera2/params/StreamConfigurationMap.java
index 5981d27..a89fed2 100644
--- a/core/java/android/hardware/camera2/params/StreamConfigurationMap.java
+++ b/core/java/android/hardware/camera2/params/StreamConfigurationMap.java
@@ -465,8 +465,6 @@
      * Recommended for recording video (simple to use)
      * <li>{@link android.media.MediaCodec} -
      * Recommended for recording video (more complicated to use, with more flexibility)
-     * <li>{@link android.renderscript.Allocation} -
-     * Recommended for image processing with {@link android.renderscript RenderScript}
      * <li>{@link android.view.SurfaceHolder} -
      * Recommended for low-power camera preview with {@link android.view.SurfaceView}
      * <li>{@link android.graphics.SurfaceTexture} -
diff --git a/core/java/android/hardware/input/input_framework.aconfig b/core/java/android/hardware/input/input_framework.aconfig
new file mode 100644
index 0000000..ebfe66f5
--- /dev/null
+++ b/core/java/android/hardware/input/input_framework.aconfig
@@ -0,0 +1,19 @@
+package: "com.android.hardware.input"
+
+# Project link: https://gantry.corp.google.com/projects/android_platform_input_native/changes
+
+flag {
+    namespace: "input_native"
+    name: "keyboard_layout_preview_flag"
+    description: "Controls whether a preview will be shown in Settings when selecting a physical keyboard layout"
+    bug: "293579375"
+}
+
+
+flag {
+    namespace: "input_native"
+    name: "keyboard_a11y_sticky_keys_flag"
+    description: "Controls if the sticky keys accessibility feature for physical keyboard is available to the user"
+    bug: "294546335"
+}
+
diff --git a/core/java/android/net/VpnService.java b/core/java/android/net/VpnService.java
index 1ae1b050d..37bd67a 100644
--- a/core/java/android/net/VpnService.java
+++ b/core/java/android/net/VpnService.java
@@ -537,8 +537,15 @@
         }
 
         /**
-         * Sets an HTTP proxy for the VPN network. This proxy is only a recommendation
-         * and it is possible that some apps will ignore it. PAC proxies are not supported.
+         * Sets an HTTP proxy for the VPN network.
+         * <p class="note">This proxy is only a recommendation and it is possible that some apps
+         * will ignore it.
+         * <p class="note">PAC proxies are not supported over VPNs.
+         * <p class="note">Apps that do use the proxy cannot distinguish between routes handled
+         * and not handled by the VPN and will try to access HTTP resources over the proxy
+         * regardless of the destination. In practice this means using a proxy with a split
+         * tunnel generally won't work as expected, because HTTP accesses on routes not handled by
+         * the VPN will not reach as the proxy won't be available outside of the VPN network.
          */
         @NonNull
         public Builder setHttpProxy(@NonNull ProxyInfo proxyInfo) {
diff --git a/core/java/android/net/metrics/WakeupEvent.java b/core/java/android/net/metrics/WakeupEvent.java
index af9a73c..53a3ea5 100644
--- a/core/java/android/net/metrics/WakeupEvent.java
+++ b/core/java/android/net/metrics/WakeupEvent.java
@@ -29,7 +29,7 @@
     public String iface;
     public int uid;
     public int ethertype;
-    public MacAddress dstHwAddr;
+    public MacAddress dstHwAddr;  // actually used to store a src mac address
     public String srcIp;
     public String dstIp;
     public int ipNextHeader;
@@ -44,7 +44,7 @@
         j.add(iface);
         j.add("uid: " + Integer.toString(uid));
         j.add("eth=0x" + Integer.toHexString(ethertype));
-        j.add("dstHw=" + dstHwAddr);
+        j.add("srcMac=" + dstHwAddr);  // really!! http://b/292404319#comment11
         if (ipNextHeader > 0) {
             j.add("ipNxtHdr=" + ipNextHeader);
             j.add("srcIp=" + srcIp);
diff --git a/core/java/android/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java
index b749d69..1307dfc 100644
--- a/core/java/android/nfc/NfcAdapter.java
+++ b/core/java/android/nfc/NfcAdapter.java
@@ -484,7 +484,6 @@
     /**
      * A callback to be invoked when the system successfully delivers your {@link NdefMessage}
      * to another device.
-     * @see #setOnNdefPushCompleteCallback
      * @deprecated this feature is removed. File sharing can work using other technology like
      * Bluetooth.
      */
@@ -496,7 +495,6 @@
          * <p>This callback is usually made on a binder thread (not the UI thread).
          *
          * @param event {@link NfcEvent} with the {@link NfcEvent#nfcAdapter} field set
-         * @see #setNdefPushMessageCallback
          */
         public void onNdefPushComplete(NfcEvent event);
     }
@@ -504,11 +502,11 @@
     /**
      * A callback to be invoked when another NFC device capable of NDEF push (Android Beam)
      * is within range.
-     * <p>Implement this interface and pass it to {@link
+     * <p>Implement this interface and pass it to {@code
      * NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()} in order to create an
      * {@link NdefMessage} at the moment that another device is within range for NFC. Using this
      * callback allows you to create a message with data that might vary based on the
-     * content currently visible to the user. Alternatively, you can call {@link
+     * content currently visible to the user. Alternatively, you can call {@code
      * #setNdefPushMessage setNdefPushMessage()} if the {@link NdefMessage} always contains the
      * same data.
      * @deprecated this feature is removed. File sharing can work using other technology like
@@ -600,6 +598,17 @@
         return offHostSE;
     }
 
+    private static void retrieveServiceRegisterer() {
+        if (sServiceRegisterer == null) {
+            NfcServiceManager manager = NfcFrameworkInitializer.getNfcServiceManager();
+            if (manager == null) {
+                Log.e(TAG, "NfcServiceManager is null");
+                throw new UnsupportedOperationException();
+            }
+            sServiceRegisterer = manager.getNfcManagerServiceRegisterer();
+        }
+    }
+
     /**
      * Returns the NfcAdapter for application context,
      * or throws if NFC is not available.
@@ -627,12 +636,7 @@
                 Log.v(TAG, "this device does not have NFC support");
                 throw new UnsupportedOperationException();
             }
-            NfcServiceManager manager = NfcFrameworkInitializer.getNfcServiceManager();
-            if (manager == null) {
-                Log.e(TAG, "NfcServiceManager is null");
-                throw new UnsupportedOperationException();
-            }
-            sServiceRegisterer = manager.getNfcManagerServiceRegisterer();
+            retrieveServiceRegisterer();
             sService = getServiceInterface();
             if (sService == null) {
                 Log.e(TAG, "could not retrieve NFC service");
@@ -642,6 +646,7 @@
                 try {
                     sTagService = sService.getNfcTagInterface();
                 } catch (RemoteException e) {
+                    sTagService = null;
                     Log.e(TAG, "could not retrieve NFC Tag service");
                     throw new UnsupportedOperationException();
                 }
@@ -650,12 +655,14 @@
                 try {
                     sNfcFCardEmulationService = sService.getNfcFCardEmulationInterface();
                 } catch (RemoteException e) {
+                    sNfcFCardEmulationService = null;
                     Log.e(TAG, "could not retrieve NFC-F card emulation service");
                     throw new UnsupportedOperationException();
                 }
                 try {
                     sCardEmulationService = sService.getNfcCardEmulationInterface();
                 } catch (RemoteException e) {
+                    sCardEmulationService = null;
                     Log.e(TAG, "could not retrieve card emulation service");
                     throw new UnsupportedOperationException();
                 }
@@ -703,12 +710,15 @@
             throw new IllegalArgumentException(
                     "context not associated with any application (using a mock context?)");
         }
-
-        if (sIsInitialized && sServiceRegisterer.tryGet() == null) {
-            synchronized (NfcAdapter.class) {
-                /* Stale sService pointer */
-                if (sIsInitialized) sIsInitialized = false;
+        retrieveServiceRegisterer();
+        if (sServiceRegisterer.tryGet() == null) {
+            if (sIsInitialized) {
+                synchronized (NfcAdapter.class) {
+                    /* Stale sService pointer */
+                    if (sIsInitialized) sIsInitialized = false;
+                }
             }
+            return null;
         }
         /* Try to initialize the service */
         NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
@@ -838,30 +848,54 @@
         // assigning to sService is not thread-safe, but this is best-effort code
         // and on a well-behaved system should never happen
         sService = service;
-        try {
-            sTagService = service.getNfcTagInterface();
-        } catch (RemoteException ee) {
-            Log.e(TAG, "could not retrieve NFC tag service during service recovery");
-            // nothing more can be done now, sService is still stale, we'll hit
-            // this recovery path again later
-            return;
+        if (sHasNfcFeature) {
+            try {
+                sTagService = service.getNfcTagInterface();
+            } catch (RemoteException ee) {
+                sTagService = null;
+                Log.e(TAG, "could not retrieve NFC tag service during service recovery");
+                // nothing more can be done now, sService is still stale, we'll hit
+                // this recovery path again later
+                return;
+            }
         }
 
-        try {
-            sCardEmulationService = service.getNfcCardEmulationInterface();
-        } catch (RemoteException ee) {
-            Log.e(TAG, "could not retrieve NFC card emulation service during service recovery");
-        }
+        if (sHasCeFeature) {
+            try {
+                sCardEmulationService = service.getNfcCardEmulationInterface();
+            } catch (RemoteException ee) {
+                sCardEmulationService = null;
+                Log.e(TAG,
+                        "could not retrieve NFC card emulation service during service recovery");
+            }
 
-        try {
-            sNfcFCardEmulationService = service.getNfcFCardEmulationInterface();
-        } catch (RemoteException ee) {
-            Log.e(TAG, "could not retrieve NFC-F card emulation service during service recovery");
+            try {
+                sNfcFCardEmulationService = service.getNfcFCardEmulationInterface();
+            } catch (RemoteException ee) {
+                sNfcFCardEmulationService = null;
+                Log.e(TAG,
+                        "could not retrieve NFC-F card emulation service during service recovery");
+            }
         }
 
         return;
     }
 
+    private boolean isCardEmulationEnabled() {
+        if (sHasCeFeature) {
+            return (sCardEmulationService != null || sNfcFCardEmulationService != null);
+        }
+        return false;
+    }
+
+    private boolean isTagReadingEnabled() {
+        if (sHasNfcFeature) {
+            return sTagService != null;
+        }
+        return false;
+    }
+
+
     /**
      * Return true if this NFC Adapter has any features enabled.
      *
@@ -875,8 +909,9 @@
      * @return true if this NFC Adapter has any features enabled
      */
     public boolean isEnabled() {
+        boolean serviceState = false;
         try {
-            return sService.getState() == STATE_ON;
+            serviceState = sService.getState() == STATE_ON;
         } catch (RemoteException e) {
             attemptDeadServiceRecovery(e);
             // Try one more time
@@ -885,12 +920,12 @@
                 return false;
             }
             try {
-                return sService.getState() == STATE_ON;
+                serviceState = sService.getState() == STATE_ON;
             } catch (RemoteException ee) {
                 Log.e(TAG, "Failed to recover NFC Service.");
             }
-            return false;
         }
+        return serviceState && (isTagReadingEnabled() || isCardEmulationEnabled());
     }
 
     /**
diff --git a/core/java/android/nfc/TEST_MAPPING b/core/java/android/nfc/TEST_MAPPING
index 71ad687..5b5ea37 100644
--- a/core/java/android/nfc/TEST_MAPPING
+++ b/core/java/android/nfc/TEST_MAPPING
@@ -2,6 +2,9 @@
   "presubmit": [
     {
       "name": "NfcManagerTests"
+    },
+    {
+      "name": "CtsNfcTestCases"
     }
   ]
 }
diff --git a/core/java/android/nfc/cardemulation/AidGroup.java b/core/java/android/nfc/cardemulation/AidGroup.java
index 2436e57..958669e 100644
--- a/core/java/android/nfc/cardemulation/AidGroup.java
+++ b/core/java/android/nfc/cardemulation/AidGroup.java
@@ -16,7 +16,11 @@
 
 package android.nfc.cardemulation;
 
-import android.compat.annotation.UnsupportedAppUsage;
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.nfc.Flags;
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.Log;
@@ -29,6 +33,11 @@
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Locale;
+
+/**********************************************************************
+ * This file is not a part of the NFC mainline module                 *
+ * *******************************************************************/
 
 /**
  * The AidGroup class represents a group of Application Identifiers (AIDs).
@@ -39,28 +48,30 @@
  *
  * @hide
  */
+@SystemApi
+@FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
 public final class AidGroup implements Parcelable {
     /**
      * The maximum number of AIDs that can be present in any one group.
      */
-    public static final int MAX_NUM_AIDS = 256;
+    private static final int MAX_NUM_AIDS = 256;
 
-    static final String TAG = "AidGroup";
+    private static final String TAG = "AidGroup";
 
-    @UnsupportedAppUsage
-    final List<String> aids;
-    @UnsupportedAppUsage
-    final String category;
-    @UnsupportedAppUsage
-    final String description;
+
+    private final List<String> mAids;
+    private final String mCategory;
+    @SuppressWarnings("unused") // Unused as of now, but part of the XML input.
+    private final String mDescription;
 
     /**
      * Creates a new AidGroup object.
      *
-     * @param aids The list of AIDs present in the group
-     * @param category The category of this group, e.g. {@link CardEmulation#CATEGORY_PAYMENT}
+     * @param aids list of AIDs present in the group
+     * @param category category of this group, e.g. {@link CardEmulation#CATEGORY_PAYMENT}
      */
-    public AidGroup(List<String> aids, String category) {
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public AidGroup(@NonNull List<String> aids, @Nullable String category) {
         if (aids == null || aids.size() == 0) {
             throw new IllegalArgumentException("No AIDS in AID group.");
         }
@@ -73,45 +84,55 @@
             }
         }
         if (isValidCategory(category)) {
-            this.category = category;
+            this.mCategory = category;
         } else {
-            this.category = CardEmulation.CATEGORY_OTHER;
+            this.mCategory = CardEmulation.CATEGORY_OTHER;
         }
-        this.aids = new ArrayList<String>(aids.size());
+        this.mAids = new ArrayList<String>(aids.size());
         for (String aid : aids) {
-            this.aids.add(aid.toUpperCase());
+            this.mAids.add(aid.toUpperCase(Locale.US));
         }
-        this.description = null;
-    }
-
-    @UnsupportedAppUsage
-    AidGroup(String category, String description) {
-        this.aids = new ArrayList<String>();
-        this.category = category;
-        this.description = description;
+        this.mDescription = null;
     }
 
     /**
+     * Creates a new AidGroup object.
+     *
+     * @param category category of this group, e.g. {@link CardEmulation#CATEGORY_PAYMENT}
+     * @param description description of this group
+     */
+    AidGroup(@NonNull String category, @NonNull String description) {
+        this.mAids = new ArrayList<String>();
+        this.mCategory = category;
+        this.mDescription = description;
+    }
+
+    /**
+     * Returns the category of this group.
      * @return the category of this AID group
      */
-    @UnsupportedAppUsage
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public String getCategory() {
-        return category;
+        return mCategory;
     }
 
     /**
+     * Returns the list of AIDs in this group.
+     *
      * @return the list of AIDs in this group
      */
-    @UnsupportedAppUsage
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public List<String> getAids() {
-        return aids;
+        return mAids;
     }
 
     @Override
     public String toString() {
-        StringBuilder out = new StringBuilder("Category: " + category +
-                  ", AIDs:");
-        for (String aid : aids) {
+        StringBuilder out = new StringBuilder("Category: " + mCategory
+                + ", AIDs:");
+        for (String aid : mAids) {
             out.append(aid);
             out.append(", ");
         }
@@ -119,41 +140,44 @@
     }
 
     /**
-     * Dump debugging info as AidGroupProto
+     * Dump debugging info as AidGroupProto.
      *
      * If the output belongs to a sub message, the caller is responsible for wrapping this function
      * between {@link ProtoOutputStream#start(long)} and {@link ProtoOutputStream#end(long)}.
      *
      * @param proto the ProtoOutputStream to write to
      */
-    public void dump(ProtoOutputStream proto) {
-        proto.write(AidGroupProto.CATEGORY, category);
-        for (String aid : aids) {
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void dump(@NonNull ProtoOutputStream proto) {
+        proto.write(AidGroupProto.CATEGORY, mCategory);
+        for (String aid : mAids) {
             proto.write(AidGroupProto.AIDS, aid);
         }
     }
 
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     @Override
     public int describeContents() {
         return 0;
     }
 
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     @Override
-    public void writeToParcel(Parcel dest, int flags) {
-        dest.writeString(category);
-        dest.writeInt(aids.size());
-        if (aids.size() > 0) {
-            dest.writeStringList(aids);
+    public void writeToParcel(@NonNull Parcel dest, int flags) {
+        dest.writeString8(mCategory);
+        dest.writeInt(mAids.size());
+        if (mAids.size() > 0) {
+            dest.writeStringList(mAids);
         }
     }
 
-    @UnsupportedAppUsage
-    public static final @android.annotation.NonNull Parcelable.Creator<AidGroup> CREATOR =
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public static final @NonNull Parcelable.Creator<AidGroup> CREATOR =
             new Parcelable.Creator<AidGroup>() {
 
         @Override
         public AidGroup createFromParcel(Parcel source) {
-            String category = source.readString();
+            String category = source.readString8();
             int listSize = source.readInt();
             ArrayList<String> aidList = new ArrayList<String>();
             if (listSize > 0) {
@@ -168,8 +192,17 @@
         }
     };
 
-    @UnsupportedAppUsage
-    static public AidGroup createFromXml(XmlPullParser parser) throws XmlPullParserException, IOException {
+    /**
+     * Create an instance of AID group from XML file.
+     *
+     * @param parser input xml parser stream
+     * @throws XmlPullParserException If an error occurs parsing the element.
+     * @throws IOException If an error occurs reading the element.
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @Nullable
+    public static AidGroup createFromXml(@NonNull XmlPullParser parser)
+            throws XmlPullParserException, IOException {
         String category = null;
         ArrayList<String> aids = new ArrayList<String>();
         AidGroup group = null;
@@ -210,11 +243,16 @@
         return group;
     }
 
-    @UnsupportedAppUsage
-    public void writeAsXml(XmlSerializer out) throws IOException {
+    /**
+     * Serialize instance of AID group to XML file.
+     * @param out XML serializer stream
+     * @throws IOException If an error occurs reading the element.
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void writeAsXml(@NonNull XmlSerializer out) throws IOException {
         out.startTag(null, "aid-group");
-        out.attribute(null, "category", category);
-        for (String aid : aids) {
+        out.attribute(null, "category", mCategory);
+        for (String aid : mAids) {
             out.startTag(null, "aid");
             out.attribute(null, "value", aid);
             out.endTag(null, "aid");
@@ -222,7 +260,7 @@
         out.endTag(null, "aid-group");
     }
 
-    static boolean isValidCategory(String category) {
+    private static boolean isValidCategory(String category) {
         return CardEmulation.CATEGORY_PAYMENT.equals(category) ||
                 CardEmulation.CATEGORY_OTHER.equals(category);
     }
diff --git a/core/java/android/nfc/cardemulation/ApduServiceInfo.java b/core/java/android/nfc/cardemulation/ApduServiceInfo.java
index 793a70e..18ec914 100644
--- a/core/java/android/nfc/cardemulation/ApduServiceInfo.java
+++ b/core/java/android/nfc/cardemulation/ApduServiceInfo.java
@@ -14,10 +14,16 @@
  * limitations under the License.
  */
 
+/**********************************************************************
+ * This file is not a part of the NFC mainline module                 *
+ * *******************************************************************/
+
 package android.nfc.cardemulation;
 
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.compat.annotation.UnsupportedAppUsage;
+import android.annotation.SystemApi;
 import android.content.ComponentName;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
@@ -28,7 +34,9 @@
 import android.content.res.TypedArray;
 import android.content.res.XmlResourceParser;
 import android.graphics.drawable.Drawable;
+import android.nfc.Flags;
 import android.os.Parcel;
+import android.os.ParcelFileDescriptor;
 import android.os.Parcelable;
 import android.util.AttributeSet;
 import android.util.Log;
@@ -38,7 +46,6 @@
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 
-import java.io.FileDescriptor;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -47,82 +54,82 @@
 import java.util.Map;
 
 /**
+ * Class holding APDU service info.
+ *
  * @hide
  */
+@SystemApi
+@FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
 public final class ApduServiceInfo implements Parcelable {
-    static final String TAG = "ApduServiceInfo";
+    private static final String TAG = "ApduServiceInfo";
 
     /**
      * The service that implements this
      */
-    @UnsupportedAppUsage
-    final ResolveInfo mService;
+    private final ResolveInfo mService;
 
     /**
      * Description of the service
      */
-    final String mDescription;
+    private final String mDescription;
 
     /**
      * Whether this service represents AIDs running on the host CPU
      */
-    final boolean mOnHost;
+    private final boolean mOnHost;
 
     /**
      * Offhost reader name.
      * eg: SIM, eSE etc
      */
-    String mOffHostName;
+    private String mOffHostName;
 
     /**
      * Offhost reader name from manifest file.
-     * Used for unsetOffHostSecureElement()
+     * Used for resetOffHostSecureElement()
      */
-    final String mStaticOffHostName;
+    private final String mStaticOffHostName;
 
     /**
      * Mapping from category to static AID group
      */
-    @UnsupportedAppUsage
-    final HashMap<String, AidGroup> mStaticAidGroups;
+    private final HashMap<String, AidGroup> mStaticAidGroups;
 
     /**
      * Mapping from category to dynamic AID group
      */
-    @UnsupportedAppUsage
-    final HashMap<String, AidGroup> mDynamicAidGroups;
+    private final HashMap<String, AidGroup> mDynamicAidGroups;
 
     /**
      * Whether this service should only be started when the device is unlocked.
      */
-    final boolean mRequiresDeviceUnlock;
+    private final boolean mRequiresDeviceUnlock;
 
     /**
      * Whether this service should only be started when the device is screen on.
      */
-    final boolean mRequiresDeviceScreenOn;
+    private final boolean mRequiresDeviceScreenOn;
 
     /**
      * The id of the service banner specified in XML.
      */
-    final int mBannerResourceId;
+    private final int mBannerResourceId;
 
     /**
      * The uid of the package the service belongs to
      */
-    final int mUid;
+    private final int mUid;
 
     /**
      * Settings Activity for this service
      */
-    final String mSettingsActivityName;
+    private final String mSettingsActivityName;
 
     /**
      * @hide
      */
-    @UnsupportedAppUsage
     public ApduServiceInfo(ResolveInfo info, boolean onHost, String description,
-            ArrayList<AidGroup> staticAidGroups, ArrayList<AidGroup> dynamicAidGroups,
+            List<AidGroup> staticAidGroups, List<AidGroup> dynamicAidGroups,
             boolean requiresUnlock, int bannerResource, int uid,
             String settingsActivityName, String offHost, String staticOffHost) {
         this(info, onHost, description, staticAidGroups, dynamicAidGroups,
@@ -134,7 +141,7 @@
      * @hide
      */
     public ApduServiceInfo(ResolveInfo info, boolean onHost, String description,
-            ArrayList<AidGroup> staticAidGroups, ArrayList<AidGroup> dynamicAidGroups,
+            List<AidGroup> staticAidGroups, List<AidGroup> dynamicAidGroups,
             boolean requiresUnlock, boolean requiresScreenOn, int bannerResource, int uid,
             String settingsActivityName, String offHost, String staticOffHost) {
         this.mService = info;
@@ -147,19 +154,28 @@
         this.mRequiresDeviceUnlock = requiresUnlock;
         this.mRequiresDeviceScreenOn = requiresScreenOn;
         for (AidGroup aidGroup : staticAidGroups) {
-            this.mStaticAidGroups.put(aidGroup.category, aidGroup);
+            this.mStaticAidGroups.put(aidGroup.getCategory(), aidGroup);
         }
         for (AidGroup aidGroup : dynamicAidGroups) {
-            this.mDynamicAidGroups.put(aidGroup.category, aidGroup);
+            this.mDynamicAidGroups.put(aidGroup.getCategory(), aidGroup);
         }
         this.mBannerResourceId = bannerResource;
         this.mUid = uid;
         this.mSettingsActivityName = settingsActivityName;
     }
 
-    @UnsupportedAppUsage
-    public ApduServiceInfo(PackageManager pm, ResolveInfo info, boolean onHost) throws
-            XmlPullParserException, IOException {
+    /**
+     * Creates a new ApduServiceInfo object.
+     *
+     * @param pm packageManager instance
+     * @param info app component info
+     * @param onHost whether service is on host or not (secure element)
+     * @throws XmlPullParserException If an error occurs parsing the element.
+     * @throws IOException If an error occurs reading the element.
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public ApduServiceInfo(@NonNull PackageManager pm, @NonNull ResolveInfo info, boolean onHost)
+            throws XmlPullParserException, IOException {
         ServiceInfo si = info.serviceInfo;
         XmlResourceParser parser = null;
         try {
@@ -277,9 +293,9 @@
                     groupAttrs.recycle();
                 } else if (eventType == XmlPullParser.END_TAG && "aid-group".equals(tagName) &&
                         currentGroup != null) {
-                    if (currentGroup.aids.size() > 0) {
-                        if (!mStaticAidGroups.containsKey(currentGroup.category)) {
-                            mStaticAidGroups.put(currentGroup.category, currentGroup);
+                    if (currentGroup.getAids().size() > 0) {
+                        if (!mStaticAidGroups.containsKey(currentGroup.getCategory())) {
+                            mStaticAidGroups.put(currentGroup.getCategory(), currentGroup);
                         }
                     } else {
                         Log.e(TAG, "Not adding <aid-group> with empty or invalid AIDs");
@@ -291,8 +307,8 @@
                             com.android.internal.R.styleable.AidFilter);
                     String aid = a.getString(com.android.internal.R.styleable.AidFilter_name).
                             toUpperCase();
-                    if (CardEmulation.isValidAid(aid) && !currentGroup.aids.contains(aid)) {
-                        currentGroup.aids.add(aid);
+                    if (CardEmulation.isValidAid(aid) && !currentGroup.getAids().contains(aid)) {
+                        currentGroup.getAids().add(aid);
                     } else {
                         Log.e(TAG, "Ignoring invalid or duplicate aid: " + aid);
                     }
@@ -305,8 +321,8 @@
                             toUpperCase();
                     // Add wildcard char to indicate prefix
                     aid = aid.concat("*");
-                    if (CardEmulation.isValidAid(aid) && !currentGroup.aids.contains(aid)) {
-                        currentGroup.aids.add(aid);
+                    if (CardEmulation.isValidAid(aid) && !currentGroup.getAids().contains(aid)) {
+                        currentGroup.getAids().add(aid);
                     } else {
                         Log.e(TAG, "Ignoring invalid or duplicate aid: " + aid);
                     }
@@ -319,8 +335,8 @@
                             toUpperCase();
                     // Add wildcard char to indicate suffix
                     aid = aid.concat("#");
-                    if (CardEmulation.isValidAid(aid) && !currentGroup.aids.contains(aid)) {
-                        currentGroup.aids.add(aid);
+                    if (CardEmulation.isValidAid(aid) && !currentGroup.getAids().contains(aid)) {
+                        currentGroup.getAids().add(aid);
                     } else {
                         Log.e(TAG, "Ignoring invalid or duplicate aid: " + aid);
                     }
@@ -336,11 +352,25 @@
         mUid = si.applicationInfo.uid;
     }
 
+    /**
+     * Returns the app component corresponding to this APDU service.
+     *
+     * @return app component for this service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public ComponentName getComponent() {
         return new ComponentName(mService.serviceInfo.packageName,
                 mService.serviceInfo.name);
     }
 
+    /**
+     * Returns the offhost secure element name (if the service is offhost).
+     *
+     * @return offhost secure element name for offhost services
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @Nullable
     public String getOffHostSecureElement() {
         return mOffHostName;
     }
@@ -353,18 +383,30 @@
      * for that category.
      * @return List of AIDs registered by the service
      */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public List<String> getAids() {
         final ArrayList<String> aids = new ArrayList<String>();
         for (AidGroup group : getAidGroups()) {
-            aids.addAll(group.aids);
+            aids.addAll(group.getAids());
         }
         return aids;
     }
 
+    /**
+     * Returns a consolidated list of AIDs with prefixes from the AID groups
+     * registered by this service. Note that if a service has both
+     * a static (manifest-based) AID group for a category and a dynamic
+     * AID group, only the dynamically registered AIDs will be returned
+     * for that category.
+     * @return List of prefix AIDs registered by the service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public List<String> getPrefixAids() {
         final ArrayList<String> prefixAids = new ArrayList<String>();
         for (AidGroup group : getAidGroups()) {
-            for (String aid : group.aids) {
+            for (String aid : group.getAids()) {
                 if (aid.endsWith("*")) {
                     prefixAids.add(aid);
                 }
@@ -373,10 +415,20 @@
         return prefixAids;
     }
 
+    /**
+     * Returns a consolidated list of AIDs with subsets from the AID groups
+     * registered by this service. Note that if a service has both
+     * a static (manifest-based) AID group for a category and a dynamic
+     * AID group, only the dynamically registered AIDs will be returned
+     * for that category.
+     * @return List of prefix AIDs registered by the service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public List<String> getSubsetAids() {
         final ArrayList<String> subsetAids = new ArrayList<String>();
         for (AidGroup group : getAidGroups()) {
-            for (String aid : group.aids) {
+            for (String aid : group.getAids()) {
                 if (aid.endsWith("#")) {
                     subsetAids.add(aid);
                 }
@@ -384,14 +436,28 @@
         }
         return subsetAids;
     }
+
     /**
      * Returns the registered AID group for this category.
+     *
+     * @param category category name
+     * @return {@link AidGroup} instance for the provided category
      */
-    public AidGroup getDynamicAidGroupForCategory(String category) {
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public AidGroup getDynamicAidGroupForCategory(@NonNull String category) {
         return mDynamicAidGroups.get(category);
     }
 
-    public boolean removeDynamicAidGroupForCategory(String category) {
+    /**
+     * Removes the registered AID group for this category.
+     *
+     * @param category category name
+     * @return {@code true} if an AID group existed
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public boolean removeDynamicAidGroupForCategory(@NonNull String category) {
         return (mDynamicAidGroups.remove(category) != null);
     }
 
@@ -403,7 +469,9 @@
      * for that category.
      * @return List of AIDs registered by the service
      */
-    public ArrayList<AidGroup> getAidGroups() {
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public List<AidGroup> getAidGroups() {
         final ArrayList<AidGroup> groups = new ArrayList<AidGroup>();
         for (Map.Entry<String, AidGroup> entry : mDynamicAidGroups.entrySet()) {
             groups.add(entry.getValue());
@@ -421,49 +489,83 @@
     /**
      * Returns the category to which this service has attributed the AID that is passed in,
      * or null if we don't know this AID.
+     * @param aid AID to lookup for
+     * @return category name corresponding to this AID
      */
-    public String getCategoryForAid(String aid) {
-        ArrayList<AidGroup> groups = getAidGroups();
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public String getCategoryForAid(@NonNull String aid) {
+        List<AidGroup> groups = getAidGroups();
         for (AidGroup group : groups) {
-            if (group.aids.contains(aid.toUpperCase())) {
-                return group.category;
+            if (group.getAids().contains(aid.toUpperCase())) {
+                return group.getCategory();
             }
         }
         return null;
     }
 
-    public boolean hasCategory(String category) {
+    /**
+     * Returns whether there is any AID group for this category.
+     * @param category category name
+     * @return {@code true} if an AID group exists
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public boolean hasCategory(@NonNull String category) {
         return (mStaticAidGroups.containsKey(category) || mDynamicAidGroups.containsKey(category));
     }
 
-    @UnsupportedAppUsage
+    /**
+     * Returns whether the service is on host or not.
+     * @return true if the service is on host (not secure element)
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     public boolean isOnHost() {
         return mOnHost;
     }
 
-    @UnsupportedAppUsage
+    /**
+     * Returns whether the service requires device unlock.
+     * @return whether the service requires device unlock
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     public boolean requiresUnlock() {
         return mRequiresDeviceUnlock;
     }
 
     /**
      * Returns whether this service should only be started when the device is screen on.
+     * @return whether the service requires screen on
      */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     public boolean requiresScreenOn() {
         return mRequiresDeviceScreenOn;
     }
 
-    @UnsupportedAppUsage
+    /**
+     * Returns description of service.
+     * @return user readable description of service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public String getDescription() {
         return mDescription;
     }
 
-    @UnsupportedAppUsage
+    /**
+     * Returns uid of service.
+     * @return uid of the service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     public int getUid() {
         return mUid;
     }
 
-    public void setOrReplaceDynamicAidGroup(AidGroup aidGroup) {
+    /**
+     * Add or replace an AID group to this service.
+     * @param aidGroup instance of aid group to set or replace
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void setDynamicAidGroup(@NonNull AidGroup aidGroup) {
         mDynamicAidGroups.put(aidGroup.getCategory(), aidGroup);
     }
 
@@ -476,7 +578,8 @@
      *                  TS26_NFC_REQ_070: For embedded SE, Secure Element Name SHALL be eSE[number]
      *                                    (e.g. eSE/eSE1, eSE2, etc.).
      */
-    public void setOffHostSecureElement(String offHost) {
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void setOffHostSecureElement(@NonNull String offHost) {
         mOffHostName = offHost;
     }
 
@@ -484,15 +587,30 @@
      * Resets the off host Secure Element to statically defined
      * by the service in the manifest file.
      */
-    public void unsetOffHostSecureElement() {
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void resetOffHostSecureElement() {
         mOffHostName = mStaticOffHostName;
     }
 
-    public CharSequence loadLabel(PackageManager pm) {
+    /**
+     * Load label for this service.
+     * @param pm packagemanager instance
+     * @return label name corresponding to service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public CharSequence loadLabel(@NonNull PackageManager pm) {
         return mService.loadLabel(pm);
     }
 
-    public CharSequence loadAppLabel(PackageManager pm) {
+    /**
+     * Load application label for this service.
+     * @param pm packagemanager instance
+     * @return app label name corresponding to service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public CharSequence loadAppLabel(@NonNull PackageManager pm) {
         try {
             return pm.getApplicationLabel(pm.getApplicationInfo(
                     mService.resolvePackageName, PackageManager.GET_META_DATA));
@@ -501,12 +619,25 @@
         }
     }
 
-    public Drawable loadIcon(PackageManager pm) {
+    /**
+     * Load application icon for this service.
+     * @param pm packagemanager instance
+     * @return app icon corresponding to service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public Drawable loadIcon(@NonNull PackageManager pm) {
         return mService.loadIcon(pm);
     }
 
-    @UnsupportedAppUsage
-    public Drawable loadBanner(PackageManager pm) {
+    /**
+     * Load application banner for this service.
+     * @param pm packagemanager instance
+     * @return app banner corresponding to service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public Drawable loadBanner(@NonNull PackageManager pm) {
         Resources res;
         try {
             res = pm.getResourcesForApplication(mService.serviceInfo.packageName);
@@ -521,7 +652,12 @@
         }
     }
 
-    @UnsupportedAppUsage
+    /**
+     * Load activity name for this service.
+     * @return activity name for this service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public String getSettingsActivityName() { return mSettingsActivityName; }
 
     @Override
@@ -556,14 +692,15 @@
         return getComponent().hashCode();
     }
 
-
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     @Override
     public int describeContents() {
         return 0;
     }
 
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     @Override
-    public void writeToParcel(Parcel dest, int flags) {
+    public void writeToParcel(@NonNull Parcel dest, int flags) {
         mService.writeToParcel(dest, flags);
         dest.writeString(mDescription);
         dest.writeInt(mOnHost ? 1 : 0);
@@ -584,8 +721,8 @@
         dest.writeString(mSettingsActivityName);
     };
 
-    @UnsupportedAppUsage
-    public static final @android.annotation.NonNull Parcelable.Creator<ApduServiceInfo> CREATOR =
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public static final @NonNull Parcelable.Creator<ApduServiceInfo> CREATOR =
             new Parcelable.Creator<ApduServiceInfo>() {
         @Override
         public ApduServiceInfo createFromParcel(Parcel source) {
@@ -620,7 +757,15 @@
         }
     };
 
-    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+    /**
+     * Dump contents for debugging.
+     * @param fd parcelfiledescriptor instance
+     * @param pw printwriter instance
+     * @param args args for dumping
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void dump(@NonNull ParcelFileDescriptor fd, @NonNull PrintWriter pw,
+                     @NonNull String[] args) {
         pw.println("    " + getComponent()
                 + " (Description: " + getDescription() + ")"
                 + " (UID: " + getUid() + ")");
@@ -633,15 +778,15 @@
         }
         pw.println("    Static AID groups:");
         for (AidGroup group : mStaticAidGroups.values()) {
-            pw.println("        Category: " + group.category);
-            for (String aid : group.aids) {
+            pw.println("        Category: " + group.getCategory());
+            for (String aid : group.getAids()) {
                 pw.println("            AID: " + aid);
             }
         }
         pw.println("    Dynamic AID groups:");
         for (AidGroup group : mDynamicAidGroups.values()) {
-            pw.println("        Category: " + group.category);
-            for (String aid : group.aids) {
+            pw.println("        Category: " + group.getCategory());
+            for (String aid : group.getAids()) {
                 pw.println("            AID: " + aid);
             }
         }
@@ -651,7 +796,7 @@
     }
 
     /**
-     * Dump debugging info as ApduServiceInfoProto
+     * Dump debugging info as ApduServiceInfoProto.
      *
      * If the output belongs to a sub message, the caller is responsible for wrapping this function
      * between {@link ProtoOutputStream#start(long)} and {@link ProtoOutputStream#end(long)}.
@@ -659,7 +804,8 @@
      *
      * @param proto the ProtoOutputStream to write to
      */
-    public void dumpDebug(ProtoOutputStream proto) {
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void dumpDebug(@NonNull ProtoOutputStream proto) {
         Utils.dumpDebugComponentName(getComponent(), proto, ApduServiceInfoProto.COMPONENT_NAME);
         proto.write(ApduServiceInfoProto.DESCRIPTION, getDescription());
         proto.write(ApduServiceInfoProto.ON_HOST, mOnHost);
diff --git a/core/java/android/nfc/cardemulation/CardEmulation.java b/core/java/android/nfc/cardemulation/CardEmulation.java
index ac3344e..4909b08 100644
--- a/core/java/android/nfc/cardemulation/CardEmulation.java
+++ b/core/java/android/nfc/cardemulation/CardEmulation.java
@@ -594,9 +594,6 @@
         if (activity == null || service == null) {
             throw new NullPointerException("activity or service or category is null");
         }
-        if (!activity.isResumed()) {
-            throw new IllegalArgumentException("Activity must be resumed.");
-        }
         try {
             return sService.setPreferredService(service);
         } catch (RemoteException e) {
@@ -629,9 +626,6 @@
         if (activity == null) {
             throw new NullPointerException("activity is null");
         }
-        if (!activity.isResumed()) {
-            throw new IllegalArgumentException("Activity must be resumed.");
-        }
         try {
             return sService.unsetPreferredService();
         } catch (RemoteException e) {
diff --git a/core/java/android/nfc/cardemulation/NfcFServiceInfo.java b/core/java/android/nfc/cardemulation/NfcFServiceInfo.java
index 7a36b26..ec919e4 100644
--- a/core/java/android/nfc/cardemulation/NfcFServiceInfo.java
+++ b/core/java/android/nfc/cardemulation/NfcFServiceInfo.java
@@ -14,9 +14,16 @@
  * limitations under the License.
  */
 
+/**********************************************************************
+ * This file is not a part of the NFC mainline module                 *
+ * *******************************************************************/
+
 package android.nfc.cardemulation;
 
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.SystemApi;
 import android.content.ComponentName;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
@@ -26,7 +33,9 @@
 import android.content.res.TypedArray;
 import android.content.res.XmlResourceParser;
 import android.graphics.drawable.Drawable;
+import android.nfc.Flags;
 import android.os.Parcel;
+import android.os.ParcelFileDescriptor;
 import android.os.Parcelable;
 import android.util.AttributeSet;
 import android.util.Log;
@@ -36,13 +45,16 @@
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 
-import java.io.FileDescriptor;
 import java.io.IOException;
 import java.io.PrintWriter;
 
 /**
+ * Class to hold NfcF service info.
+ *
  * @hide
  */
+@SystemApi
+@FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
 public final class NfcFServiceInfo implements Parcelable {
     static final String TAG = "NfcFServiceInfo";
 
@@ -51,42 +63,42 @@
     /**
      * The service that implements this
      */
-    final ResolveInfo mService;
+    private final ResolveInfo mService;
 
     /**
      * Description of the service
      */
-    final String mDescription;
+    private final String mDescription;
 
     /**
      * System Code of the service
      */
-    final String mSystemCode;
+    private final String mSystemCode;
 
     /**
      * System Code of the service registered by API
      */
-    String mDynamicSystemCode;
+    private String mDynamicSystemCode;
 
     /**
      * NFCID2 of the service
      */
-    final String mNfcid2;
+    private final String mNfcid2;
 
     /**
      * NFCID2 of the service registered by API
      */
-    String mDynamicNfcid2;
+    private String mDynamicNfcid2;
 
     /**
      * The uid of the package the service belongs to
      */
-    final int mUid;
+    private final int mUid;
 
     /**
      * LF_T3T_PMM of the service
      */
-    final String mT3tPmm;
+    private final String mT3tPmm;
 
     /**
      * @hide
@@ -104,7 +116,16 @@
         this.mT3tPmm = t3tPmm;
     }
 
-    public NfcFServiceInfo(PackageManager pm, ResolveInfo info)
+    /**
+     * Creates a new NfcFServiceInfo object.
+     *
+     * @param pm packageManager instance
+     * @param info app component info
+     * @throws XmlPullParserException If an error occurs parsing the element.
+     * @throws IOException If an error occurs reading the element.
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public NfcFServiceInfo(@NonNull PackageManager pm, @NonNull ResolveInfo info)
             throws XmlPullParserException, IOException {
         ServiceInfo si = info.serviceInfo;
         XmlResourceParser parser = null;
@@ -192,44 +213,107 @@
         mUid = si.applicationInfo.uid;
     }
 
+    /**
+     * Returns the app component corresponding to this NFCF service.
+     *
+     * @return app component for this service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public ComponentName getComponent() {
         return new ComponentName(mService.serviceInfo.packageName,
                 mService.serviceInfo.name);
     }
 
+    /**
+     * Returns the system code corresponding to this service.
+     *
+     * @return system code for this service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public String getSystemCode() {
         return (mDynamicSystemCode == null ? mSystemCode : mDynamicSystemCode);
     }
 
-    public void setOrReplaceDynamicSystemCode(String systemCode) {
+    /**
+     * Add or replace a system code to this service.
+     * @param systemCode system code to set or replace
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void setDynamicSystemCode(@NonNull String systemCode) {
         mDynamicSystemCode = systemCode;
     }
 
+    /**
+     * Returns NFC ID2.
+     *
+     * @return nfc id2 to return
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public String getNfcid2() {
         return (mDynamicNfcid2 == null ? mNfcid2 : mDynamicNfcid2);
     }
 
-    public void setOrReplaceDynamicNfcid2(String nfcid2) {
+    /**
+     * Set or replace NFC ID2
+     *
+     * @param nfcid2 NFC ID2 string
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void setDynamicNfcid2(@NonNull String nfcid2) {
         mDynamicNfcid2 = nfcid2;
     }
 
+    /**
+     * Returns description of service.
+     * @return user readable description of service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public String getDescription() {
         return mDescription;
     }
 
+    /**
+     * Returns uid of service.
+     * @return uid of the service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     public int getUid() {
         return mUid;
     }
 
+    /**
+     * Returns LF_T3T_PMM of the service
+     * @return returns LF_T3T_PMM of the service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
     public String getT3tPmm() {
         return mT3tPmm;
     }
 
-    public CharSequence loadLabel(PackageManager pm) {
+    /**
+     * Load application label for this service.
+     * @param pm packagemanager instance
+     * @return label name corresponding to service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public CharSequence loadLabel(@NonNull PackageManager pm) {
         return mService.loadLabel(pm);
     }
 
-    public Drawable loadIcon(PackageManager pm) {
+    /**
+     * Load application icon for this service.
+     * @param pm packagemanager instance
+     * @return app icon corresponding to service
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    @NonNull
+    public Drawable loadIcon(@NonNull PackageManager pm) {
         return mService.loadIcon(pm);
     }
 
@@ -270,13 +354,15 @@
         return getComponent().hashCode();
     }
 
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     @Override
     public int describeContents() {
         return 0;
     }
 
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
     @Override
-    public void writeToParcel(Parcel dest, int flags) {
+    public void writeToParcel(@NonNull Parcel dest, int flags) {
         mService.writeToParcel(dest, flags);
         dest.writeString(mDescription);
         dest.writeString(mSystemCode);
@@ -293,7 +379,8 @@
         dest.writeString(mT3tPmm);
     };
 
-    public static final @android.annotation.NonNull Parcelable.Creator<NfcFServiceInfo> CREATOR =
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public static final @NonNull Parcelable.Creator<NfcFServiceInfo> CREATOR =
             new Parcelable.Creator<NfcFServiceInfo>() {
         @Override
         public NfcFServiceInfo createFromParcel(Parcel source) {
@@ -322,7 +409,15 @@
         }
     };
 
-    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+    /**
+     * Dump contents of the service for debugging.
+     * @param fd parcelfiledescriptor instance
+     * @param pw printwriter instance
+     * @param args args for dumping
+     */
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void dump(@NonNull ParcelFileDescriptor fd, @NonNull PrintWriter pw,
+                     @NonNull String[] args) {
         pw.println("    " + getComponent()
                 + " (Description: " + getDescription() + ")"
                 + " (UID: " + getUid() + ")");
@@ -332,14 +427,15 @@
     }
 
     /**
-     * Dump debugging info as NfcFServiceInfoProto
+     * Dump debugging info as NfcFServiceInfoProto.
      *
      * If the output belongs to a sub message, the caller is responsible for wrapping this function
      * between {@link ProtoOutputStream#start(long)} and {@link ProtoOutputStream#end(long)}.
      *
      * @param proto the ProtoOutputStream to write to
      */
-    public void dumpDebug(ProtoOutputStream proto) {
+    @FlaggedApi(Flags.FLAG_ENABLE_NFC_MAINLINE)
+    public void dumpDebug(@NonNull ProtoOutputStream proto) {
         Utils.dumpDebugComponentName(getComponent(), proto, NfcFServiceInfoProto.COMPONENT_NAME);
         proto.write(NfcFServiceInfoProto.DESCRIPTION, getDescription());
         proto.write(NfcFServiceInfoProto.SYSTEM_CODE, getSystemCode());
@@ -347,4 +443,3 @@
         proto.write(NfcFServiceInfoProto.T3T_PMM, getT3tPmm());
     }
 }
-
diff --git a/core/java/android/nfc/flags.aconfig b/core/java/android/nfc/flags.aconfig
new file mode 100644
index 0000000..e3faf39
--- /dev/null
+++ b/core/java/android/nfc/flags.aconfig
@@ -0,0 +1,8 @@
+package: "android.nfc"
+
+flag {
+    name: "enable_nfc_mainline"
+    namespace: "nfc"
+    description: "Flag for NFC mainline changes"
+    bug: "292140387"
+}
diff --git a/core/java/android/os/Binder.java b/core/java/android/os/Binder.java
index 5d0a723..8e60102 100644
--- a/core/java/android/os/Binder.java
+++ b/core/java/android/os/Binder.java
@@ -186,6 +186,8 @@
     /**
      * Get the binder transaction observer for this process.
      *
+     * TODO(b/299356196): only applies to Java code, not C++/Rust
+     *
      * @hide
      */
     public static void setObserver(@Nullable BinderInternal.Observer observer) {
@@ -202,6 +204,8 @@
      * that require a result must be sent as {@link IBinder#FLAG_ONEWAY} calls
      * which deliver results through a callback interface.
      *
+     * TODO(b/299355525): only applies to Java code, not C++/Rust
+     *
      * @hide
      */
     public static void setWarnOnBlocking(boolean warnOnBlocking) {
@@ -218,6 +222,8 @@
      * interfaces hosted by package that could be upgraded or replaced,
      * otherwise you risk system instability if that remote interface wedges.
      *
+     * TODO(b/299355525): only applies to Java code, not C++/Rust
+     *
      * @hide
      */
     public static IBinder allowBlocking(IBinder binder) {
@@ -943,16 +949,19 @@
      * @hide
      */
     @VisibleForTesting
-    public final @NonNull String getTransactionTraceName(int transactionCode) {
+    public final @Nullable String getTransactionTraceName(int transactionCode) {
+        final boolean isInterfaceUserDefined = getMaxTransactionId() == 0;
         if (mTransactionTraceNames == null) {
-            final int highestId = Math.min(getMaxTransactionId(), TRANSACTION_TRACE_NAME_ID_LIMIT);
+            final int highestId = isInterfaceUserDefined ? TRANSACTION_TRACE_NAME_ID_LIMIT
+                    : Math.min(getMaxTransactionId(), TRANSACTION_TRACE_NAME_ID_LIMIT);
             mSimpleDescriptor = getSimpleDescriptor();
             mTransactionTraceNames = new AtomicReferenceArray(highestId + 1);
         }
 
-        final int index = transactionCode - FIRST_CALL_TRANSACTION;
-        if (index < 0 || index >= mTransactionTraceNames.length()) {
-            return mSimpleDescriptor + "#" + transactionCode;
+        final int index = isInterfaceUserDefined
+                ? transactionCode : transactionCode - FIRST_CALL_TRANSACTION;
+        if (index >= mTransactionTraceNames.length() || index < 0) {
+            return null;
         }
 
         String transactionTraceName = mTransactionTraceNames.getAcquire(index);
@@ -1304,6 +1313,8 @@
             int callingUid) {
         // Make sure the observer won't change while processing a transaction.
         final BinderInternal.Observer observer = sObserver;
+
+        // TODO(b/299356196): observer should also observe transactions in native code
         final CallSession callSession =
                 observer != null ? observer.callStarted(this, code, UNSET_WORKSOURCE) : null;
         // Theoretically, we should call transact, which will call onTransact,
@@ -1317,26 +1328,16 @@
         final boolean hasFullyQualifiedName = getMaxTransactionId() > 0;
         final String transactionTraceName;
 
-        if (tagEnabled && hasFullyQualifiedName) {
+        if (tagEnabled) {
             // If tracing enabled and we have a fully qualified name, fetch the name
             transactionTraceName = getTransactionTraceName(code);
-        } else if (tagEnabled && isStackTrackingEnabled()) {
-            // If tracing is enabled and we *don't* have a fully qualified name, fetch the
-            // 'best effort' name only for stack tracking. This works around noticeable perf impact
-            // on low latency binder calls (<100us). The tracing call itself is between (1-10us) and
-            // the perf impact can be quite noticeable while benchmarking such binder calls.
-            // The primary culprits are ContentProviders and Cursors which convenienty don't
-            // autogenerate their AIDL and hence will not have a fully qualified name.
-            //
-            // TODO(b/253426478): Relax this constraint after a more robust fix
-            transactionTraceName = getTransactionTraceName(code);
         } else {
             transactionTraceName = null;
         }
 
         final boolean tracingEnabled = tagEnabled && transactionTraceName != null;
         try {
-            // TODO - this logic should not be in Java - it should be in native
+            // TODO(b/299356201) - this logic should not be in Java - it should be in native
             // code in libbinder so that it works for all binder users.
             final BinderCallHeavyHitterWatcher heavyHitterWatcher = sHeavyHitterWatcher;
             if (heavyHitterWatcher != null && callingUid != -1) {
@@ -1347,9 +1348,9 @@
                 Trace.traceBegin(Trace.TRACE_TAG_AIDL, transactionTraceName);
             }
 
-            // TODO - this logic should not be in Java - it should be in native
-            // code in libbinder so that it works for all binder users. Further,
-            // this should not re-use flags.
+            // TODO(b/299353919) - this logic should not be in Java - it should be
+            // in native code in libbinder so that it works for all binder users.
+            // Further, this should not re-use flags.
             if ((flags & FLAG_COLLECT_NOTED_APP_OPS) != 0 && callingUid != -1) {
                 AppOpsManager.startNotedAppOpsCollection(callingUid);
                 try {
diff --git a/core/java/android/os/BinderProxy.java b/core/java/android/os/BinderProxy.java
index 1929a4d..5196b17 100644
--- a/core/java/android/os/BinderProxy.java
+++ b/core/java/android/os/BinderProxy.java
@@ -32,7 +32,9 @@
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
@@ -613,15 +615,35 @@
      */
     public native boolean transactNative(int code, Parcel data, Parcel reply,
             int flags) throws RemoteException;
+
+    /* This list is to hold strong reference to the death recipients that are waiting for the death
+     * of binder that this proxy references. Previously, the death recipients were strongy
+     * referenced from JNI, but that can cause memory leak (b/298374304) when the application has a
+     * strong reference from the death recipient to the proxy object. The JNI reference is now weak.
+     * And this strong reference is to keep death recipients at least until the proxy is GC'ed. */
+    private List<DeathRecipient> mDeathRecipients = Collections.synchronizedList(new ArrayList<>());
+
     /**
      * See {@link IBinder#linkToDeath(DeathRecipient, int)}
      */
-    public native void linkToDeath(DeathRecipient recipient, int flags)
-            throws RemoteException;
+    public void linkToDeath(DeathRecipient recipient, int flags)
+            throws RemoteException {
+        linkToDeathNative(recipient, flags);
+        mDeathRecipients.add(recipient);
+    }
+
     /**
      * See {@link IBinder#unlinkToDeath}
      */
-    public native boolean unlinkToDeath(DeathRecipient recipient, int flags);
+    public boolean unlinkToDeath(DeathRecipient recipient, int flags) {
+        mDeathRecipients.remove(recipient);
+        return unlinkToDeathNative(recipient, flags);
+    }
+
+    private native void linkToDeathNative(DeathRecipient recipient, int flags)
+            throws RemoteException;
+
+    private native boolean unlinkToDeathNative(DeathRecipient recipient, int flags);
 
     /**
      * Perform a dump on the remote object
diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java
index 2e05b8d..9dc4a97 100755
--- a/core/java/android/os/Build.java
+++ b/core/java/android/os/Build.java
@@ -1560,7 +1560,7 @@
         String attestProp = getString(
                 TextUtils.formatSimple("ro.product.%s_for_attestation", property));
         return attestProp.equals(UNKNOWN)
-                ? getString(TextUtils.formatSimple("ro.product.vendor.%s", property)) : UNKNOWN;
+                ? getString(TextUtils.formatSimple("ro.product.vendor.%s", property)) : attestProp;
     }
 
     private static String[] getStringList(String property, String separator) {
diff --git a/core/java/android/os/DropBoxManager.java b/core/java/android/os/DropBoxManager.java
index 403f55c..cf35460 100644
--- a/core/java/android/os/DropBoxManager.java
+++ b/core/java/android/os/DropBoxManager.java
@@ -364,7 +364,7 @@
     }
 
     /**
-     * Checks any blacklists (set in system settings) to see whether a certain
+     * Checks any denylists (set in system settings) to see whether a certain
      * tag is allowed.  Entries with disabled tags will be dropped immediately,
      * so you can save the work of actually constructing and sending the data.
      *
diff --git a/core/java/android/os/Handler.java b/core/java/android/os/Handler.java
index 834867c..d6a0690 100644
--- a/core/java/android/os/Handler.java
+++ b/core/java/android/os/Handler.java
@@ -119,7 +119,7 @@
      *   crashes (if a handler is sometimes created on a thread without a Looper active), or race
      *   conditions, where the thread a handler is associated with is not what the author
      *   anticipated. Instead, use an {@link java.util.concurrent.Executor} or specify the Looper
-     *   explicitly, using {@link Looper#getMainLooper}, {link android.view.View#getHandler}, or
+     *   explicitly, using {@link Looper#getMainLooper}, {@link android.view.View#getHandler}, or
      *   similar. If the implicit thread local behavior is required for compatibility, use
      *   {@code new Handler(Looper.myLooper())} to make it clear to readers.
      *
@@ -144,7 +144,7 @@
      *   crashes (if a handler is sometimes created on a thread without a Looper active), or race
      *   conditions, where the thread a handler is associated with is not what the author
      *   anticipated. Instead, use an {@link java.util.concurrent.Executor} or specify the Looper
-     *   explicitly, using {@link Looper#getMainLooper}, {link android.view.View#getHandler}, or
+     *   explicitly, using {@link Looper#getMainLooper}, {@link android.view.View#getHandler}, or
      *   similar. If the implicit thread local behavior is required for compatibility, use
      *   {@code new Handler(Looper.myLooper(), callback)} to make it clear to readers.
      */
@@ -182,7 +182,7 @@
      *
      * Asynchronous messages represent interrupts or events that do not require global ordering
      * with respect to synchronous messages.  Asynchronous messages are not subject to
-     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
+     * the synchronization barriers introduced by {@link MessageQueue#postSyncBarrier()}.
      *
      * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
      * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
@@ -203,7 +203,7 @@
      *
      * Asynchronous messages represent interrupts or events that do not require global ordering
      * with respect to synchronous messages.  Asynchronous messages are not subject to
-     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
+     * the synchronization barriers introduced by {@link MessageQueue#postSyncBarrier()}.
      *
      * @param callback The callback interface in which to handle messages, or null.
      * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
@@ -743,7 +743,7 @@
         MessageQueue queue = mQueue;
         if (queue == null) {
             RuntimeException e = new RuntimeException(
-                this + " sendMessageAtTime() called with no mQueue");
+                    this + " sendMessageAtFrontOfQueue() called with no mQueue");
             Log.w("Looper", e.getMessage(), e);
             return false;
         }
diff --git a/core/java/android/os/INetworkManagementService.aidl b/core/java/android/os/INetworkManagementService.aidl
index ec69e2a..6e6ab7b 100644
--- a/core/java/android/os/INetworkManagementService.aidl
+++ b/core/java/android/os/INetworkManagementService.aidl
@@ -125,50 +125,65 @@
     /**
      * Returns true if IP forwarding is enabled
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "Use {@code android.net.INetd#ipfwdEnabled}")
     boolean getIpForwardingEnabled();
 
     /**
      * Enables/Disables IP Forwarding
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "Avoid using this directly. Instead, enable tethering with "
+            + "{@code android.net.TetheringManager#startTethering}. See also "
+            + "{@code INetd#ipfwdEnableForwarding(String)}.")
     void setIpForwardingEnabled(boolean enabled);
 
     /**
      * Start tethering services with the specified dhcp server range
      * arg is a set of start end pairs defining the ranges.
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "{@code android.net.TetheringManager#startTethering}")
     void startTethering(in String[] dhcpRanges);
 
     /**
      * Stop currently running tethering services
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "{@code android.net.TetheringManager#stopTethering(int)}")
     void stopTethering();
 
     /**
      * Returns true if tethering services are started
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "Generally track your own tethering requests. "
+            + "See also {@code android.net.INetd#tetherIsEnabled()}")
     boolean isTetheringStarted();
 
     /**
      * Tethers the specified interface
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "Avoid using this directly. Instead, enable tethering with "
+            + "{@code android.net.TetheringManager#startTethering}. See also "
+            + "{@code com.android.net.module.util.NetdUtils#tetherInterface}.")
     void tetherInterface(String iface);
 
     /**
      * Untethers the specified interface
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "Avoid using this directly. Instead, disable "
+            + "tethering with {@code android.net.TetheringManager#stopTethering(int)}. "
+            + "See also {@code NetdUtils#untetherInterface}.")
     void untetherInterface(String iface);
 
     /**
      * Returns a list of currently tethered interfaces
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "{@code android.net.TetheringManager#getTetheredIfaces()}")
     String[] listTetheredInterfaces();
 
     /**
@@ -176,13 +191,17 @@
      *  The address and netmask of the external interface is used for
      *  the NAT'ed network.
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "Avoid using this directly. Instead, enable tethering with "
+            + "{@code android.net.TetheringManager#startTethering}.")
     void enableNat(String internalInterface, String externalInterface);
 
     /**
      *  Disables Network Address Translation between two interfaces.
      */
-    @UnsupportedAppUsage
+    @UnsupportedAppUsage(maxTargetSdk = 34, trackingBug = 170729553,
+            publicAlternatives = "Avoid using this directly. Instead, disable tethering with "
+            + "{@code android.net.TetheringManager#stopTethering(int)}.")
     void disableNat(String internalInterface, String externalInterface);
 
     /**
diff --git a/core/java/android/os/OWNERS b/core/java/android/os/OWNERS
index 4899a4d..9bf04d2 100644
--- a/core/java/android/os/OWNERS
+++ b/core/java/android/os/OWNERS
@@ -10,6 +10,7 @@
 # BatteryStats
 per-file *BatteryConsumer* = file:/BATTERY_STATS_OWNERS
 per-file BatteryManager* = file:/BATTERY_STATS_OWNERS
+per-file PowerMonitor* = file:/BATTERY_STATS_OWNERS
 per-file PowerComponents.java = file:/BATTERY_STATS_OWNERS
 per-file *Stats* = file:/BATTERY_STATS_OWNERS
 
@@ -76,3 +77,10 @@
 
 # PermissionEnforcer
 per-file PermissionEnforcer.java = tweek@google.com, brufino@google.com
+
+# ART
+per-file ArtModuleServiceManager.java = file:platform/art:/OWNERS
+
+# PerformanceHintManager
+per-file PerformanceHintManager.java = file:/ADPF_OWNERS
+
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index aa733b5..bd040b2 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -33,7 +33,6 @@
 import android.compat.annotation.UnsupportedAppUsage;
 import android.content.Context;
 import android.service.dreams.Sandman;
-import android.sysprop.InitProperties;
 import android.util.ArrayMap;
 import android.util.Log;
 import android.util.proto.ProtoOutputStream;
@@ -873,6 +872,8 @@
 
     /**
      * The 'reason' value used for rebooting userspace.
+     *
+     * @deprecated userspace reboot is not supported
      * @hide
      */
     @SystemApi
@@ -1805,16 +1806,18 @@
      * <p>This method exists solely for the sake of re-using same logic between {@code PowerManager}
      * and {@code PowerManagerService}.
      *
+     * @deprecated TODO(b/292469129): remove this method.
      * @hide
      */
     public static boolean isRebootingUserspaceSupportedImpl() {
-        return InitProperties.is_userspace_reboot_supported().orElse(false);
+        return false;
     }
 
     /**
      * Returns {@code true} if this device supports rebooting userspace.
+     *
+     * @deprecated userspace reboot is deprecated, this method always returns {@code false}.
      */
-    // TODO(b/138605180): add link to documentation once it's ready.
     public boolean isRebootingUserspaceSupported() {
         return isRebootingUserspaceSupportedImpl();
     }
diff --git a/core/java/android/os/ServiceManager.java b/core/java/android/os/ServiceManager.java
index b210c46..e96c24d 100644
--- a/core/java/android/os/ServiceManager.java
+++ b/core/java/android/os/ServiceManager.java
@@ -245,7 +245,7 @@
     public static boolean isDeclared(@NonNull String name) {
         try {
             return getIServiceManager().isDeclared(name);
-        } catch (RemoteException e) {
+        } catch (RemoteException | SecurityException e) {
             Log.e(TAG, "error in isDeclared", e);
             return false;
         }
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index 83a4e9a..b32cbff 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -1527,6 +1527,31 @@
     public static final String DISALLOW_ULTRA_WIDEBAND_RADIO = "no_ultra_wideband_radio";
 
     /**
+     * This user restriction specifies if Near-fied communication is disallowed on the device. If
+     * Near-field communication is disallowed it cannot be turned on via Settings.
+     *
+     * <p>This restriction can only be set by a device owner or a profile owner of an
+     * organization-owned managed profile on the parent profile.
+     * In both cases, the restriction applies globally on the device and will turn off the
+     * Near-field communication radio if it's currently on and prevent the radio from being turned
+     * on in the future.
+     *
+     * <p>
+     * Near-field communication (NFC) is a radio technology that allows two devices (like your phone
+     * and a payments terminal) to communicate with each other when they're close together.
+     *
+     * <p>Default is <code>false</code>.
+     *
+     * <p>Key for user restrictions.
+     * <p>Type: Boolean
+     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
+     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
+     * @see #getUserRestrictions()
+     */
+    public static final String DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO =
+            "no_near_field_communication_radio";
+
+    /**
      * List of key values that can be passed into the various user restriction related methods
      * in {@link UserManager} & {@link DevicePolicyManager}.
      * Note: This is slightly different from the real set of user restrictions listed in {@link
@@ -1609,6 +1634,7 @@
             DISALLOW_ADD_WIFI_CONFIG,
             DISALLOW_CELLULAR_2G,
             DISALLOW_ULTRA_WIDEBAND_RADIO,
+            DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO,
     })
     @Retention(RetentionPolicy.SOURCE)
     public @interface UserRestrictionKey {}
diff --git a/core/java/android/os/flags.aconfig b/core/java/android/os/flags.aconfig
new file mode 100644
index 0000000..851aa6d
--- /dev/null
+++ b/core/java/android/os/flags.aconfig
@@ -0,0 +1,8 @@
+package: "android.os"
+
+flag {
+    name: "disallow_cellular_null_ciphers_restriction"
+    namespace: "cellular_security"
+    description: "Guards a new UserManager user restriction that admins can use to require cellular encryption on their managed devices."
+    bug: "276752881"
+}
diff --git a/core/java/android/os/storage/StorageManagerInternal.java b/core/java/android/os/storage/StorageManagerInternal.java
index 059bd84..22e8251 100644
--- a/core/java/android/os/storage/StorageManagerInternal.java
+++ b/core/java/android/os/storage/StorageManagerInternal.java
@@ -19,6 +19,7 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.UserIdInt;
+import android.content.pm.UserInfo;
 import android.os.IVold;
 
 import java.util.List;
@@ -169,4 +170,19 @@
      */
     public abstract void registerCloudProviderChangeListener(
             @NonNull CloudProviderChangeListener listener);
+
+    /**
+     * Prepares user data directories before moving storage or apps. This is required as adoptable
+     * storage unlock is tied to the prepare user data and storage needs to be unlocked before
+     * performing any operations on it. This will also create user data directories before
+     * initiating the move operations, which essential for ensuring the directories to have correct
+     * SELinux labels and permissions.
+     *
+     * @param fromVolumeUuid the source volume UUID from which content needs to be transferred
+     * @param toVolumeUuid the destination volume UUID to which contents are to be transferred
+     * @param users a list of users for whom to prepare storage
+     */
+    public abstract void prepareUserStorageForMove(String fromVolumeUuid, String toVolumeUuid,
+            List<UserInfo> users);
+
 }
diff --git a/core/java/android/permission/IPermissionManager.aidl b/core/java/android/permission/IPermissionManager.aidl
index 6a93b35..45dad98 100644
--- a/core/java/android/permission/IPermissionManager.aidl
+++ b/core/java/android/permission/IPermissionManager.aidl
@@ -77,8 +77,7 @@
     List<SplitPermissionInfoParcelable> getSplitPermissions();
 
     void startOneTimePermissionSession(String packageName, int userId, long timeout,
-            long revokeAfterKilledDelay, int importanceToResetTimer,
-            int importanceToKeepSessionAlive);
+            long revokeAfterKilledDelay);
 
     void stopOneTimePermissionSession(String packageName, int userId);
 
diff --git a/core/java/android/permission/PermissionManager.java b/core/java/android/permission/PermissionManager.java
index 6b540d7..6769954 100644
--- a/core/java/android/permission/PermissionManager.java
+++ b/core/java/android/permission/PermissionManager.java
@@ -1371,8 +1371,7 @@
             @ActivityManager.RunningAppProcessInfo.Importance int importanceToKeepSessionAlive) {
         try {
             mPermissionManager.startOneTimePermissionSession(packageName, mContext.getUserId(),
-                    timeoutMillis, revokeAfterKilledDelayMillis, importanceToResetTimer,
-                    importanceToKeepSessionAlive);
+                    timeoutMillis, revokeAfterKilledDelayMillis);
         } catch (RemoteException e) {
             e.rethrowFromSystemServer();
         }
diff --git a/core/java/android/print/OWNERS b/core/java/android/print/OWNERS
index 28a24203..0809de2 100644
--- a/core/java/android/print/OWNERS
+++ b/core/java/android/print/OWNERS
@@ -1,4 +1,4 @@
 # Bug component: 47273
 
-svetoslavganov@android.com
-svetoslavganov@google.com
+anothermark@google.com
+kumarashishg@google.com
diff --git a/core/java/android/print/pdf/OWNERS b/core/java/android/print/pdf/OWNERS
deleted file mode 100644
index 28a24203..0000000
--- a/core/java/android/print/pdf/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-# Bug component: 47273
-
-svetoslavganov@android.com
-svetoslavganov@google.com
diff --git a/core/java/android/printservice/OWNERS b/core/java/android/printservice/OWNERS
index 28a24203..0809de2 100644
--- a/core/java/android/printservice/OWNERS
+++ b/core/java/android/printservice/OWNERS
@@ -1,4 +1,4 @@
 # Bug component: 47273
 
-svetoslavganov@android.com
-svetoslavganov@google.com
+anothermark@google.com
+kumarashishg@google.com
diff --git a/core/java/android/printservice/recommendation/OWNERS b/core/java/android/printservice/recommendation/OWNERS
deleted file mode 100644
index 28a24203..0000000
--- a/core/java/android/printservice/recommendation/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-# Bug component: 47273
-
-svetoslavganov@android.com
-svetoslavganov@google.com
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 7a75769..507f1bb 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -1322,7 +1322,7 @@
 
     /**
      * Activity Action: Ask the user to allow an app to ignore battery optimizations (that is,
-     * put them on the whitelist of apps shown by
+     * put them on the allowlist of apps shown by
      * {@link #ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS}).  For an app to use this, it also
      * must hold the {@link android.Manifest.permission#REQUEST_IGNORE_BATTERY_OPTIMIZATIONS}
      * permission.
@@ -11543,7 +11543,7 @@
         public static final String BUGREPORT_IN_POWER_MENU = "bugreport_in_power_menu";
 
         /**
-         * The package name for the custom bugreport handler app. This app must be whitelisted.
+         * The package name for the custom bugreport handler app. This app must be allowlisted.
          * This is currently used only by Power Menu short press.
          *
          * @hide
@@ -11924,7 +11924,7 @@
                 "location_background_throttle_proximity_alert_interval_ms";
 
         /**
-         * Packages that are whitelisted for background throttling (throttling will not be applied).
+         * Packages that are allowlisted for background throttling (throttling will not be applied).
          * @hide
          */
         @Readable
@@ -11932,7 +11932,7 @@
             "location_background_throttle_package_whitelist";
 
         /**
-         * Packages that are whitelisted for ignoring location settings (may retrieve location even
+         * Packages that are allowlisted for ignoring location settings (may retrieve location even
          * when user location settings are off), for emergency purposes.
          * @deprecated No longer used from Android 12+
          * @hide
@@ -12465,7 +12465,7 @@
 
         /**
          * List of certificate (hex string representation of the application's certificate - SHA-1
-         * or SHA-256) and carrier app package pairs which are whitelisted to prompt the user for
+         * or SHA-256) and carrier app package pairs which are allowlisted to prompt the user for
          * install when a sim card with matching UICC carrier privilege rules is inserted.  The
          * certificate is used as a key, so the certificate encoding here must be the same as the
          * certificate encoding used on the SIM.
@@ -15841,7 +15841,7 @@
                 "enable_adb_incremental_install_default";
 
         /**
-         * The packages whitelisted to be run in autofill compatibility mode. The list
+         * The packages allowlisted to be run in autofill compatibility mode. The list
          * of packages is {@code ":"} colon delimited, and each entry has the name of the
          * package and an optional list of url bar resource ids (the list is delimited by
          * brackets&mdash{@code [} and {@code ]}&mdash and is also comma delimited).
@@ -15912,7 +15912,7 @@
         public static final String STYLUS_EVER_USED = "stylus_ever_used";
 
         /**
-         * Exemptions to the hidden API blacklist.
+         * Exemptions to the hidden API denylist.
          *
          * @hide
          */
diff --git a/core/java/android/security/OWNERS b/core/java/android/security/OWNERS
index 7140ff1..96c0be7 100644
--- a/core/java/android/security/OWNERS
+++ b/core/java/android/security/OWNERS
@@ -1,11 +1,10 @@
 # Bug component: 36824
 
-cbrubaker@google.com
-vishwath@google.com
+brambonne@google.com
+brufino@google.com
+jeffv@google.com
 
-per-file NetworkSecurityPolicy.java = cbrubaker@google.com
-per-file NetworkSecurityPolicy.java = klyubin@google.com
-per-file FrameworkNetworkSecurityPolicy.java = cbrubaker@google.com
-per-file FrameworkNetworkSecurityPolicy.java = klyubin@google.com
-per-file Confirmation*.java = jdanis@google.com
-per-file Confirmation*.java = swillden@google.com
+per-file *NetworkSecurityPolicy.java = file:net/OWNERS
+per-file Confirmation*.java = file:/keystore/OWNERS
+per-file FileIntegrityManager.java = file:platform/system/security:/fsverity/OWNERS
+per-file IFileIntegrityService.aidl = file:platform/system/security:/fsverity/OWNERS
diff --git a/core/java/android/security/flags.aconfig b/core/java/android/security/flags.aconfig
new file mode 100644
index 0000000..b6c2b83
--- /dev/null
+++ b/core/java/android/security/flags.aconfig
@@ -0,0 +1,15 @@
+package: "android.security"
+
+flag {
+    name: "fsverity_api"
+    namespace: "hardware_backed_security"
+    description: "Feature flag for fs-verity API"
+    bug: "285185747"
+}
+
+flag {
+    name: "fix_unlocked_device_required_keys"
+    namespace: "hardware_backed_security"
+    description: "Fix bugs in behavior of UnlockedDeviceRequired keystore keys"
+    bug: "296464083"
+}
diff --git a/core/java/android/security/keystore/OWNERS b/core/java/android/security/keystore/OWNERS
index 65129a4..d9e0116 100644
--- a/core/java/android/security/keystore/OWNERS
+++ b/core/java/android/security/keystore/OWNERS
@@ -1,5 +1 @@
-# Bug component: 189335
-
-swillden@google.com
-jdanis@google.com
-jbires@google.com
+include /keystore/OWNERS
diff --git a/core/java/android/security/keystore/recovery/OWNERS b/core/java/android/security/keystore/recovery/OWNERS
deleted file mode 100644
index 65129a4..0000000
--- a/core/java/android/security/keystore/recovery/OWNERS
+++ /dev/null
@@ -1,5 +0,0 @@
-# Bug component: 189335
-
-swillden@google.com
-jdanis@google.com
-jbires@google.com
diff --git a/core/java/android/security/net/OWNERS b/core/java/android/security/net/OWNERS
index d828164..1d52eed 100644
--- a/core/java/android/security/net/OWNERS
+++ b/core/java/android/security/net/OWNERS
@@ -1,4 +1,4 @@
 # Bug component: 36824
 
-cbrubaker@google.com
 brambonne@google.com
+jeffv@google.com
diff --git a/core/java/android/service/controls/Control.java b/core/java/android/service/controls/Control.java
index 3b757d6..33978be 100644
--- a/core/java/android/service/controls/Control.java
+++ b/core/java/android/service/controls/Control.java
@@ -50,7 +50,7 @@
  * and zone. Some of these values are defined by the user and/or the {@link ControlsProviderService}
  * and will be used to display the control as well as group them for management.
  * <p>
- * Each object will have an associated {@link DeviceTypes.DeviceType}. This will determine the icons and colors
+ * Each object will have an associated {@link DeviceTypes}. This will determine the icons and colors
  * used to display it.
  * <p>
  * An {@link Intent} linking to the provider Activity that expands on this {@link Control} and
@@ -420,7 +420,7 @@
      * This fixes the values relating to state of the {@link Control} as required by
      * {@link ControlsProviderService#createPublisherForAllAvailable}:
      * <ul>
-     *     <li> Status: {@link Status#STATUS_UNKNOWN}
+     *     <li> Status: {@link #STATUS_UNKNOWN}
      *     <li> Control template: {@link ControlTemplate#getNoTemplateObject}
      *     <li> Status text: {@code ""}
      *     <li> Auth Required: {@code true}
@@ -620,7 +620,7 @@
      *     <li> Device type: {@link DeviceTypes#TYPE_UNKNOWN}
      *     <li> Title: {@code ""}
      *     <li> Subtitle: {@code ""}
-     *     <li> Status: {@link Status#STATUS_UNKNOWN}
+     *     <li> Status: {@link #STATUS_UNKNOWN}
      *     <li> Control template: {@link ControlTemplate#getNoTemplateObject}
      *     <li> Status text: {@code ""}
      *     <li> Auth Required: {@code true}
diff --git a/core/java/android/service/controls/ControlsProviderService.java b/core/java/android/service/controls/ControlsProviderService.java
index ed24740..097abbb 100644
--- a/core/java/android/service/controls/ControlsProviderService.java
+++ b/core/java/android/service/controls/ControlsProviderService.java
@@ -158,7 +158,7 @@
      * The user has interacted with a Control. The action is dictated by the type of
      * {@link ControlAction} that was sent. A response can be sent via
      * {@link Consumer#accept}, with the Integer argument being one of the provided
-     * {@link ControlAction.ResponseResult}. The Integer should indicate whether the action
+     * {@link ControlAction} response results. The Integer should indicate whether the action
      * was received successfully, or if additional prompts should be presented to
      * the user. Any visual control updates should be sent via the Publisher.
 
diff --git a/core/java/android/service/controls/actions/ControlAction.java b/core/java/android/service/controls/actions/ControlAction.java
index 10f526d..4e38222 100644
--- a/core/java/android/service/controls/actions/ControlAction.java
+++ b/core/java/android/service/controls/actions/ControlAction.java
@@ -154,7 +154,7 @@
     public static final @ResponseResult int RESPONSE_CHALLENGE_PASSPHRASE = 5;
 
     /**
-     * The {@link ActionType} associated with this class.
+     * The action type associated with this class.
      */
     public abstract @ActionType int getActionType();
 
diff --git a/core/java/android/service/controls/templates/ControlTemplate.java b/core/java/android/service/controls/templates/ControlTemplate.java
index 3902d6a..0dd950d 100644
--- a/core/java/android/service/controls/templates/ControlTemplate.java
+++ b/core/java/android/service/controls/templates/ControlTemplate.java
@@ -137,7 +137,7 @@
     }
 
     /**
-     * The {@link TemplateType} associated with this class.
+     * The template type associated with this class.
      */
     public abstract @TemplateType int getTemplateType();
 
diff --git a/core/java/android/service/dreams/OWNERS b/core/java/android/service/dreams/OWNERS
index 489a5f6..77bcee8 100644
--- a/core/java/android/service/dreams/OWNERS
+++ b/core/java/android/service/dreams/OWNERS
@@ -4,5 +4,7 @@
 dsandler@google.com
 galinap@google.com
 jjaggi@google.com
+lusilva@google.com
 michaelwr@google.com
 santoscordon@google.com
+wxyz@google.com
diff --git a/core/java/android/service/gatekeeper/OWNERS b/core/java/android/service/gatekeeper/OWNERS
index 2ca52cd..7c4f285 100644
--- a/core/java/android/service/gatekeeper/OWNERS
+++ b/core/java/android/service/gatekeeper/OWNERS
@@ -1,3 +1,2 @@
-swillden@google.com
-jdanis@google.com
-jbires@google.com
+include platform/system/gatekeeper:/OWNERS
+include /services/core/java/com/android/server/locksettings/OWNERS
diff --git a/core/java/android/service/rotationresolver/OWNERS b/core/java/android/service/rotationresolver/OWNERS
index e381d17..5b57fc7 100644
--- a/core/java/android/service/rotationresolver/OWNERS
+++ b/core/java/android/service/rotationresolver/OWNERS
@@ -2,7 +2,6 @@
 
 asalo@google.com
 augale@google.com
-bquezada@google.com
 eejiang@google.com
 payamp@google.com
 siddikap@google.com
diff --git a/core/java/android/service/trust/OWNERS b/core/java/android/service/trust/OWNERS
index affe471..d352525 100644
--- a/core/java/android/service/trust/OWNERS
+++ b/core/java/android/service/trust/OWNERS
@@ -1,4 +1,4 @@
 # Bug component: 36824
 
-cbrubaker@google.com
-vishwath@google.com
+jacobhobbie@google.com
+dlm@google.com
diff --git a/core/java/android/service/watchdog/ExplicitHealthCheckService.java b/core/java/android/service/watchdog/ExplicitHealthCheckService.java
index 49e00d6..7befbfb 100644
--- a/core/java/android/service/watchdog/ExplicitHealthCheckService.java
+++ b/core/java/android/service/watchdog/ExplicitHealthCheckService.java
@@ -151,7 +151,7 @@
      */
     @NonNull public abstract List<String> onGetRequestedPackages();
 
-    private final Handler mHandler = new Handler(Looper.getMainLooper(), null, true);
+    private final Handler mHandler = Handler.createAsync(Looper.getMainLooper());
     @Nullable private RemoteCallback mCallback;
 
     @Override
diff --git a/core/java/android/speech/OWNERS b/core/java/android/speech/OWNERS
index 162e029..0f2f8ad 100644
--- a/core/java/android/speech/OWNERS
+++ b/core/java/android/speech/OWNERS
@@ -1,5 +1,4 @@
 volnov@google.com
 eugeniom@google.com
 schfan@google.com
-andreaambu@google.com
-hackz@google.com
\ No newline at end of file
+hackz@google.com
diff --git a/core/java/android/text/OWNERS b/core/java/android/text/OWNERS
index a6be687..0935ffd9 100644
--- a/core/java/android/text/OWNERS
+++ b/core/java/android/text/OWNERS
@@ -1,5 +1,6 @@
 set noparent
 
+grantapher@google.com
 halilibo@google.com
 haoyuchang@google.com
 justinghan@google.com
diff --git a/core/java/android/text/flags/use_bounds_for_width.aconfig b/core/java/android/text/flags/use_bounds_for_width.aconfig
new file mode 100644
index 0000000..d89d5f4
--- /dev/null
+++ b/core/java/android/text/flags/use_bounds_for_width.aconfig
@@ -0,0 +1,8 @@
+package: "com.android.text.flags"
+
+flag {
+  name: "use_bounds_for_width"
+  namespace: "text"
+  description: "Feature flag for preventing horizontal clipping."
+  bug: "63938206"
+}
diff --git a/core/java/android/util/Patterns.java b/core/java/android/util/Patterns.java
index ece069f..c4660c4 100644
--- a/core/java/android/util/Patterns.java
+++ b/core/java/android/util/Patterns.java
@@ -111,7 +111,7 @@
     /**
      *  Regular expression to match all IANA top-level domains.
      *
-     *  List accurate as of 2015/11/24.  List taken from:
+     *  List accurate as of 2023/09/11.  List taken from:
      *  http://data.iana.org/TLD/tlds-alpha-by-domain.txt
      *  This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py
      *
@@ -119,121 +119,167 @@
      */
     static final String IANA_TOP_LEVEL_DOMAINS =
         "(?:"
-        + "(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active"
-        + "|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam"
-        + "|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates"
-        + "|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])"
-        + "|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva"
-        + "|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black"
-        + "|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique"
-        + "|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business"
-        + "|buzz|bzh|b[abdefghijmnorstvwyz])"
-        + "|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards"
-        + "|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo"
-        + "|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco"
-        + "|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach"
-        + "|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos"
-        + "|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses"
-        + "|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])"
-        + "|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta"
-        + "|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount"
-        + "|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])"
-        + "|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises"
-        + "|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed"
-        + "|express|e[cegrstu])"
-        + "|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film"
-        + "|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth"
-        + "|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi"
-        + "|f[ijkmor])"
-        + "|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving"
-        + "|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger"
-        + "|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])"
-        + "|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings"
-        + "|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai"
-        + "|h[kmnrtu])"
-        + "|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute"
-        + "|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])"
-        + "|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])"
-        + "|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])"
-        + "|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc"
-        + "|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live"
-        + "|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])"
-        + "|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba"
-        + "|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda"
-        + "|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar"
-        + "|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])"
-        + "|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk"
-        + "|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])"
-        + "|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka"
-        + "|otsuka|ovh|om)"
-        + "|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography"
-        + "|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing"
-        + "|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property"
-        + "|protection|pub|p[aefghklmnrstwy])"
-        + "|(?:qpon|quebec|qa)"
-        + "|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals"
-        + "|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks"
-        + "|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])"
-        + "|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo"
-        + "|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security"
-        + "|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski"
-        + "|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting"
-        + "|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies"
-        + "|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])"
-        + "|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica"
-        + "|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools"
-        + "|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])"
-        + "|(?:ubs|university|uno|uol|u[agksyz])"
-        + "|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin"
-        + "|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])"
-        + "|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill"
-        + "|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])"
-        + "|(?:\u03b5\u03bb|\u0431\u0435\u043b|\u0434\u0435\u0442\u0438|\u043a\u043e\u043c|\u043c\u043a\u0434"
+        + "(?:aaa|aarp|abb|abbott|abbvie|abc|able|abogado|abudhabi|academy|accenture|accountant"
+        + "|accountants|aco|actor|ads|adult|aeg|aero|aetna|afl|africa|agakhan|agency|aig|airbus"
+        + "|airforce|airtel|akdn|alibaba|alipay|allfinanz|allstate|ally|alsace|alstom|amazon|americanexpress"
+        + "|americanfamily|amex|amfam|amica|amsterdam|analytics|android|anquan|anz|aol|apartments"
+        + "|app|apple|aquarelle|arab|aramco|archi|army|arpa|art|arte|asda|asia|associates|athleta"
+        + "|attorney|auction|audi|audible|audio|auspost|author|auto|autos|avianca|aws|axa|azure"
+        + "|a[cdefgilmoqrstuwxz])"
+        + "|(?:baby|baidu|banamex|bananarepublic|band|bank|bar|barcelona|barclaycard|barclays"
+        + "|barefoot|bargains|baseball|basketball|bauhaus|bayern|bbc|bbt|bbva|bcg|bcn|beats|beauty"
+        + "|beer|bentley|berlin|best|bestbuy|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black"
+        + "|blackfriday|blockbuster|blog|bloomberg|blue|bms|bmw|bnpparibas|boats|boehringer|bofa"
+        + "|bom|bond|boo|book|booking|bosch|bostik|boston|bot|boutique|box|bradesco|bridgestone"
+        + "|broadway|broker|brother|brussels|build|builders|business|buy|buzz|bzh|b[abdefghijmnorstvwyz])"
+        + "|(?:cab|cafe|cal|call|calvinklein|cam|camera|camp|canon|capetown|capital|capitalone"
+        + "|car|caravan|cards|care|career|careers|cars|casa|case|cash|casino|cat|catering|catholic"
+        + "|cba|cbn|cbre|cbs|center|ceo|cern|cfa|cfd|chanel|channel|charity|chase|chat|cheap|chintai"
+        + "|christmas|chrome|church|cipriani|circle|cisco|citadel|citi|citic|city|cityeats|claims"
+        + "|cleaning|click|clinic|clinique|clothing|cloud|club|clubmed|coach|codes|coffee|college"
+        + "|cologne|com|comcast|commbank|community|company|compare|computer|comsec|condos|construction"
+        + "|consulting|contact|contractors|cooking|cool|coop|corsica|country|coupon|coupons|courses"
+        + "|cpa|credit|creditcard|creditunion|cricket|crown|crs|cruise|cruises|cuisinella|cymru"
+        + "|cyou|c[acdfghiklmnoruvwxyz])"
+        + "|(?:dabur|dad|dance|data|date|dating|datsun|day|dclk|dds|deal|dealer|deals|degree"
+        + "|delivery|dell|deloitte|delta|democrat|dental|dentist|desi|design|dev|dhl|diamonds|diet"
+        + "|digital|direct|directory|discount|discover|dish|diy|dnp|docs|doctor|dog|domains|dot"
+        + "|download|drive|dtv|dubai|dunlop|dupont|durban|dvag|dvr|d[ejkmoz])"
+        + "|(?:earth|eat|eco|edeka|edu|education|email|emerck|energy|engineer|engineering|enterprises"
+        + "|epson|equipment|ericsson|erni|esq|estate|etisalat|eurovision|eus|events|exchange|expert"
+        + "|exposed|express|extraspace|e[cegrstu])"
+        + "|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|farmers|fashion|fast|fedex|feedback"
+        + "|ferrari|ferrero|fidelity|fido|film|final|finance|financial|fire|firestone|firmdale"
+        + "|fish|fishing|fit|fitness|flickr|flights|flir|florist|flowers|fly|foo|food|football"
+        + "|ford|forex|forsale|forum|foundation|fox|free|fresenius|frl|frogans|frontdoor|frontier"
+        + "|ftr|fujitsu|fun|fund|furniture|futbol|fyi|f[ijkmor])"
+        + "|(?:gal|gallery|gallo|gallup|game|games|gap|garden|gay|gbiz|gdn|gea|gent|genting"
+        + "|george|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmbh|gmo|gmx|godaddy"
+        + "|gold|goldpoint|golf|goo|goodyear|goog|google|gop|got|gov|grainger|graphics|gratis|green"
+        + "|gripe|grocery|group|guardian|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])"
+        + "|(?:hair|hamburg|hangout|haus|hbo|hdfc|hdfcbank|health|healthcare|help|helsinki|here"
+        + "|hermes|hiphop|hisamitsu|hitachi|hiv|hkt|hockey|holdings|holiday|homedepot|homegoods"
+        + "|homes|homesense|honda|horse|hospital|host|hosting|hot|hotels|hotmail|house|how|hsbc"
+        + "|hughes|hyatt|hyundai|h[kmnrtu])"
+        + "|(?:ibm|icbc|ice|icu|ieee|ifm|ikano|imamat|imdb|immo|immobilien|inc|industries|infiniti"
+        + "|info|ing|ink|institute|insurance|insure|int|international|intuit|investments|ipiranga"
+        + "|irish|ismaili|ist|istanbul|itau|itv|i[delmnoqrst])"
+        + "|(?:jaguar|java|jcb|jeep|jetzt|jewelry|jio|jll|jmp|jnj|jobs|joburg|jot|joy|jpmorgan"
+        + "|jprs|juegos|juniper|j[emop])"
+        + "|(?:kaufen|kddi|kerryhotels|kerrylogistics|kerryproperties|kfh|kia|kids|kim|kinder"
+        + "|kindle|kitchen|kiwi|koeln|komatsu|kosher|kpmg|kpn|krd|kred|kuokgroup|kyoto|k[eghimnprwyz])"
+        + "|(?:lacaixa|lamborghini|lamer|lancaster|land|landrover|lanxess|lasalle|lat|latino"
+        + "|latrobe|law|lawyer|lds|lease|leclerc|lefrak|legal|lego|lexus|lgbt|lidl|life|lifeinsurance"
+        + "|lifestyle|lighting|like|lilly|limited|limo|lincoln|link|lipsy|live|living|llc|llp|loan"
+        + "|loans|locker|locus|lol|london|lotte|lotto|love|lpl|lplfinancial|ltd|ltda|lundbeck|luxe"
+        + "|luxury|l[abcikrstuvy])"
+        + "|(?:madrid|maif|maison|makeup|man|management|mango|map|market|marketing|markets|marriott"
+        + "|marshalls|mattel|mba|mckinsey|med|media|meet|melbourne|meme|memorial|men|menu|merckmsd"
+        + "|miami|microsoft|mil|mini|mint|mit|mitsubishi|mlb|mls|mma|mobi|mobile|moda|moe|moi|mom"
+        + "|monash|money|monster|mormon|mortgage|moscow|moto|motorcycles|mov|movie|msd|mtn|mtr"
+        + "|museum|music|m[acdeghklmnopqrstuvwxyz])"
+        + "|(?:nab|nagoya|name|natura|navy|nba|nec|net|netbank|netflix|network|neustar|new|news"
+        + "|next|nextdirect|nexus|nfl|ngo|nhk|nico|nike|nikon|ninja|nissan|nissay|nokia|norton"
+        + "|now|nowruz|nowtv|nra|nrw|ntt|nyc|n[acefgilopruz])"
+        + "|(?:obi|observer|office|okinawa|olayan|olayangroup|oldnavy|ollo|omega|one|ong|onl"
+        + "|online|ooo|open|oracle|orange|org|organic|origins|osaka|otsuka|ott|ovh|om)"
+        + "|(?:page|panasonic|paris|pars|partners|parts|party|pay|pccw|pet|pfizer|pharmacy|phd"
+        + "|philips|phone|photo|photography|photos|physio|pics|pictet|pictures|pid|pin|ping|pink"
+        + "|pioneer|pizza|place|play|playstation|plumbing|plus|pnc|pohl|poker|politie|porn|post"
+        + "|pramerica|praxi|press|prime|pro|prod|productions|prof|progressive|promo|properties"
+        + "|property|protection|pru|prudential|pub|pwc|p[aefghklmnrstwy])"
+        + "|(?:qpon|quebec|quest|qa)"
+        + "|(?:racing|radio|read|realestate|realtor|realty|recipes|red|redstone|redumbrella"
+        + "|rehab|reise|reisen|reit|reliance|ren|rent|rentals|repair|report|republican|rest|restaurant"
+        + "|review|reviews|rexroth|rich|richardli|ricoh|ril|rio|rip|rocher|rocks|rodeo|rogers|room"
+        + "|rsvp|rugby|ruhr|run|rwe|ryukyu|r[eosuw])"
+        + "|(?:saarland|safe|safety|sakura|sale|salon|samsclub|samsung|sandvik|sandvikcoromant"
+        + "|sanofi|sap|sarl|sas|save|saxo|sbi|sbs|sca|scb|schaeffler|schmidt|scholarships|school"
+        + "|schule|schwarz|science|scot|search|seat|secure|security|seek|select|sener|services"
+        + "|seven|sew|sex|sexy|sfr|shangrila|sharp|shaw|shell|shia|shiksha|shoes|shop|shopping"
+        + "|shouji|show|showtime|silk|sina|singles|site|ski|skin|sky|skype|sling|smart|smile|sncf"
+        + "|soccer|social|softbank|software|sohu|solar|solutions|song|sony|soy|spa|space|sport"
+        + "|spot|srl|stada|staples|star|statebank|statefarm|stc|stcgroup|stockholm|storage|store"
+        + "|stream|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch"
+        + "|swiss|sydney|systems|s[abcdeghijklmnorstuvxyz])"
+        + "|(?:tab|taipei|talk|taobao|target|tatamotors|tatar|tattoo|tax|taxi|tci|tdk|team|tech"
+        + "|technology|tel|temasek|tennis|teva|thd|theater|theatre|tiaa|tickets|tienda|tips|tires"
+        + "|tirol|tjmaxx|tjx|tkmaxx|tmall|today|tokyo|tools|top|toray|toshiba|total|tours|town"
+        + "|toyota|toys|trade|trading|training|travel|travelers|travelersinsurance|trust|trv|tube"
+        + "|tui|tunes|tushu|tvs|t[cdfghjklmnortvwz])"
+        + "|(?:ubank|ubs|unicom|university|uno|uol|ups|u[agksyz])"
+        + "|(?:vacations|vana|vanguard|vegas|ventures|verisign|versicherung|vet|viajes|video"
+        + "|vig|viking|villas|vin|vip|virgin|visa|vision|viva|vivo|vlaanderen|vodka|volkswagen"
+        + "|volvo|vote|voting|voto|voyage|v[aceginu])"
+        + "|(?:wales|walmart|walter|wang|wanggou|watch|watches|weather|weatherchannel|webcam"
+        + "|weber|website|wed|wedding|weibo|weir|whoswho|wien|wiki|williamhill|win|windows|wine"
+        + "|winners|wme|wolterskluwer|woodside|work|works|world|wow|wtc|wtf|w[fs])"
+        + "|(?:\u03b5\u03bb|\u03b5\u03c5|\u0431\u0433|\u0431\u0435\u043b|\u0434\u0435\u0442\u0438"
+        + "|\u0435\u044e|\u043a\u0430\u0442\u043e\u043b\u0438\u043a|\u043a\u043e\u043c|\u043c\u043a\u0434"
         + "|\u043c\u043e\u043d|\u043c\u043e\u0441\u043a\u0432\u0430|\u043e\u043d\u043b\u0430\u0439\u043d"
         + "|\u043e\u0440\u0433|\u0440\u0443\u0441|\u0440\u0444|\u0441\u0430\u0439\u0442|\u0441\u0440\u0431"
-        + "|\u0443\u043a\u0440|\u049b\u0430\u0437|\u0570\u0561\u0575|\u05e7\u05d5\u05dd|\u0627\u0631\u0627\u0645\u0643\u0648"
-        + "|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629"
-        + "|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0627\u06cc\u0631\u0627\u0646"
-        + "|\u0628\u0627\u0632\u0627\u0631|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633"
-        + "|\u0633\u0648\u062f\u0627\u0646|\u0633\u0648\u0631\u064a\u0629|\u0634\u0628\u0643\u0629"
-        + "|\u0639\u0631\u0627\u0642|\u0639\u0645\u0627\u0646|\u0641\u0644\u0633\u0637\u064a\u0646"
-        + "|\u0642\u0637\u0631|\u0643\u0648\u0645|\u0645\u0635\u0631|\u0645\u0644\u064a\u0633\u064a\u0627"
-        + "|\u0645\u0648\u0642\u0639|\u0915\u0949\u092e|\u0928\u0947\u091f|\u092d\u093e\u0930\u0924"
-        + "|\u0938\u0902\u0917\u0920\u0928|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4"
-        + "|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd"
-        + "|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e04\u0e2d\u0e21|\u0e44\u0e17\u0e22"
-        + "|\u10d2\u10d4|\u307f\u3093\u306a|\u30b0\u30fc\u30b0\u30eb|\u30b3\u30e0|\u4e16\u754c"
-        + "|\u4e2d\u4fe1|\u4e2d\u56fd|\u4e2d\u570b|\u4e2d\u6587\u7f51|\u4f01\u4e1a|\u4f5b\u5c71"
-        + "|\u4fe1\u606f|\u5065\u5eb7|\u516b\u5366|\u516c\u53f8|\u516c\u76ca|\u53f0\u6e7e|\u53f0\u7063"
-        + "|\u5546\u57ce|\u5546\u5e97|\u5546\u6807|\u5728\u7ebf|\u5927\u62ff|\u5a31\u4e50|\u5de5\u884c"
-        + "|\u5e7f\u4e1c|\u6148\u5584|\u6211\u7231\u4f60|\u624b\u673a|\u653f\u52a1|\u653f\u5e9c"
-        + "|\u65b0\u52a0\u5761|\u65b0\u95fb|\u65f6\u5c1a|\u673a\u6784|\u6de1\u9a6c\u9521|\u6e38\u620f"
-        + "|\u70b9\u770b|\u79fb\u52a8|\u7ec4\u7ec7\u673a\u6784|\u7f51\u5740|\u7f51\u5e97|\u7f51\u7edc"
-        + "|\u8c37\u6b4c|\u96c6\u56e2|\u98de\u5229\u6d66|\u9910\u5385|\u9999\u6e2f|\ub2f7\ub137"
-        + "|\ub2f7\ucef4|\uc0bc\uc131|\ud55c\uad6d|xbox"
-        + "|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g"
-        + "|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim"
-        + "|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks"
-        + "|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a"
-        + "|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd"
-        + "|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h"
-        + "|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s"
-        + "|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c"
-        + "|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i"
-        + "|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d"
+        + "|\u0443\u043a\u0440|\u049b\u0430\u0437|\u0570\u0561\u0575|\u05d9\u05e9\u05e8\u05d0\u05dc"
+        + "|\u05e7\u05d5\u05dd|\u0627\u0628\u0648\u0638\u0628\u064a|\u0627\u062a\u0635\u0627\u0644\u0627\u062a"
+        + "|\u0627\u0631\u0627\u0645\u0643\u0648|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u0628\u062d\u0631\u064a\u0646"
+        + "|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629"
+        + "|\u0627\u0644\u0639\u0644\u064a\u0627\u0646|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a"
+        + "|\u0627\u06cc\u0631\u0627\u0646|\u0628\u0627\u0631\u062a|\u0628\u0627\u0632\u0627\u0631"
+        + "|\u0628\u064a\u062a\u0643|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633|\u0633\u0648\u062f\u0627\u0646"
+        + "|\u0633\u0648\u0631\u064a\u0629|\u0634\u0628\u0643\u0629|\u0639\u0631\u0627\u0642|\u0639\u0631\u0628"
+        + "|\u0639\u0645\u0627\u0646|\u0641\u0644\u0633\u0637\u064a\u0646|\u0642\u0637\u0631|\u0643\u0627\u062b\u0648\u0644\u064a\u0643"
+        + "|\u0643\u0648\u0645|\u0645\u0635\u0631|\u0645\u0644\u064a\u0633\u064a\u0627|\u0645\u0648\u0631\u064a\u062a\u0627\u0646\u064a\u0627"
+        + "|\u0645\u0648\u0642\u0639|\u0647\u0645\u0631\u0627\u0647|\u067e\u0627\u06a9\u0633\u062a\u0627\u0646"
+        + "|\u0680\u0627\u0631\u062a|\u0915\u0949\u092e|\u0928\u0947\u091f|\u092d\u093e\u0930\u0924"
+        + "|\u092d\u093e\u0930\u0924\u092e\u094d|\u092d\u093e\u0930\u094b\u0924|\u0938\u0902\u0917\u0920\u0928"
+        + "|\u09ac\u09be\u0982\u09b2\u09be|\u09ad\u09be\u09b0\u09a4|\u09ad\u09be\u09f0\u09a4|\u0a2d\u0a3e\u0a30\u0a24"
+        + "|\u0aad\u0abe\u0ab0\u0aa4|\u0b2d\u0b3e\u0b30\u0b24|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe"
+        + "|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd"
+        + "|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0cad\u0cbe\u0cb0\u0ca4|\u0d2d\u0d3e\u0d30\u0d24\u0d02"
+        + "|\u0dbd\u0d82\u0d9a\u0dcf|\u0e04\u0e2d\u0e21|\u0e44\u0e17\u0e22|\u0ea5\u0eb2\u0ea7|\u10d2\u10d4"
+        + "|\u307f\u3093\u306a|\u30a2\u30de\u30be\u30f3|\u30af\u30e9\u30a6\u30c9|\u30b0\u30fc\u30b0\u30eb"
+        + "|\u30b3\u30e0|\u30b9\u30c8\u30a2|\u30bb\u30fc\u30eb|\u30d5\u30a1\u30c3\u30b7\u30e7\u30f3"
+        + "|\u30dd\u30a4\u30f3\u30c8|\u4e16\u754c|\u4e2d\u4fe1|\u4e2d\u56fd|\u4e2d\u570b|\u4e2d\u6587\u7f51"
+        + "|\u4e9a\u9a6c\u900a|\u4f01\u4e1a|\u4f5b\u5c71|\u4fe1\u606f|\u5065\u5eb7|\u516b\u5366"
+        + "|\u516c\u53f8|\u516c\u76ca|\u53f0\u6e7e|\u53f0\u7063|\u5546\u57ce|\u5546\u5e97|\u5546\u6807"
+        + "|\u5609\u91cc|\u5609\u91cc\u5927\u9152\u5e97|\u5728\u7ebf|\u5927\u62ff|\u5929\u4e3b\u6559"
+        + "|\u5a31\u4e50|\u5bb6\u96fb|\u5e7f\u4e1c|\u5fae\u535a|\u6148\u5584|\u6211\u7231\u4f60"
+        + "|\u624b\u673a|\u62db\u8058|\u653f\u52a1|\u653f\u5e9c|\u65b0\u52a0\u5761|\u65b0\u95fb"
+        + "|\u65f6\u5c1a|\u66f8\u7c4d|\u673a\u6784|\u6de1\u9a6c\u9521|\u6e38\u620f|\u6fb3\u9580"
+        + "|\u70b9\u770b|\u79fb\u52a8|\u7ec4\u7ec7\u673a\u6784|\u7f51\u5740|\u7f51\u5e97|\u7f51\u7ad9"
+        + "|\u7f51\u7edc|\u8054\u901a|\u8c37\u6b4c|\u8d2d\u7269|\u901a\u8ca9|\u96c6\u56e2|\u96fb\u8a0a\u76c8\u79d1"
+        + "|\u98de\u5229\u6d66|\u98df\u54c1|\u9910\u5385|\u9999\u683c\u91cc\u62c9|\u9999\u6e2f"
+        + "|\ub2f7\ub137|\ub2f7\ucef4|\uc0bc\uc131|\ud55c\uad6d"
+        + "|xbox|xerox|xfinity|xihuan|xin|xn\\-\\-11b4c3d|xn\\-\\-1ck2e1b|xn\\-\\-1qqw23a|xn\\-\\-2scrj9c"
+        + "|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3hcrj9c|xn\\-\\-3pxu8k"
+        + "|xn\\-\\-42c2d9a|xn\\-\\-45br5cyl|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4dbrk0ce|xn\\-\\-4gbrim"
+        + "|xn\\-\\-54b7fta0cc|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-5su34j936bgsg|xn\\-\\-5tzm5g"
+        + "|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80aqecdr1a"
+        + "|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-8y0a063a|xn\\-\\-90a3ac|xn\\-\\-90ae|xn\\-\\-90ais"
+        + "|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-9krt00a|xn\\-\\-b4w605ferd|xn\\-\\-bck1b9a5dre4c"
+        + "|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cck2b3b|xn\\-\\-cckwcxetd|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd"
+        + "|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-e1a4c"
+        + "|xn\\-\\-eckvdtc9d|xn\\-\\-efvy88h|xn\\-\\-fct429k|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs"
+        + "|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d"
+        + "|xn\\-\\-fzc2c9e2c|xn\\-\\-fzys8d69uvgm|xn\\-\\-g2xx48c|xn\\-\\-gckr3f0f|xn\\-\\-gecrj9c"
+        + "|xn\\-\\-gk3at1e|xn\\-\\-h2breg3eve|xn\\-\\-h2brj9c|xn\\-\\-h2brj9c8c|xn\\-\\-hxt814e"
+        + "|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g"
+        + "|xn\\-\\-jlq480n2rg|xn\\-\\-jvr189m|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d"
         + "|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt"
-        + "|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e"
-        + "|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab"
-        + "|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema"
-        + "|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh"
-        + "|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c"
-        + "|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb"
-        + "|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a"
+        + "|xn\\-\\-mgba3a4f16a|xn\\-\\-mgba7c0bbn0a|xn\\-\\-mgbaakc7dvf|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd"
+        + "|xn\\-\\-mgbah1a3hjkrd|xn\\-\\-mgbai9azgqp6j|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a|xn\\-\\-mgbbh1a71e"
+        + "|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgbca7dzdo|xn\\-\\-mgbcpq6gpa1a|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbgu82a"
+        + "|xn\\-\\-mgbi4ecexp|xn\\-\\-mgbpl2fh|xn\\-\\-mgbt3dhd|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab"
+        + "|xn\\-\\-mix891f|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-ngbe9e0a|xn\\-\\-ngbrx"
+        + "|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl"
+        + "|xn\\-\\-otu796d|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q7ce6a"
+        + "|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxa6a|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-rovu88b"
+        + "|xn\\-\\-rvc1e0am3e|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-tiq49xqyj"
+        + "|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv"
+        + "|xn\\-\\-vuq861b|xn\\-\\-w4r85el8fhu5dnra|xn\\-\\-w4rs40l|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a"
         + "|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o"
-        + "|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)"
-        + "|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])"
-        + "|(?:zara|zip|zone|zuerich|z[amw]))";
-
+        + "|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xxx|xyz)"
+        + "|(?:yachts|yahoo|yamaxun|yandex|yodobashi|yoga|yokohama|you|youtube|yun|y[et])"
+        + "|(?:zappos|zara|zero|zip|zone|zuerich|z[amw]))";
     /**
      * Kept for backward compatibility reasons.
      *
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 483c39d..11e43dd 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -5223,11 +5223,6 @@
     @Retention(RetentionPolicy.SOURCE)
     public @interface LayerType {}
 
-    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
-            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
-            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
-            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
-    })
     int mLayerType = LAYER_TYPE_NONE;
     Paint mLayerPaint;
 
@@ -21206,6 +21201,8 @@
         mCurrentAnimation = null;
 
         if ((mViewFlags & TOOLTIP) == TOOLTIP) {
+            removeCallbacks(mTooltipInfo.mShowTooltipRunnable);
+            removeCallbacks(mTooltipInfo.mHideTooltipRunnable);
             hideTooltip();
         }
 
@@ -21886,6 +21883,11 @@
             @EnumEntry(value = LAYER_TYPE_SOFTWARE, name = "software"),
             @EnumEntry(value = LAYER_TYPE_HARDWARE, name = "hardware")
     })
+    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
+            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
+            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
+            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
+    })
     @LayerType
     public int getLayerType() {
         return mLayerType;
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 9f0ad11..6dace15 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -4400,7 +4400,7 @@
      * @param drawingPosition the drawing order position.
      * @return the container position of a child for this drawing order position.
      *
-     * @see #getChildDrawingOrder(int, int)}
+     * @see #getChildDrawingOrder(int, int)
      */
     public final int getChildDrawingOrder(int drawingPosition) {
         return getChildDrawingOrder(getChildCount(), drawingPosition);
diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java
index 033f726..d67a476 100644
--- a/core/java/android/view/WindowManager.java
+++ b/core/java/android/view/WindowManager.java
@@ -877,7 +877,7 @@
      * &lt;application&gt;
      *   &lt;property
      *     android:name=
-     *       "android.window.PROPERTY_COMPAT_IGNORE_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED"
+     *       "android.window.PROPERTY_COMPAT_ALLOW_IGNORING_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED"
      *     android:value="false"/&gt;
      * &lt;/application&gt;
      * </pre>
@@ -885,8 +885,8 @@
      * @hide
      */
     // TODO(b/274924641): Make this public API.
-    String PROPERTY_COMPAT_IGNORE_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED =
-            "android.window.PROPERTY_COMPAT_IGNORE_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED";
+    String PROPERTY_COMPAT_ALLOW_IGNORING_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED =
+            "android.window.PROPERTY_COMPAT_ALLOW_IGNORING_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED";
 
     /**
      * Application level {@link android.content.pm.PackageManager.Property PackageManager
diff --git a/core/java/android/view/textclassifier/TextClassifierEvent.java b/core/java/android/view/textclassifier/TextClassifierEvent.java
index 195565c..33db671 100644
--- a/core/java/android/view/textclassifier/TextClassifierEvent.java
+++ b/core/java/android/view/textclassifier/TextClassifierEvent.java
@@ -551,8 +551,8 @@
          * Sets the entity types. e.g. {@link TextClassifier#TYPE_ADDRESS}.
          * <p>
          * Supported types:
-         * <p>See {@link TextClassifier.EntityType}
-         * <p>See {@link ConversationAction.ActionType}
+         * <p>See {@link TextClassifier} types
+         * <p>See {@link ConversationAction} types
          * <p>See {@link ULocale#toLanguageTag()}
          */
         @NonNull
diff --git a/core/java/android/view/translation/TranslationCapability.java b/core/java/android/view/translation/TranslationCapability.java
index b7e13dd..52760f7 100644
--- a/core/java/android/view/translation/TranslationCapability.java
+++ b/core/java/android/view/translation/TranslationCapability.java
@@ -207,7 +207,7 @@
 
     /**
      * Translation flags for settings that are supported by the
-     * {@link android.service.translation.TranslationService} between the {@link TranslationSpec}s
+     * translation service between the {@link TranslationSpec}s
      * provided in this capability.
      */
     @DataClass.Generated.Member
diff --git a/core/java/android/view/translation/TranslationManager.java b/core/java/android/view/translation/TranslationManager.java
index fbaf711..4e7223e 100644
--- a/core/java/android/view/translation/TranslationManager.java
+++ b/core/java/android/view/translation/TranslationManager.java
@@ -56,7 +56,7 @@
  * translation framework.
  *
  * <p>The TranslationManager manages {@link Translator}s and help bridge client calls to
- * the server {@link android.service.translation.TranslationService} </p>
+ * the server translation service </p>
  */
 @SystemService(Context.TRANSLATION_MANAGER_SERVICE)
 public final class TranslationManager {
diff --git a/core/java/android/view/translation/TranslationRequest.java b/core/java/android/view/translation/TranslationRequest.java
index 027edc2..ff11ffa 100644
--- a/core/java/android/view/translation/TranslationRequest.java
+++ b/core/java/android/view/translation/TranslationRequest.java
@@ -27,7 +27,7 @@
 import java.util.List;
 
 /**
- * Translation request sent to the {@link android.service.translation.TranslationService} by the
+ * Translation request sent to the translation service by the
  * {@link android.view.translation.Translator} which contains the text to be translated.
  */
 @DataClass(genToString = true, genHiddenConstDefs = true, genBuilder = true)
diff --git a/core/java/android/view/translation/TranslationResponse.java b/core/java/android/view/translation/TranslationResponse.java
index b77f2e2..3362fc0 100644
--- a/core/java/android/view/translation/TranslationResponse.java
+++ b/core/java/android/view/translation/TranslationResponse.java
@@ -20,7 +20,6 @@
 import android.annotation.NonNull;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.service.translation.TranslationService;
 import android.util.SparseArray;
 
 import com.android.internal.util.DataClass;
@@ -30,17 +29,17 @@
 import java.util.Objects;
 
 /**
- * Response from the {@link TranslationService}, which contains the translated result.
+ * Response from the translation service, which contains the translated result.
  */
 @DataClass(genBuilder = true, genToString = true, genHiddenConstDefs = true)
 public final class TranslationResponse implements Parcelable {
 
     /**
-     * The {@link TranslationService} was successful in translating.
+     * The translation service was successful in translating.
      */
     public static final int TRANSLATION_STATUS_SUCCESS = 0;
     /**
-     * The {@link TranslationService} returned unknown translation result.
+     * The translation service returned unknown translation result.
      */
     public static final int TRANSLATION_STATUS_UNKNOWN_ERROR = 1;
     /**
diff --git a/core/java/android/view/translation/TranslationResponseValue.java b/core/java/android/view/translation/TranslationResponseValue.java
index 9dff2d5..18a240d 100644
--- a/core/java/android/view/translation/TranslationResponseValue.java
+++ b/core/java/android/view/translation/TranslationResponseValue.java
@@ -27,7 +27,7 @@
 import java.util.Objects;
 
 /**
- * A translated response value from {@link android.service.translation.TranslationService}.
+ * A translated response value from translation service.
  */
 @DataClass(genBuilder = true, genToString = true, genEqualsHashCode = true,
         genHiddenConstDefs = true)
diff --git a/core/java/android/view/translation/ViewTranslationRequest.java b/core/java/android/view/translation/ViewTranslationRequest.java
index a41749a..54b8ac2 100644
--- a/core/java/android/view/translation/ViewTranslationRequest.java
+++ b/core/java/android/view/translation/ViewTranslationRequest.java
@@ -33,7 +33,7 @@
 
 /**
  * Wrapper class representing a translation request associated with a {@link android.view.View} to
- * be used by {@link android.service.translation.TranslationService}.
+ * be used by translation service.
  */
 @DataClass(genBuilder = false, genToString = true, genEqualsHashCode = true, genGetters = false,
         genHiddenConstructor = true, genHiddenConstDefs = true)
diff --git a/core/java/android/view/translation/ViewTranslationResponse.java b/core/java/android/view/translation/ViewTranslationResponse.java
index d993114..134ff5a 100644
--- a/core/java/android/view/translation/ViewTranslationResponse.java
+++ b/core/java/android/view/translation/ViewTranslationResponse.java
@@ -33,7 +33,7 @@
 
 /**
  * Wrapper class representing a translation response associated with a {@link android.view.View} to
- * be used by {@link android.service.translation.TranslationService}.
+ * be used by translation service.
  */
 @DataClass(genBuilder = true, genToString = true, genEqualsHashCode = true, genGetters = false)
 public final class ViewTranslationResponse implements Parcelable {
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index a339062..c985ae8 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -726,6 +726,12 @@
                 mActions.get(i).visitUris(visitor);
             }
         }
+        if (mLandscape != null) {
+            mLandscape.visitUris(visitor);
+        }
+        if (mPortrait != null) {
+            mPortrait.visitUris(visitor);
+        }
     }
 
     private static void visitIconUri(Icon icon, @NonNull Consumer<Uri> visitor) {
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 450bb1e..81320a4 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -13355,6 +13355,9 @@
 
         final ClipDescription description =
                 getClipboardManagerForUser().getPrimaryClipDescription();
+        if (description == null) {
+            return false;
+        }
         final boolean isPlainType = description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
         return (isPlainType && description.isStyledText())
                 || description.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML);
diff --git a/core/java/android/window/flags/windowing_frontend.aconfig b/core/java/android/window/flags/windowing_frontend.aconfig
new file mode 100644
index 0000000..7a4c5bc
--- /dev/null
+++ b/core/java/android/window/flags/windowing_frontend.aconfig
@@ -0,0 +1,8 @@
+package: "com.android.window.flags"
+
+flag {
+  name: "nav_bar_transparent_by_default"
+  namespace: "windowing_frontend"
+  description: "Make nav bar color transparent by default when targeting SDK 35 or greater"
+  bug: "232195501"
+}
diff --git a/core/java/android/window/flags/windowing_sdk.aconfig b/core/java/android/window/flags/windowing_sdk.aconfig
new file mode 100644
index 0000000..560e41b
--- /dev/null
+++ b/core/java/android/window/flags/windowing_sdk.aconfig
@@ -0,0 +1,10 @@
+package: "com.android.window.flags"
+
+# Project link: https://gantry.corp.google.com/projects/android_platform_windowing_sdk/changes
+
+flag {
+    namespace: "windowing_sdk"
+    name: "sync_window_config_update_flag"
+    description: "Whether the feature to sync different window-related config updates is enabled"
+    bug: "260873529"
+}
diff --git a/core/java/com/android/internal/content/om/OverlayConfig.java b/core/java/com/android/internal/content/om/OverlayConfig.java
index fc0943b..e8bdd1d 100644
--- a/core/java/com/android/internal/content/om/OverlayConfig.java
+++ b/core/java/com/android/internal/content/om/OverlayConfig.java
@@ -34,8 +34,15 @@
 import com.android.internal.util.Preconditions;
 import com.android.internal.util.function.TriConsumer;
 
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -46,6 +53,10 @@
 import java.util.Map;
 import java.util.function.Supplier;
 
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
 /**
  * Responsible for reading overlay configuration files and handling queries of overlay mutability,
  * default-enabled state, and priority.
@@ -61,6 +72,8 @@
     @VisibleForTesting
     public static final int DEFAULT_PRIORITY = Integer.MAX_VALUE;
 
+    public static final String PARTITION_ORDER_FILE_PATH = "/product/overlay/partition_order.xml";
+
     @VisibleForTesting
     public static final class Configuration {
         @Nullable
@@ -119,6 +132,10 @@
     // Singleton instance only assigned in system server
     private static OverlayConfig sInstance;
 
+    private final String mPartitionOrder;
+
+    private final boolean mIsDefaultPartitionOrder;
+
     @VisibleForTesting
     public OverlayConfig(@Nullable File rootDirectory,
             @Nullable Supplier<OverlayScanner> scannerFactory,
@@ -137,6 +154,8 @@
                             new File(rootDirectory, p.getNonConicalFolder().getPath()),
                             p)));
         }
+        mIsDefaultPartitionOrder = !sortPartitions(PARTITION_ORDER_FILE_PATH, partitions);
+        mPartitionOrder = generatePartitionOrderString(partitions);
 
         ArrayMap<Integer, List<String>> activeApexesPerPartition = getActiveApexes(partitions);
 
@@ -198,6 +217,96 @@
         }
     }
 
+    private static String generatePartitionOrderString(List<OverlayPartition> partitions) {
+        if (partitions == null || partitions.size() == 0) {
+            return "";
+        }
+        StringBuilder partitionOrder = new StringBuilder();
+        partitionOrder.append(partitions.get(0).getName());
+        for (int i = 1; i < partitions.size(); i++) {
+            partitionOrder.append(", ").append(partitions.get(i).getName());
+        }
+        return partitionOrder.toString();
+    }
+
+    private static boolean parseAndValidatePartitionsOrderXml(String partitionOrderFilePath,
+            Map<String, Integer> orderMap, List<OverlayPartition> partitions) {
+        try {
+            File file = new File(partitionOrderFilePath);
+            if (!file.exists()) {
+                Log.w(TAG, "partition_order.xml does not exist.");
+                return false;
+            }
+            var dbFactory = DocumentBuilderFactory.newInstance();
+            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
+            Document doc = dBuilder.parse(file);
+            doc.getDocumentElement().normalize();
+
+            Element root = doc.getDocumentElement();
+            if (!root.getNodeName().equals("partition-order")) {
+                Log.w(TAG, "Invalid partition_order.xml, "
+                        + "xml root element is not partition-order");
+                return false;
+            }
+
+            NodeList partitionList = doc.getElementsByTagName("partition");
+            for (int order = 0; order < partitionList.getLength(); order++) {
+                Node partitionNode = partitionList.item(order);
+                if (partitionNode.getNodeType() == Node.ELEMENT_NODE) {
+                    Element partitionElement = (Element) partitionNode;
+                    String partitionName = partitionElement.getAttribute("name");
+                    if (orderMap.containsKey(partitionName)) {
+                        Log.w(TAG, "Invalid partition_order.xml, "
+                                + "it has duplicate partition: " + partitionName);
+                        return false;
+                    }
+                    orderMap.put(partitionName, order);
+                }
+            }
+
+            if (orderMap.keySet().size() != partitions.size()) {
+                Log.w(TAG, "Invalid partition_order.xml, partition_order.xml has "
+                        + orderMap.keySet().size() + " partitions, "
+                        + "which is different from SYSTEM_PARTITIONS");
+                return false;
+            }
+            for (int i = 0; i < partitions.size(); i++) {
+                if (!orderMap.keySet().contains(partitions.get(i).getName())) {
+                    Log.w(TAG, "Invalid Parsing partition_order.xml, "
+                            + "partition_order.xml does not have partition: "
+                            + partitions.get(i).getName());
+                    return false;
+                }
+            }
+        } catch (ParserConfigurationException | SAXException | IOException e) {
+            Log.w(TAG, "Parsing or validating partition_order.xml failed, "
+                    + "exception thrown: " + e.getMessage());
+            return false;
+        }
+        Log.i(TAG, "Sorting partitions in the specified order from partitions_order.xml");
+        return true;
+    }
+
+    /**
+     * Sort partitions by order in partition_order.xml if the file exists.
+     *
+     * @hide
+     */
+    @VisibleForTesting
+    public static boolean sortPartitions(String partitionOrderFilePath,
+            List<OverlayPartition> partitions) {
+        Map<String, Integer> orderMap = new HashMap<>();
+        if (!parseAndValidatePartitionsOrderXml(partitionOrderFilePath, orderMap, partitions)) {
+            return false;
+        }
+
+        Comparator<OverlayPartition> partitionComparator = Comparator.comparingInt(
+                o -> orderMap.get(o.getName()));
+        Collections.sort(partitions, partitionComparator);
+
+        return true;
+    }
+
     /**
      * Creates an instance of OverlayConfig for use in the zygote process.
      * This instance will not include information of static overlays existing outside of a partition
@@ -476,4 +585,19 @@
      */
     private static native String[] createIdmap(@NonNull String targetPath,
             @NonNull String[] overlayPath, @NonNull String[] policies, boolean enforceOverlayable);
+
+    /**
+     * @hide
+     */
+    public boolean isDefaultPartitionOrder() {
+        return mIsDefaultPartitionOrder;
+    }
+
+    /**
+     * @hide
+     */
+    public String getPartitionOrder() {
+        return mPartitionOrder;
+    }
+
 }
diff --git a/core/java/com/android/internal/content/om/OverlayConfigParser.java b/core/java/com/android/internal/content/om/OverlayConfigParser.java
index 0ab7b3d..5a86b93 100644
--- a/core/java/com/android/internal/content/om/OverlayConfigParser.java
+++ b/core/java/com/android/internal/content/om/OverlayConfigParser.java
@@ -27,6 +27,7 @@
 import android.util.Log;
 import android.util.Xml;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.content.om.OverlayScanner.ParsedOverlayInfo;
 import com.android.internal.util.Preconditions;
 import com.android.internal.util.XmlUtils;
@@ -53,8 +54,11 @@
  *
  * @see #parseOverlay(File, XmlPullParser, OverlayScanner, ParsingContext)
  * @see #parseMerge(File, XmlPullParser, OverlayScanner, ParsingContext)
+ *
+ * @hide
  **/
-final class OverlayConfigParser {
+@VisibleForTesting
+public final class OverlayConfigParser {
 
     // Default values for overlay configurations.
     static final boolean DEFAULT_ENABLED_STATE = false;
@@ -115,7 +119,11 @@
         }
     }
 
-    static class OverlayPartition extends SystemPartition {
+    /**
+     * @hide
+     **/
+    @VisibleForTesting
+    public static class OverlayPartition extends SystemPartition {
         // Policies passed to idmap2 during idmap creation.
         // Keep partition policy constants in sync with f/b/cmds/idmap2/include/idmap2/Policies.h.
         static final String POLICY_ODM = "odm";
@@ -128,7 +136,11 @@
         @NonNull
         public final String policy;
 
-        OverlayPartition(@NonNull SystemPartition partition) {
+        /**
+         * @hide
+         **/
+        @VisibleForTesting
+        public OverlayPartition(@NonNull SystemPartition partition) {
             super(partition);
             this.policy = policyForPartition(partition);
         }
diff --git a/core/java/com/android/internal/dynamicanimation/animation/DynamicAnimation.java b/core/java/com/android/internal/dynamicanimation/animation/DynamicAnimation.java
index d4fe7c8d..03f10b6 100644
--- a/core/java/com/android/internal/dynamicanimation/animation/DynamicAnimation.java
+++ b/core/java/com/android/internal/dynamicanimation/animation/DynamicAnimation.java
@@ -651,7 +651,7 @@
             if (!mStartValueIsSet) {
                 mValue = getPropertyValue();
             }
-            // Sanity check:
+            // Initial check:
             if (mValue > mMaxValue || mValue < mMinValue) {
                 throw new IllegalArgumentException("Starting value need to be in between min"
                         + " value and max value");
diff --git a/core/java/com/android/internal/dynamicanimation/animation/SpringForce.java b/core/java/com/android/internal/dynamicanimation/animation/SpringForce.java
index 36242ae2..dea4907 100644
--- a/core/java/com/android/internal/dynamicanimation/animation/SpringForce.java
+++ b/core/java/com/android/internal/dynamicanimation/animation/SpringForce.java
@@ -228,7 +228,7 @@
     }
 
     /**
-     * Initialize the string by doing the necessary pre-calculation as well as some sanity check
+     * Initialize the string by doing the necessary pre-calculation as well as some initial check
      * on the setup.
      *
      * @throws IllegalStateException if the final position is not yet set by the time the spring
diff --git a/core/java/com/android/internal/net/OWNERS b/core/java/com/android/internal/net/OWNERS
index 71f997b..7157683 100644
--- a/core/java/com/android/internal/net/OWNERS
+++ b/core/java/com/android/internal/net/OWNERS
@@ -1,4 +1,4 @@
 set noparent
-file:platform/packages/modules/Connectivity:master:/OWNERS_core_networking
+file:platform/packages/modules/Connectivity:main:/OWNERS_core_networking
 
 jsharkey@android.com
diff --git a/core/java/com/android/internal/os/Zygote.java b/core/java/com/android/internal/os/Zygote.java
index d8aeb51..26c5b87 100644
--- a/core/java/com/android/internal/os/Zygote.java
+++ b/core/java/com/android/internal/os/Zygote.java
@@ -195,6 +195,12 @@
      */
     public static final int PROFILEABLE = 1 << 24;
 
+    /**
+     * Enable ptrace.  This is enabled on eng, if the app is debuggable, or if
+     * the persist.debug.ptrace.enabled property is set.
+     */
+    public static final int DEBUG_ENABLE_PTRACE = 1 << 25;
+
     /** No external storage should be mounted. */
     public static final int MOUNT_EXTERNAL_NONE = IVold.REMOUNT_MODE_NONE;
     /** Default external storage should be mounted. */
@@ -1015,18 +1021,36 @@
                           "persist.debug.dalvik.vm.jdwp.enabled").equals("1");
 
     /**
+     * This will enable ptrace by default for all apps. It is OK to cache this property
+     * because we expect to reboot the system whenever this property changes
+     */
+    private static final boolean ENABLE_PTRACE = SystemProperties.get(
+                          "persist.debug.ptrace.enabled").equals("1");
+
+    /**
      * Applies debugger system properties to the zygote arguments.
      *
-     * For eng builds all apps are debuggable. On userdebug and user builds
-     * if persist.debug.dalvik.vm.jdwp.enabled is 1 all apps are
-     * debuggable. Otherwise, the debugger state is specified via the
-     * "--enable-jdwp" flag in the spawn request.
+     * For eng builds all apps are debuggable with JDWP and ptrace.
+     *
+     * On userdebug builds if persist.debug.dalvik.vm.jdwp.enabled
+     * is 1 all apps are debuggable with JDWP and ptrace. Otherwise, the
+     * debugger state is specified via the "--enable-jdwp" flag in the
+     * spawn request.
+     *
+     * On userdebug builds if persist.debug.ptrace.enabled is 1 all
+     * apps are debuggable with ptrace.
      *
      * @param args non-null; zygote spawner args
      */
     static void applyDebuggerSystemProperty(ZygoteArguments args) {
-        if (Build.IS_ENG || ENABLE_JDWP) {
+        if (Build.IS_ENG || (Build.IS_USERDEBUG && ENABLE_JDWP)) {
             args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
+            // Also enable ptrace when JDWP is enabled for consistency with
+            // before persist.debug.ptrace.enabled existed.
+            args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_PTRACE;
+        }
+        if (Build.IS_ENG || (Build.IS_USERDEBUG && ENABLE_PTRACE)) {
+            args.mRuntimeFlags |= Zygote.DEBUG_ENABLE_PTRACE;
         }
     }
 
@@ -1049,7 +1073,8 @@
         int peerUid = peer.getUid();
 
         if (args.mInvokeWith != null && peerUid != 0
-                && (args.mRuntimeFlags & Zygote.DEBUG_ENABLE_JDWP) == 0) {
+                && (args.mRuntimeFlags
+                    & (Zygote.DEBUG_ENABLE_JDWP | Zygote.DEBUG_ENABLE_PTRACE)) == 0) {
             throw new ZygoteSecurityException("Peer is permitted to specify an "
                 + "explicit invoke-with wrapper command only for debuggable "
                 + "applications.");
diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java
index 85cb15b..b3938b4 100644
--- a/core/java/com/android/internal/os/ZygoteInit.java
+++ b/core/java/com/android/internal/os/ZygoteInit.java
@@ -26,7 +26,6 @@
 import android.compat.annotation.UnsupportedAppUsage;
 import android.content.pm.SharedLibraryInfo;
 import android.content.res.Resources;
-import android.content.res.TypedArray;
 import android.os.Build;
 import android.os.Environment;
 import android.os.IInstalld;
@@ -102,21 +101,10 @@
     private static final String SOCKET_NAME_ARG = "--socket-name=";
 
     /**
-     * Used to pre-load resources.
-     */
-    @UnsupportedAppUsage
-    private static Resources mResources;
-
-    /**
      * The path of a file that contains classes to preload.
      */
     private static final String PRELOADED_CLASSES = "/system/etc/preloaded-classes";
 
-    /**
-     * Controls whether we should preload resources during zygote init.
-     */
-    private static final boolean PRELOAD_RESOURCES = true;
-
     private static final int UNPRIVILEGED_UID = 9999;
     private static final int UNPRIVILEGED_GID = 9999;
 
@@ -143,7 +131,7 @@
         cacheNonBootClasspathClassLoaders();
         bootTimingsTraceLog.traceEnd(); // CacheNonBootClasspathClassLoaders
         bootTimingsTraceLog.traceBegin("PreloadResources");
-        preloadResources();
+        Resources.preloadResources();
         bootTimingsTraceLog.traceEnd(); // PreloadResources
         Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadAppProcessHALs");
         nativePreloadAppProcessHALs();
@@ -414,87 +402,6 @@
     }
 
     /**
-     * Load in commonly used resources, so they can be shared across processes.
-     *
-     * These tend to be a few Kbytes, but are frequently in the 20-40K range, and occasionally even
-     * larger.
-     */
-    private static void preloadResources() {
-        try {
-            mResources = Resources.getSystem();
-            mResources.startPreloading();
-            if (PRELOAD_RESOURCES) {
-                Log.i(TAG, "Preloading resources...");
-
-                long startTime = SystemClock.uptimeMillis();
-                TypedArray ar = mResources.obtainTypedArray(
-                        com.android.internal.R.array.preloaded_drawables);
-                int N = preloadDrawables(ar);
-                ar.recycle();
-                Log.i(TAG, "...preloaded " + N + " resources in "
-                        + (SystemClock.uptimeMillis() - startTime) + "ms.");
-
-                startTime = SystemClock.uptimeMillis();
-                ar = mResources.obtainTypedArray(
-                        com.android.internal.R.array.preloaded_color_state_lists);
-                N = preloadColorStateLists(ar);
-                ar.recycle();
-                Log.i(TAG, "...preloaded " + N + " resources in "
-                        + (SystemClock.uptimeMillis() - startTime) + "ms.");
-
-                if (mResources.getBoolean(
-                        com.android.internal.R.bool.config_freeformWindowManagement)) {
-                    startTime = SystemClock.uptimeMillis();
-                    ar = mResources.obtainTypedArray(
-                            com.android.internal.R.array.preloaded_freeform_multi_window_drawables);
-                    N = preloadDrawables(ar);
-                    ar.recycle();
-                    Log.i(TAG, "...preloaded " + N + " resource in "
-                            + (SystemClock.uptimeMillis() - startTime) + "ms.");
-                }
-            }
-            mResources.finishPreloading();
-        } catch (RuntimeException e) {
-            Log.w(TAG, "Failure preloading resources", e);
-        }
-    }
-
-    private static int preloadColorStateLists(TypedArray ar) {
-        int N = ar.length();
-        for (int i = 0; i < N; i++) {
-            int id = ar.getResourceId(i, 0);
-
-            if (id != 0) {
-                if (mResources.getColorStateList(id, null) == null) {
-                    throw new IllegalArgumentException(
-                            "Unable to find preloaded color resource #0x"
-                                    + Integer.toHexString(id)
-                                    + " (" + ar.getString(i) + ")");
-                }
-            }
-        }
-        return N;
-    }
-
-
-    private static int preloadDrawables(TypedArray ar) {
-        int N = ar.length();
-        for (int i = 0; i < N; i++) {
-            int id = ar.getResourceId(i, 0);
-
-            if (id != 0) {
-                if (mResources.getDrawable(id, null) == null) {
-                    throw new IllegalArgumentException(
-                            "Unable to find preloaded drawable resource #0x"
-                                    + Integer.toHexString(id)
-                                    + " (" + ar.getString(i) + ")");
-                }
-            }
-        }
-        return N;
-    }
-
-    /**
      * Runs several special GCs to try to clean up a few generations of softly- and final-reachable
      * objects, along with any other garbage. This is only useful just before a fork().
      */
diff --git a/core/java/com/android/internal/policy/DecorView.java b/core/java/com/android/internal/policy/DecorView.java
index f998a69..e2a0c49 100644
--- a/core/java/com/android/internal/policy/DecorView.java
+++ b/core/java/com/android/internal/policy/DecorView.java
@@ -2660,8 +2660,7 @@
 
     @Override
     public String toString() {
-        return "DecorView@" + Integer.toHexString(this.hashCode()) + "["
-                + getTitleSuffix(mWindow.getAttributes()) + "]";
+        return super.toString() + "[" + getTitleSuffix(mWindow.getAttributes()) + "]";
     }
 
     private static class ColorViewState {
diff --git a/core/java/com/android/internal/util/FastDataInput.java b/core/java/com/android/internal/util/FastDataInput.java
index 5117034..3548bcb 100644
--- a/core/java/com/android/internal/util/FastDataInput.java
+++ b/core/java/com/android/internal/util/FastDataInput.java
@@ -269,6 +269,10 @@
 
             return s;
         } else {
+            if (ref >= mStringRefs.length) {
+                throw new IOException("Invalid interned string reference " + ref + " for "
+                        + mStringRefs.length + " interned strings");
+            }
             return mStringRefs[ref];
         }
     }
diff --git a/core/java/com/android/internal/util/FileRotator.java b/core/java/com/android/internal/util/FileRotator.java
index 5bc48c5..c9d9926 100644
--- a/core/java/com/android/internal/util/FileRotator.java
+++ b/core/java/com/android/internal/util/FileRotator.java
@@ -19,6 +19,9 @@
 import android.annotation.NonNull;
 import android.os.FileUtils;
 import android.util.Log;
+import android.util.Pair;
+
+import libcore.io.IoUtils;
 
 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
@@ -28,12 +31,12 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
+import java.util.Comparator;
 import java.util.Objects;
+import java.util.TreeSet;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipOutputStream;
 
-import libcore.io.IoUtils;
-
 /**
  * Utility that rotates files over time, similar to {@code logrotate}. There is
  * a single "active" file, which is periodically rotated into historical files,
@@ -302,17 +305,24 @@
     public void readMatching(Reader reader, long matchStartMillis, long matchEndMillis)
             throws IOException {
         final FileInfo info = new FileInfo(mPrefix);
+        final TreeSet<Pair<Long, String>> readSet = new TreeSet<>(
+                Comparator.comparingLong(o -> o.first));
         for (String name : mBasePath.list()) {
             if (!info.parse(name)) continue;
 
-            // read file when it overlaps
+            // Add file to set when it overlaps.
             if (info.startMillis <= matchEndMillis && matchStartMillis <= info.endMillis) {
-                if (LOGD) Log.d(TAG, "reading matching " + name);
-
-                final File file = new File(mBasePath, name);
-                readFile(file, reader);
+                readSet.add(new Pair(info.startMillis, name));
             }
         }
+
+        // Read files in ascending order of start timestamp.
+        for (Pair<Long, String> pair : readSet) {
+            final String name = pair.second;
+            if (LOGD) Log.d(TAG, "reading matching " + name);
+            final File file = new File(mBasePath, name);
+            readFile(file, reader);
+        }
     }
 
     /**
diff --git a/core/java/com/android/internal/widget/LockPatternUtils.java b/core/java/com/android/internal/widget/LockPatternUtils.java
index 5b2c441..30a3e11 100644
--- a/core/java/com/android/internal/widget/LockPatternUtils.java
+++ b/core/java/com/android/internal/widget/LockPatternUtils.java
@@ -986,7 +986,7 @@
      */
     @UnsupportedAppUsage
     public boolean isVisiblePatternEnabled(int userId) {
-        return getBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE, false, userId);
+        return getBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE, true, userId);
     }
 
     /**
@@ -1022,13 +1022,6 @@
     }
 
     /**
-     * Set whether the visible password is enabled for cryptkeeper screen.
-     */
-    public void setVisiblePasswordEnabled(boolean enabled, int userId) {
-        // No longer does anything.
-    }
-
-    /**
      * Set and store the lockout deadline, meaning the user can't attempt their unlock
      * pattern until the deadline has passed.
      * @return the chosen deadline.
diff --git a/core/java/com/android/internal/widget/OWNERS b/core/java/com/android/internal/widget/OWNERS
index d068a3a..e2672f5 100644
--- a/core/java/com/android/internal/widget/OWNERS
+++ b/core/java/com/android/internal/widget/OWNERS
@@ -21,3 +21,6 @@
 per-file ObservableTextView.java = file:/services/core/java/com/android/server/notification/OWNERS
 per-file RemeasuringLinearLayout.java = file:/services/core/java/com/android/server/notification/OWNERS
 per-file ViewClippingUtil.java = file:/services/core/java/com/android/server/notification/OWNERS
+
+# Appwidget related
+per-file *RemoteViews* = file:/services/appwidget/java/com/android/server/appwidget/OWNERS
diff --git a/core/java/com/android/server/SystemConfig.java b/core/java/com/android/server/SystemConfig.java
index 088c001..221c999 100644
--- a/core/java/com/android/server/SystemConfig.java
+++ b/core/java/com/android/server/SystemConfig.java
@@ -85,7 +85,7 @@
     private static final int ALLOW_APP_CONFIGS = 0x008;
     private static final int ALLOW_PRIVAPP_PERMISSIONS = 0x010;
     private static final int ALLOW_OEM_PERMISSIONS = 0x020;
-    private static final int ALLOW_HIDDENAPI_WHITELISTING = 0x040;
+    private static final int ALLOW_HIDDENAPI_ALLOWLISTING = 0x040;
     private static final int ALLOW_ASSOCIATIONS = 0x080;
     // ALLOW_OVERRIDE_APP_RESTRICTIONS allows to use "allow-in-power-save-except-idle",
     // "allow-in-power-save", "allow-in-data-usage-save","allow-unthrottled-location",
@@ -234,7 +234,7 @@
     final ArrayMap<String, PermissionEntry> mPermissions = new ArrayMap<>();
 
     // These are the packages that are white-listed to be able to run in the
-    // background while in power save mode (but not whitelisted from device idle modes),
+    // background while in power save mode (but not allowlisted from device idle modes),
     // as read from the configuration files.
     final ArraySet<String> mAllowInPowerSaveExceptIdle = new ArraySet<>();
 
@@ -258,7 +258,7 @@
     // location settings are off, for emergency purposes, as read from the configuration files.
     final ArrayMap<String, ArraySet<String>> mAllowIgnoreLocationSettings = new ArrayMap<>();
 
-    // These are the action strings of broadcasts which are whitelisted to
+    // These are the action strings of broadcasts which are allowlisted to
     // be delivered anonymously even to apps which target O+.
     final ArraySet<String> mAllowImplicitBroadcasts = new ArraySet<>();
 
@@ -281,7 +281,7 @@
     final ArrayMap<String, ArrayMap<String, Boolean>> mPackageComponentEnabledState =
             new ArrayMap<>();
 
-    // Package names that are exempted from private API blacklisting
+    // Package names that are exempted from private API denylisting
     final ArraySet<String> mHiddenApiPackageWhitelist = new ArraySet<>();
 
     // The list of carrier applications which should be disabled until used.
@@ -562,7 +562,7 @@
 
     /**
      * Gets map of packagesNames to userTypes, dictating on which user types each package should NOT
-     * be initially installed, even if they are whitelisted, and then removes this map from
+     * be initially installed, even if they are allowlisted, and then removes this map from
      * SystemConfig.
      * Called by UserManagerService when it is constructed.
      */
@@ -670,10 +670,10 @@
                 Environment.getOemDirectory(), "etc", "permissions"), oemPermissionFlag);
 
         // Allow Product to customize these configs
-        // TODO(b/157203468): ALLOW_HIDDENAPI_WHITELISTING must be removed because we prohibited
+        // TODO(b/157203468): ALLOW_HIDDENAPI_ALLOWLISTING must be removed because we prohibited
         // the use of hidden APIs from the product partition.
         int productPermissionFlag = ALLOW_FEATURES | ALLOW_LIBS | ALLOW_PERMISSIONS
-                | ALLOW_APP_CONFIGS | ALLOW_PRIVAPP_PERMISSIONS | ALLOW_HIDDENAPI_WHITELISTING
+                | ALLOW_APP_CONFIGS | ALLOW_PRIVAPP_PERMISSIONS | ALLOW_HIDDENAPI_ALLOWLISTING
                 | ALLOW_ASSOCIATIONS | ALLOW_OVERRIDE_APP_RESTRICTIONS | ALLOW_IMPLICIT_BROADCASTS
                 | ALLOW_VENDOR_APEX;
         if (Build.VERSION.DEVICE_INITIAL_SDK_INT <= Build.VERSION_CODES.R) {
@@ -797,7 +797,7 @@
             final boolean allowPrivappPermissions = (permissionFlag & ALLOW_PRIVAPP_PERMISSIONS)
                     != 0;
             final boolean allowOemPermissions = (permissionFlag & ALLOW_OEM_PERMISSIONS) != 0;
-            final boolean allowApiWhitelisting = (permissionFlag & ALLOW_HIDDENAPI_WHITELISTING)
+            final boolean allowApiWhitelisting = (permissionFlag & ALLOW_HIDDENAPI_ALLOWLISTING)
                     != 0;
             final boolean allowAssociations = (permissionFlag & ALLOW_ASSOCIATIONS) != 0;
             final boolean allowOverrideAppRestrictions =
@@ -1848,6 +1848,9 @@
                         soname, soname, new String[0], true);
                 mSharedLibraries.put(entry.name, entry);
             }
+        } catch (FileNotFoundException e) {
+            // Expected for /vendor/etc/public.libraries.txt on some devices
+            Slog.d(TAG, listFile + " does not exist");
         } catch (IOException e) {
             Slog.w(TAG, "Failed to read public libraries file " + listFile, e);
         }
diff --git a/core/java/com/android/server/net/OWNERS b/core/java/com/android/server/net/OWNERS
index 62c5737..c24680e9 100644
--- a/core/java/com/android/server/net/OWNERS
+++ b/core/java/com/android/server/net/OWNERS
@@ -1,2 +1,2 @@
 set noparent
-file:platform/packages/modules/Connectivity:master:/OWNERS_core_networking
+file:platform/packages/modules/Connectivity:main:/OWNERS_core_networking
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index 73c93ac..81c3255 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -15,7 +15,19 @@
     ],
 }
 
-cc_library_shared {
+soong_config_module_type {
+    name: "cc_library_shared_for_libandroid_runtime",
+    module_type: "cc_library_shared",
+    config_namespace: "ANDROID",
+    bool_variables: [
+        "release_binder_death_recipient_weak_from_jni",
+    ],
+    properties: [
+        "cflags",
+    ],
+}
+
+cc_library_shared_for_libandroid_runtime {
     name: "libandroid_runtime",
     host_supported: true,
     cflags: [
@@ -46,6 +58,12 @@
         },
     },
 
+    soong_config_variables: {
+        release_binder_death_recipient_weak_from_jni: {
+            cflags: ["-DBINDER_DEATH_RECIPIENT_WEAK_FROM_JNI"],
+        },
+    },
+
     cpp_std: "gnu++20",
 
     srcs: [
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 7c8ea93..2b6dc6a 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -346,7 +346,7 @@
     JNIEnv* env;
     jmethodID methodId;
 
-    ALOGD("Calling main entry %s", className.string());
+    ALOGD("Calling main entry %s", className.c_str());
 
     env = getJNIEnv();
     if (clazz == NULL || env == NULL) {
@@ -355,7 +355,7 @@
 
     methodId = env->GetStaticMethodID(clazz, "main", "([Ljava/lang/String;)V");
     if (methodId == NULL) {
-        ALOGE("ERROR: could not find method %s.main(String[])\n", className.string());
+        ALOGE("ERROR: could not find method %s.main(String[])\n", className.c_str());
         return UNKNOWN_ERROR;
     }
 
@@ -371,7 +371,7 @@
     strArray = env->NewObjectArray(numArgs, stringClass, NULL);
 
     for (size_t i = 0; i < numArgs; i++) {
-        jstring argStr = env->NewStringUTF(args[i].string());
+        jstring argStr = env->NewStringUTF(args[i].c_str());
         env->SetObjectArrayElement(strArray, i, argStr);
     }
 
@@ -1277,7 +1277,7 @@
     env->SetObjectArrayElement(strArray, 0, classNameStr);
 
     for (size_t i = 0; i < options.size(); ++i) {
-        jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
+        jstring optionsStr = env->NewStringUTF(options.itemAt(i).c_str());
         assert(optionsStr != NULL);
         env->SetObjectArrayElement(strArray, i + 1, optionsStr);
     }
diff --git a/core/jni/OWNERS b/core/jni/OWNERS
index a17048c..921a45f 100644
--- a/core/jni/OWNERS
+++ b/core/jni/OWNERS
@@ -105,3 +105,6 @@
 
 # SQLite
 per-file android_database_SQLite* = file:/SQLITE_OWNERS
+
+# PerformanceHintManager
+per-file android_os_PerformanceHintManager.cpp = file:/ADPF_OWNERS
diff --git a/core/jni/android_app_NativeActivity.cpp b/core/jni/android_app_NativeActivity.cpp
index 21369f9..d6c5593 100644
--- a/core/jni/android_app_NativeActivity.cpp
+++ b/core/jni/android_app_NativeActivity.cpp
@@ -352,7 +352,7 @@
 
     const char* dirStr = env->GetStringUTFChars(internalDataDir, NULL);
     code->internalDataPathObj = dirStr;
-    code->internalDataPath = code->internalDataPathObj.string();
+    code->internalDataPath = code->internalDataPathObj.c_str();
     env->ReleaseStringUTFChars(internalDataDir, dirStr);
 
     if (externalDataDir != NULL) {
@@ -360,7 +360,7 @@
         code->externalDataPathObj = dirStr;
         env->ReleaseStringUTFChars(externalDataDir, dirStr);
     }
-    code->externalDataPath = code->externalDataPathObj.string();
+    code->externalDataPath = code->externalDataPathObj.c_str();
 
     code->sdkVersion = sdkVersion;
 
@@ -372,7 +372,7 @@
         code->obbPathObj = dirStr;
         env->ReleaseStringUTFChars(obbDir, dirStr);
     }
-    code->obbPath = code->obbPathObj.string();
+    code->obbPath = code->obbPathObj.c_str();
 
     jbyte* rawSavedState = NULL;
     jsize rawSavedSize = 0;
diff --git a/core/jni/android_app_backup_FullBackup.cpp b/core/jni/android_app_backup_FullBackup.cpp
index 339a7d3..5e096d7 100644
--- a/core/jni/android_app_backup_FullBackup.cpp
+++ b/core/jni/android_app_backup_FullBackup.cpp
@@ -106,15 +106,14 @@
             : NULL;
 
     if (path.length() < rootpath.length()) {
-        ALOGE("file path [%s] shorter than root path [%s]",
-                path.string(), rootpath.string());
+        ALOGE("file path [%s] shorter than root path [%s]", path.c_str(), rootpath.c_str());
         return (jint) -1;
     }
 
     off64_t tarSize = 0;
     jint err = write_tarfile(packageName, domain, rootpath, path, &tarSize, writer);
     if (!err) {
-        ALOGI("measured [%s] at %lld", path.string(), (long long)tarSize);
+        ALOGI("measured [%s] at %lld", path.c_str(), (long long)tarSize);
         env->CallVoidMethod(dataOutputObj, sFullBackupDataOutput.addSize, (jlong) tarSize);
     }
 
diff --git a/core/jni/android_backup_BackupDataInput.cpp b/core/jni/android_backup_BackupDataInput.cpp
index 79fa2a2..fc081a7 100644
--- a/core/jni/android_backup_BackupDataInput.cpp
+++ b/core/jni/android_backup_BackupDataInput.cpp
@@ -76,7 +76,7 @@
             return err < 0 ? err : -1;
         }
         // TODO: Set the fields in the entity object
-        jstring keyStr = env->NewStringUTF(key.string());
+        jstring keyStr = env->NewStringUTF(key.c_str());
         env->SetObjectField(entity, s_keyField, keyStr);
         env->SetIntField(entity, s_dataSizeField, dataSize);
         return 0;
diff --git a/core/jni/android_backup_BackupHelperDispatcher.cpp b/core/jni/android_backup_BackupHelperDispatcher.cpp
index efe7d0b..efce8e1 100644
--- a/core/jni/android_backup_BackupHelperDispatcher.cpp
+++ b/core/jni/android_backup_BackupHelperDispatcher.cpp
@@ -118,7 +118,7 @@
     }
 
     env->SetIntField(headerObj, s_chunkSizeField, flattenedHeader.dataSize);
-    env->SetObjectField(headerObj, s_keyPrefixField, env->NewStringUTF(keyPrefix.string()));
+    env->SetObjectField(headerObj, s_keyPrefixField, env->NewStringUTF(keyPrefix.c_str()));
 
     return (jint) 0;
 }
diff --git a/core/jni/android_content_res_ObbScanner.cpp b/core/jni/android_content_res_ObbScanner.cpp
index de429a0..760037f 100644
--- a/core/jni/android_content_res_ObbScanner.cpp
+++ b/core/jni/android_content_res_ObbScanner.cpp
@@ -52,7 +52,7 @@
 
     env->ReleaseStringUTFChars(file, filePath);
 
-    const char* packageNameStr = obb->getPackageName().string();
+    const char* packageNameStr = obb->getPackageName().c_str();
 
     jstring packageName = env->NewStringUTF(packageNameStr);
     if (packageName == NULL) {
diff --git a/core/jni/android_database_CursorWindow.cpp b/core/jni/android_database_CursorWindow.cpp
index 2435406..c0e9215 100644
--- a/core/jni/android_database_CursorWindow.cpp
+++ b/core/jni/android_database_CursorWindow.cpp
@@ -58,13 +58,13 @@
     msg.appendFormat("Couldn't read row %d, col %d from CursorWindow.  "
             "Make sure the Cursor is initialized correctly before accessing data from it.",
             row, column);
-    jniThrowException(env, "java/lang/IllegalStateException", msg.string());
+    jniThrowException(env, "java/lang/IllegalStateException", msg.c_str());
 }
 
 static void throwUnknownTypeException(JNIEnv * env, jint type) {
     String8 msg;
     msg.appendFormat("UNKNOWN type %d", type);
-    jniThrowException(env, "java/lang/IllegalStateException", msg.string());
+    jniThrowException(env, "java/lang/IllegalStateException", msg.c_str());
 }
 
 static int getFdCount() {
@@ -89,7 +89,7 @@
     CursorWindow* window;
 
     const char* nameStr = env->GetStringUTFChars(nameObj, NULL);
-    name.setTo(nameStr);
+    name = nameStr;
     env->ReleaseStringUTFChars(nameObj, nameStr);
 
     if (cursorWindowSize < 0) {
@@ -107,7 +107,7 @@
 fail:
     jniThrowExceptionFmt(env, "android/database/CursorWindowAllocationException",
                          "Could not allocate CursorWindow '%s' of size %d due to error %d.",
-                         name.string(), cursorWindowSize, status);
+                         name.c_str(), cursorWindowSize, status);
     return 0;
 }
 
@@ -139,7 +139,7 @@
 
 static jstring nativeGetName(JNIEnv* env, jclass clazz, jlong windowPtr) {
     CursorWindow* window = reinterpret_cast<CursorWindow*>(windowPtr);
-    return env->NewStringUTF(window->name().string());
+    return env->NewStringUTF(window->name().c_str());
 }
 
 static void nativeWriteToParcel(JNIEnv * env, jclass clazz, jlong windowPtr,
@@ -151,7 +151,7 @@
     if (status) {
         String8 msg;
         msg.appendFormat("Could not write CursorWindow to Parcel due to error %d.", status);
-        jniThrowRuntimeException(env, msg.string());
+        jniThrowRuntimeException(env, msg.c_str());
     }
 }
 
@@ -267,7 +267,7 @@
         // doesn't like UTF-8 strings with high codepoints.  It actually expects
         // Modified UTF-8 with encoded surrogate pairs.
         String16 utf16(value, sizeIncludingNull - 1);
-        return env->NewString(reinterpret_cast<const jchar*>(utf16.string()), utf16.size());
+        return env->NewString(reinterpret_cast<const jchar*>(utf16.c_str()), utf16.size());
     } else if (type == CursorWindow::FIELD_TYPE_INTEGER) {
         int64_t value = window->getFieldSlotValueLong(fieldSlot);
         char buf[32];
diff --git a/core/jni/android_database_SQLiteCommon.cpp b/core/jni/android_database_SQLiteCommon.cpp
index daa2087..c6a7511 100644
--- a/core/jni/android_database_SQLiteCommon.cpp
+++ b/core/jni/android_database_SQLiteCommon.cpp
@@ -229,7 +229,7 @@
             fullMessage.append(": ");
             fullMessage.append(message);
         }
-        jniThrowException(env, exceptionClass, fullMessage.string());
+        jniThrowException(env, exceptionClass, fullMessage.c_str());
     } else {
         jniThrowException(env, exceptionClass, message);
     }
diff --git a/core/jni/android_database_SQLiteConnection.cpp b/core/jni/android_database_SQLiteConnection.cpp
index 32697ae..03d3bc6 100644
--- a/core/jni/android_database_SQLiteConnection.cpp
+++ b/core/jni/android_database_SQLiteConnection.cpp
@@ -91,15 +91,14 @@
 // Called each time a statement begins execution, when tracing is enabled.
 static void sqliteTraceCallback(void *data, const char *sql) {
     SQLiteConnection* connection = static_cast<SQLiteConnection*>(data);
-    ALOG(LOG_VERBOSE, SQLITE_TRACE_TAG, "%s: \"%s\"\n",
-            connection->label.string(), sql);
+    ALOG(LOG_VERBOSE, SQLITE_TRACE_TAG, "%s: \"%s\"\n", connection->label.c_str(), sql);
 }
 
 // Called each time a statement finishes execution, when profiling is enabled.
 static void sqliteProfileCallback(void *data, const char *sql, sqlite3_uint64 tm) {
     SQLiteConnection* connection = static_cast<SQLiteConnection*>(data);
-    ALOG(LOG_VERBOSE, SQLITE_PROFILE_TAG, "%s: \"%s\" took %0.3f ms\n",
-            connection->label.string(), sql, tm * 0.000001f);
+    ALOG(LOG_VERBOSE, SQLITE_PROFILE_TAG, "%s: \"%s\" took %0.3f ms\n", connection->label.c_str(),
+         sql, tm * 0.000001f);
 }
 
 // Called after each SQLite VM instruction when cancelation is enabled.
@@ -130,7 +129,7 @@
     env->ReleaseStringUTFChars(labelStr, labelChars);
 
     sqlite3* db;
-    int err = sqlite3_open_v2(path.string(), &db, sqliteFlags, NULL);
+    int err = sqlite3_open_v2(path.c_str(), &db, sqliteFlags, NULL);
     if (err != SQLITE_OK) {
         throw_sqlite3_exception_errcode(env, err, "Could not open database");
         return 0;
@@ -180,7 +179,7 @@
         sqlite3_profile(db, &sqliteProfileCallback, connection);
     }
 
-    ALOGV("Opened connection %p with label '%s'", db, label.string());
+    ALOGV("Opened connection %p with label '%s'", db, label.c_str());
     return reinterpret_cast<jlong>(connection);
 }
 
@@ -760,7 +759,7 @@
     if (status) {
         String8 msg;
         msg.appendFormat("Failed to clear the cursor window, status=%d", status);
-        throw_sqlite3_exception(env, connection->db, msg.string());
+        throw_sqlite3_exception(env, connection->db, msg.c_str());
         return 0;
     }
 
@@ -770,7 +769,7 @@
         String8 msg;
         msg.appendFormat("Failed to set the cursor window column count to %d, status=%d",
                 numColumns, status);
-        throw_sqlite3_exception(env, connection->db, msg.string());
+        throw_sqlite3_exception(env, connection->db, msg.c_str());
         return 0;
     }
 
@@ -845,7 +844,7 @@
         String8 msg;
         msg.appendFormat("Row too big to fit into CursorWindow requiredPos=%d, totalRows=%d",
                 requiredPos, totalRows);
-        throw_sqlite3_exception(env, SQLITE_TOOBIG, NULL, msg.string());
+        throw_sqlite3_exception(env, SQLITE_TOOBIG, NULL, msg.c_str());
         return 0;
     }
 
diff --git a/core/jni/android_ddm_DdmHandleNativeHeap.cpp b/core/jni/android_ddm_DdmHandleNativeHeap.cpp
index 2ca4500..d36d29c 100644
--- a/core/jni/android_ddm_DdmHandleNativeHeap.cpp
+++ b/core/jni/android_ddm_DdmHandleNativeHeap.cpp
@@ -100,8 +100,8 @@
     if (array != NULL) {
         env->SetByteArrayRegion(array, 0,
                                 sizeof(header), reinterpret_cast<jbyte*>(&header));
-        env->SetByteArrayRegion(array, sizeof(header),
-                                maps.size(), reinterpret_cast<const jbyte*>(maps.string()));
+        env->SetByteArrayRegion(array, sizeof(header), maps.size(),
+                                reinterpret_cast<const jbyte*>(maps.c_str()));
         env->SetByteArrayRegion(array, sizeof(header) + maps.size(),
                                 header.allocSize, reinterpret_cast<jbyte*>(leak_info.buffer));
     }
diff --git a/core/jni/android_hardware_Camera.cpp b/core/jni/android_hardware_Camera.cpp
index 2a670e8..5f3a1b5 100644
--- a/core/jni/android_hardware_Camera.cpp
+++ b/core/jni/android_hardware_Camera.cpp
@@ -17,22 +17,21 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "Camera-JNI"
-#include <utils/Log.h>
-
-#include "jni.h"
-#include <nativehelper/JNIHelp.h>
-#include "core_jni_helpers.h"
 #include <android_runtime/android_graphics_SurfaceTexture.h>
 #include <android_runtime/android_view_Surface.h>
-
+#include <binder/IMemory.h>
+#include <camera/Camera.h>
+#include <camera/StringUtils.h>
 #include <cutils/properties.h>
-#include <utils/Vector.h>
-#include <utils/Errors.h>
-
 #include <gui/GLConsumer.h>
 #include <gui/Surface.h>
-#include <camera/Camera.h>
-#include <binder/IMemory.h>
+#include <nativehelper/JNIHelp.h>
+#include <utils/Errors.h>
+#include <utils/Log.h>
+#include <utils/Vector.h>
+
+#include "core_jni_helpers.h"
+#include "jni.h"
 
 using namespace android;
 
@@ -562,7 +561,7 @@
     const char16_t *rawClientName = reinterpret_cast<const char16_t*>(
         env->GetStringChars(clientPackageName, NULL));
     jsize rawClientNameLen = env->GetStringLength(clientPackageName);
-    String16 clientName(rawClientName, rawClientNameLen);
+    std::string clientName = toStdString(rawClientName, rawClientNameLen);
     env->ReleaseStringChars(clientPackageName,
                             reinterpret_cast<const jchar*>(rawClientName));
 
@@ -875,11 +874,11 @@
     if (camera == 0) return 0;
 
     String8 params8 = camera->getParameters();
-    if (params8.isEmpty()) {
+    if (params8.empty()) {
         jniThrowRuntimeException(env, "getParameters failed (empty parameters)");
         return 0;
     }
-    return env->NewStringUTF(params8.string());
+    return env->NewStringUTF(params8.c_str());
 }
 
 static void android_hardware_Camera_reconnect(JNIEnv *env, jobject thiz)
diff --git a/core/jni/android_hardware_SensorManager.cpp b/core/jni/android_hardware_SensorManager.cpp
index cb97698..b482897 100644
--- a/core/jni/android_hardware_SensorManager.cpp
+++ b/core/jni/android_hardware_SensorManager.cpp
@@ -150,7 +150,7 @@
         return gStringOffsets.emptyString;
     }
 
-    ScopedLocalRef<jstring> javaString(env, env->NewStringUTF(string.string()));
+    ScopedLocalRef<jstring> javaString(env, env->NewStringUTF(string.c_str()));
     jstring internedString = (jstring)
             env->CallObjectMethod(javaString.get(), gStringOffsets.intern);
     return internedString;
diff --git a/core/jni/android_hardware_camera2_CameraMetadata.cpp b/core/jni/android_hardware_camera2_CameraMetadata.cpp
index 5293c58..041fed7 100644
--- a/core/jni/android_hardware_camera2_CameraMetadata.cpp
+++ b/core/jni/android_hardware_camera2_CameraMetadata.cpp
@@ -514,7 +514,7 @@
         ssize_t res;
         while ((res = TEMP_FAILURE_RETRY(read(readFd, &out[0], /*count*/1))) > 0) {
             if (out[0] == '\n') {
-                ALOGD("%s", logLine.string());
+                ALOGD("%s", logLine.c_str());
                 logLine.clear();
             } else {
                 logLine.append(out);
@@ -526,8 +526,8 @@
                     "Failed to read from fd (errno = %#x, message = '%s')",
                     errno, strerror(errno));
             //return;
-        } else if (!logLine.isEmpty()) {
-            ALOGD("%s", logLine.string());
+        } else if (!logLine.empty()) {
+            ALOGD("%s", logLine.c_str());
         }
 
         close(readFd);
@@ -956,8 +956,8 @@
         return OK;
     } else if (!res.isOk()) {
         VendorTagDescriptor::clearGlobalVendorTagDescriptor();
-        ALOGE("%s: Failed to setup vendor tag descriptors: %s",
-                __FUNCTION__, res.toString8().string());
+        ALOGE("%s: Failed to setup vendor tag descriptors: %s", __FUNCTION__,
+              res.toString8().c_str());
         return res.serviceSpecificErrorCode();
     }
     if (0 < desc->getTagCount()) {
@@ -971,8 +971,8 @@
             return OK;
         } else if (!res.isOk()) {
             VendorTagDescriptorCache::clearGlobalVendorTagCache();
-            ALOGE("%s: Failed to setup vendor tag cache: %s",
-                    __FUNCTION__, res.toString8().string());
+            ALOGE("%s: Failed to setup vendor tag cache: %s", __FUNCTION__,
+                  res.toString8().c_str());
             return res.serviceSpecificErrorCode();
         }
 
diff --git a/core/jni/android_hardware_camera2_DngCreator.cpp b/core/jni/android_hardware_camera2_DngCreator.cpp
index c947fba..30e546c 100644
--- a/core/jni/android_hardware_camera2_DngCreator.cpp
+++ b/core/jni/android_hardware_camera2_DngCreator.cpp
@@ -1543,7 +1543,8 @@
         String8 captureTime = nativeContext->getCaptureTime();
 
         if (writer->addEntry(TAG_DATETIME, NativeContext::DATETIME_COUNT,
-                reinterpret_cast<const uint8_t*>(captureTime.string()), TIFF_IFD_0) != OK) {
+                             reinterpret_cast<const uint8_t*>(captureTime.c_str()),
+                             TIFF_IFD_0) != OK) {
             jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
                     "Invalid metadata for tag %x", TAG_DATETIME);
             return nullptr;
@@ -1551,7 +1552,8 @@
 
         // datetime original
         if (writer->addEntry(TAG_DATETIMEORIGINAL, NativeContext::DATETIME_COUNT,
-                reinterpret_cast<const uint8_t*>(captureTime.string()), TIFF_IFD_0) != OK) {
+                             reinterpret_cast<const uint8_t*>(captureTime.c_str()),
+                             TIFF_IFD_0) != OK) {
             jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
                     "Invalid metadata for tag %x", TAG_DATETIMEORIGINAL);
             return nullptr;
@@ -1879,8 +1881,10 @@
         cameraModel += brand.c_str();
 
         BAIL_IF_INVALID_RET_NULL_SP(writer->addEntry(TAG_UNIQUECAMERAMODEL, cameraModel.size() + 1,
-                reinterpret_cast<const uint8_t*>(cameraModel.string()), TIFF_IFD_0), env,
-                TAG_UNIQUECAMERAMODEL, writer);
+                                                     reinterpret_cast<const uint8_t*>(
+                                                             cameraModel.c_str()),
+                                                     TIFF_IFD_0),
+                                    env, TAG_UNIQUECAMERAMODEL, writer);
     }
 
     {
@@ -2165,7 +2169,8 @@
         String8 description = nativeContext->getDescription();
         size_t len = description.bytes() + 1;
         if (writer->addEntry(TAG_IMAGEDESCRIPTION, len,
-                reinterpret_cast<const uint8_t*>(description.string()), TIFF_IFD_0) != OK) {
+                             reinterpret_cast<const uint8_t*>(description.c_str()),
+                             TIFF_IFD_0) != OK) {
             jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
                     "Invalid metadata for tag %x", TAG_IMAGEDESCRIPTION);
         }
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index 56c2a864..2af9a38 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -29,6 +29,8 @@
 #include <media/AudioSystem.h>
 #include <nativehelper/JNIHelp.h>
 #include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedPrimitiveArray.h>
+#include <nativehelper/jni_macros.h>
 #include <system/audio.h>
 #include <system/audio_policy.h>
 #include <utils/Log.h>
@@ -265,7 +267,7 @@
         ALOGE("Can't find class %s", kEventHandlerClassPathName);
         return;
     }
-    mClass = (jclass)env->NewGlobalRef(clazz);
+    mClass = static_cast<jclass>(env->NewGlobalRef(clazz));
 
     // We use a weak reference so the AudioPortEventHandler object can be garbage collected.
     // The reference is only used as a proxy for callbacks.
@@ -317,15 +319,16 @@
                                        const sp<JNIAudioPortCallback>& callback)
 {
     Mutex::Autolock l(gLock);
-    sp<JNIAudioPortCallback> old =
-            (JNIAudioPortCallback*)env->GetLongField(thiz, gEventHandlerFields.mJniCallback);
+    sp<JNIAudioPortCallback> old = reinterpret_cast<JNIAudioPortCallback *>(
+            env->GetLongField(thiz, gEventHandlerFields.mJniCallback));
     if (callback.get()) {
-        callback->incStrong((void*)setJniCallback);
+        callback->incStrong(reinterpret_cast<void *>(setJniCallback));
     }
     if (old != 0) {
-        old->decStrong((void*)setJniCallback);
+        old->decStrong(reinterpret_cast<void *>(setJniCallback));
     }
-    env->SetLongField(thiz, gEventHandlerFields.mJniCallback, (jlong)callback.get());
+    env->SetLongField(thiz, gEventHandlerFields.mJniCallback,
+                      reinterpret_cast<jlong>(callback.get()));
     return old;
 }
 
@@ -354,43 +357,44 @@
                                            jobjectArray deviceAddresses,
                                            AudioDeviceTypeAddrVector &audioDeviceTypeAddrVector) {
     if (deviceTypes == nullptr || deviceAddresses == nullptr) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+    return AUDIO_JAVA_BAD_VALUE;
     }
     jsize deviceCount = env->GetArrayLength(deviceTypes);
     if (deviceCount == 0 || deviceCount != env->GetArrayLength(deviceAddresses)) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+    return AUDIO_JAVA_BAD_VALUE;
     }
     // retrieve all device types
     std::vector<audio_devices_t> deviceTypesVector;
     jint *typesPtr = nullptr;
     typesPtr = env->GetIntArrayElements(deviceTypes, 0);
     if (typesPtr == nullptr) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+    return AUDIO_JAVA_BAD_VALUE;
     }
     for (jint i = 0; i < deviceCount; i++) {
-        deviceTypesVector.push_back((audio_devices_t)typesPtr[i]);
+    deviceTypesVector.push_back(static_cast<audio_devices_t>(typesPtr[i]));
     }
     // check each address is a string and add device type/address to list
     jclass stringClass = FindClassOrDie(env, "java/lang/String");
     for (jint i = 0; i < deviceCount; i++) {
         jobject addrJobj = env->GetObjectArrayElement(deviceAddresses, i);
         if (!env->IsInstanceOf(addrJobj, stringClass)) {
-            return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
         }
-        const char *address = env->GetStringUTFChars((jstring)addrJobj, NULL);
-        AudioDeviceTypeAddr dev = AudioDeviceTypeAddr((audio_devices_t)typesPtr[i], address);
+        const char *address = env->GetStringUTFChars(static_cast<jstring>(addrJobj), NULL);
+        AudioDeviceTypeAddr dev =
+                AudioDeviceTypeAddr(static_cast<audio_devices_t>(typesPtr[i]), address);
         audioDeviceTypeAddrVector.push_back(dev);
-        env->ReleaseStringUTFChars((jstring)addrJobj, address);
+        env->ReleaseStringUTFChars(static_cast<jstring>(addrJobj), address);
     }
     env->ReleaseIntArrayElements(deviceTypes, typesPtr, 0);
 
-    return (jint)NO_ERROR;
+    return NO_ERROR;
 }
 
 static jint
 android_media_AudioSystem_muteMicrophone(JNIEnv *env, jobject thiz, jboolean on)
 {
-    return (jint) check_AudioSystem_Command(AudioSystem::muteMicrophone(on));
+    return check_AudioSystem_Command(AudioSystem::muteMicrophone(on));
 }
 
 static jboolean
@@ -405,7 +409,7 @@
 android_media_AudioSystem_isStreamActive(JNIEnv *env, jobject thiz, jint stream, jint inPastMs)
 {
     bool state = false;
-    AudioSystem::isStreamActive((audio_stream_type_t) stream, &state, inPastMs);
+    AudioSystem::isStreamActive(static_cast<audio_stream_type_t>(stream), &state, inPastMs);
     return state;
 }
 
@@ -414,7 +418,7 @@
         jint inPastMs)
 {
     bool state = false;
-    AudioSystem::isStreamActiveRemotely((audio_stream_type_t) stream, &state, inPastMs);
+    AudioSystem::isStreamActiveRemotely(static_cast<audio_stream_type_t>(stream), &state, inPastMs);
     return state;
 }
 
@@ -422,7 +426,7 @@
 android_media_AudioSystem_isSourceActive(JNIEnv *env, jobject thiz, jint source)
 {
     bool state = false;
-    AudioSystem::isSourceActive((audio_source_t) source, &state);
+    AudioSystem::isSourceActive(static_cast<audio_source_t>(source), &state);
     return state;
 }
 
@@ -457,8 +461,7 @@
             env->GetStringLength(keyValuePairs));
         env->ReleaseStringCritical(keyValuePairs, c_keyValuePairs);
     }
-    int status = check_AudioSystem_Command(AudioSystem::setParameters(c_keyValuePairs8));
-    return (jint) status;
+    return check_AudioSystem_Command(AudioSystem::setParameters(c_keyValuePairs8));
 }
 
 static jstring
@@ -471,7 +474,7 @@
                           env->GetStringLength(keys));
         env->ReleaseStringCritical(keys, c_keys);
     }
-    return env->NewStringUTF(AudioSystem::getParameters(c_keys8).string());
+    return env->NewStringUTF(AudioSystem::getParameters(c_keys8).c_str());
 }
 
 static void
@@ -500,7 +503,7 @@
     }
 
     jclass clazz = env->FindClass(kClassPathName);
-    const char* zechars = regId.string();
+    const char *zechars = regId.c_str();
     jstring zestring = env->NewStringUTF(zechars);
 
     env->CallStaticVoidMethod(clazz, gAudioPolicyEventHandlerMethods.postDynPolicyEventFromNative,
@@ -538,15 +541,15 @@
         return;
     }
     jint recParamData[REC_PARAM_SIZE];
-    recParamData[0] = (jint) audioFormatFromNative(clientConfig->format);
+    recParamData[0] = audioFormatFromNative(clientConfig->format);
     // FIXME this doesn't support index-based masks
-    recParamData[1] = (jint) inChannelMaskFromNative(clientConfig->channel_mask);
-    recParamData[2] = (jint) clientConfig->sample_rate;
-    recParamData[3] = (jint) audioFormatFromNative(deviceConfig->format);
+    recParamData[1] = inChannelMaskFromNative(clientConfig->channel_mask);
+    recParamData[2] = clientConfig->sample_rate;
+    recParamData[3] = audioFormatFromNative(deviceConfig->format);
     // FIXME this doesn't support index-based masks
-    recParamData[4] = (jint) inChannelMaskFromNative(deviceConfig->channel_mask);
-    recParamData[5] = (jint) deviceConfig->sample_rate;
-    recParamData[6] = (jint) patchHandle;
+    recParamData[4] = inChannelMaskFromNative(deviceConfig->channel_mask);
+    recParamData[5] = deviceConfig->sample_rate;
+    recParamData[6] = patchHandle;
     env->SetIntArrayRegion(recParamArray, 0, REC_PARAM_SIZE, recParamData);
 
     jobjectArray jClientEffects;
@@ -560,10 +563,9 @@
 
     env->CallStaticVoidMethod(clazz,
                               gAudioPolicyEventHandlerMethods.postRecordConfigEventFromNative,
-                              event, (jint) clientInfo->riid, (jint) clientInfo->uid,
-                              clientInfo->session, clientInfo->source, clientInfo->port_id,
-                              clientInfo->silenced, recParamArray, jClientEffects, jEffects,
-                              source);
+                              event, clientInfo->riid, clientInfo->uid, clientInfo->session,
+                              clientInfo->source, clientInfo->port_id, clientInfo->silenced,
+                              recParamArray, jClientEffects, jEffects, source);
     env->DeleteLocalRef(clazz);
     env->DeleteLocalRef(recParamArray);
     env->DeleteLocalRef(jClientEffects);
@@ -606,11 +608,9 @@
     if (Parcel *parcel = parcelForJavaObject(env, jParcel); parcel != nullptr) {
         android::media::audio::common::AudioPort port{};
         if (status_t statusOfParcel = port.readFromParcel(parcel); statusOfParcel == OK) {
-            status = check_AudioSystem_Command(
-                    AudioSystem::setDeviceConnectionState(static_cast<audio_policy_dev_state_t>(
-                                                                  state),
-                                                          port,
-                                                          static_cast<audio_format_t>(codec)));
+        status = check_AudioSystem_Command(
+                AudioSystem::setDeviceConnectionState(static_cast<audio_policy_dev_state_t>(state),
+                                                      port, static_cast<audio_format_t>(codec)));
         } else {
             ALOGE("Failed to read from parcel: %s", statusToString(statusOfParcel).c_str());
             status = kAudioStatusError;
@@ -619,17 +619,17 @@
         ALOGE("Failed to retrieve the native parcel from Java parcel");
         status = kAudioStatusError;
     }
-    return (jint) status;
+    return status;
 }
 
 static jint
 android_media_AudioSystem_getDeviceConnectionState(JNIEnv *env, jobject thiz, jint device, jstring device_address)
 {
     const char *c_address = env->GetStringUTFChars(device_address, NULL);
-    int state = static_cast <int>(AudioSystem::getDeviceConnectionState(static_cast <audio_devices_t>(device),
-                                          c_address));
+    int state = static_cast<int>(
+            AudioSystem::getDeviceConnectionState(static_cast<audio_devices_t>(device), c_address));
     env->ReleaseStringUTFChars(device_address, c_address);
-    return (jint) state;
+    return state;
 }
 
 static jint
@@ -638,38 +638,41 @@
 {
     const char *c_address = env->GetStringUTFChars(device_address, NULL);
     const char *c_name = env->GetStringUTFChars(device_name, NULL);
-    int status = check_AudioSystem_Command(AudioSystem::handleDeviceConfigChange(static_cast <audio_devices_t>(device),
-                                          c_address, c_name, static_cast <audio_format_t>(codec)));
+    int status = check_AudioSystem_Command(
+            AudioSystem::handleDeviceConfigChange(static_cast<audio_devices_t>(device), c_address,
+                                                  c_name, static_cast<audio_format_t>(codec)));
     env->ReleaseStringUTFChars(device_address, c_address);
     env->ReleaseStringUTFChars(device_name, c_name);
-    return (jint) status;
+    return status;
 }
 
 static jint android_media_AudioSystem_setPhoneState(JNIEnv *env, jobject thiz, jint state,
                                                     jint uid) {
-    return (jint)check_AudioSystem_Command(
-            AudioSystem::setPhoneState((audio_mode_t)state, (uid_t)uid));
+    return check_AudioSystem_Command(
+            AudioSystem::setPhoneState(static_cast<audio_mode_t>(state), static_cast<uid_t>(uid)));
 }
 
 static jint
 android_media_AudioSystem_setForceUse(JNIEnv *env, jobject thiz, jint usage, jint config)
 {
-    return (jint) check_AudioSystem_Command(AudioSystem::setForceUse(static_cast <audio_policy_force_use_t>(usage),
-                                                           static_cast <audio_policy_forced_cfg_t>(config)));
+    return check_AudioSystem_Command(
+            AudioSystem::setForceUse(static_cast<audio_policy_force_use_t>(usage),
+                                     static_cast<audio_policy_forced_cfg_t>(config)));
 }
 
 static jint
 android_media_AudioSystem_getForceUse(JNIEnv *env, jobject thiz, jint usage)
 {
-    return static_cast <jint>(AudioSystem::getForceUse(static_cast <audio_policy_force_use_t>(usage)));
+    return static_cast<jint>(
+            AudioSystem::getForceUse(static_cast<audio_policy_force_use_t>(usage)));
 }
 
 static jint
 android_media_AudioSystem_initStreamVolume(JNIEnv *env, jobject thiz, jint stream, jint indexMin, jint indexMax)
 {
-    return (jint) check_AudioSystem_Command(AudioSystem::initStreamVolume(static_cast <audio_stream_type_t>(stream),
-                                                                   indexMin,
-                                                                   indexMax));
+    return check_AudioSystem_Command(
+            AudioSystem::initStreamVolume(static_cast<audio_stream_type_t>(stream), indexMin,
+                                          indexMax));
 }
 
 static jint
@@ -679,10 +682,9 @@
                                                jint index,
                                                jint device)
 {
-    return (jint) check_AudioSystem_Command(
-            AudioSystem::setStreamVolumeIndex(static_cast <audio_stream_type_t>(stream),
-                                              index,
-                                              (audio_devices_t)device));
+    return check_AudioSystem_Command(
+            AudioSystem::setStreamVolumeIndex(static_cast<audio_stream_type_t>(stream), index,
+                                              static_cast<audio_devices_t>(device)));
 }
 
 static jint
@@ -692,13 +694,11 @@
                                                jint device)
 {
     int index;
-    if (AudioSystem::getStreamVolumeIndex(static_cast <audio_stream_type_t>(stream),
-                                          &index,
-                                          (audio_devices_t)device)
-            != NO_ERROR) {
+    if (AudioSystem::getStreamVolumeIndex(static_cast<audio_stream_type_t>(stream), &index,
+                                          static_cast<audio_devices_t>(device)) != NO_ERROR) {
         index = -1;
     }
-    return (jint) index;
+    return index;
 }
 
 static jint
@@ -711,11 +711,12 @@
     // read the AudioAttributes values
     JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
     jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
-    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+    if (jStatus != AUDIO_JAVA_SUCCESS) {
         return jStatus;
     }
-    return (jint) check_AudioSystem_Command(
-            AudioSystem::setVolumeIndexForAttributes(*(paa.get()), index, (audio_devices_t)device));
+    return check_AudioSystem_Command(
+            AudioSystem::setVolumeIndexForAttributes(*(paa.get()), index,
+                                                     static_cast<audio_devices_t>(device)));
 }
 
 static jint
@@ -727,15 +728,16 @@
     // read the AudioAttributes values
     JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
     jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
-    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+    if (jStatus != AUDIO_JAVA_SUCCESS) {
         return jStatus;
     }
     int index;
-    if (AudioSystem::getVolumeIndexForAttributes(*(paa.get()), index, (audio_devices_t)device)
-            != NO_ERROR) {
+    if (AudioSystem::getVolumeIndexForAttributes(*(paa.get()), index,
+                                                 static_cast<audio_devices_t>(device)) !=
+        NO_ERROR) {
         index = -1;
     }
-    return (jint) index;
+    return index;
 }
 
 static jint
@@ -746,7 +748,7 @@
     // read the AudioAttributes values
     JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
     jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
-    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+    if (jStatus != AUDIO_JAVA_SUCCESS) {
         return jStatus;
     }
     int index;
@@ -754,7 +756,7 @@
             != NO_ERROR) {
         index = -1;
     }
-    return (jint) index;
+    return index;
 }
 
 static jint
@@ -765,7 +767,7 @@
     // read the AudioAttributes values
     JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
     jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
-    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+    if (jStatus != AUDIO_JAVA_SUCCESS) {
         return jStatus;
     }
     int index;
@@ -773,13 +775,13 @@
             != NO_ERROR) {
         index = -1;
     }
-    return (jint) index;
+    return index;
 }
 
 static jint
 android_media_AudioSystem_setMasterVolume(JNIEnv *env, jobject thiz, jfloat value)
 {
-    return (jint) check_AudioSystem_Command(AudioSystem::setMasterVolume(value));
+    return check_AudioSystem_Command(AudioSystem::setMasterVolume(value));
 }
 
 static jfloat
@@ -795,7 +797,7 @@
 static jint
 android_media_AudioSystem_setMasterMute(JNIEnv *env, jobject thiz, jboolean mute)
 {
-    return (jint) check_AudioSystem_Command(AudioSystem::setMasterMute(mute));
+    return check_AudioSystem_Command(AudioSystem::setMasterMute(mute));
 }
 
 static jboolean
@@ -811,7 +813,7 @@
 static jint
 android_media_AudioSystem_setMasterMono(JNIEnv *env, jobject thiz, jboolean mono)
 {
-    return (jint) check_AudioSystem_Command(AudioSystem::setMasterMono(mono));
+    return check_AudioSystem_Command(AudioSystem::setMasterMono(mono));
 }
 
 static jboolean
@@ -827,7 +829,7 @@
 static jint
 android_media_AudioSystem_setMasterBalance(JNIEnv *env, jobject thiz, jfloat balance)
 {
-    return (jint) check_AudioSystem_Command(AudioSystem::setMasterBalance(balance));
+    return check_AudioSystem_Command(AudioSystem::setMasterBalance(balance));
 }
 
 static jfloat
@@ -845,37 +847,37 @@
 static jint
 android_media_AudioSystem_getPrimaryOutputSamplingRate(JNIEnv *env, jobject clazz)
 {
-    return (jint) AudioSystem::getPrimaryOutputSamplingRate();
+    return AudioSystem::getPrimaryOutputSamplingRate();
 }
 
 static jint
 android_media_AudioSystem_getPrimaryOutputFrameCount(JNIEnv *env, jobject clazz)
 {
-    return (jint) AudioSystem::getPrimaryOutputFrameCount();
+    return AudioSystem::getPrimaryOutputFrameCount();
 }
 
 static jint
 android_media_AudioSystem_getOutputLatency(JNIEnv *env, jobject clazz, jint stream)
 {
     uint32_t afLatency;
-    if (AudioSystem::getOutputLatency(&afLatency, static_cast <audio_stream_type_t>(stream))
-            != NO_ERROR) {
+    if (AudioSystem::getOutputLatency(&afLatency, static_cast<audio_stream_type_t>(stream)) !=
+        NO_ERROR) {
         afLatency = -1;
     }
-    return (jint) afLatency;
+    return afLatency;
 }
 
 static jint
 android_media_AudioSystem_setLowRamDevice(
         JNIEnv *env, jobject clazz, jboolean isLowRamDevice, jlong totalMemory)
 {
-    return (jint) AudioSystem::setLowRamDevice((bool) isLowRamDevice, (int64_t) totalMemory);
+    return AudioSystem::setLowRamDevice(isLowRamDevice, totalMemory);
 }
 
 static jint
 android_media_AudioSystem_checkAudioFlinger(JNIEnv *env, jobject clazz)
 {
-    return (jint) check_AudioSystem_Command(AudioSystem::checkAudioFlinger());
+    return check_AudioSystem_Command(AudioSystem::checkAudioFlinger());
 }
 
 static void android_media_AudioSystem_setAudioFlingerBinder(JNIEnv *env, jobject clazz,
@@ -889,8 +891,8 @@
                                                bool useInMask)
 {
     nAudioGainConfig->index = env->GetIntField(jAudioGainConfig, gAudioGainConfigFields.mIndex);
-    nAudioGainConfig->mode =
-            (audio_gain_mode_t)env->GetIntField(jAudioGainConfig, gAudioGainConfigFields.mMode);
+    nAudioGainConfig->mode = static_cast<audio_gain_mode_t>(
+            env->GetIntField(jAudioGainConfig, gAudioGainConfigFields.mMode));
     ALOGV("convertAudioGainConfigToNative got gain index %d", nAudioGainConfig->index);
     jint jMask = env->GetIntField(jAudioGainConfig, gAudioGainConfigFields.mChannelMask);
     audio_channel_mask_t nMask;
@@ -904,8 +906,8 @@
     nAudioGainConfig->channel_mask = nMask;
     nAudioGainConfig->ramp_duration_ms = env->GetIntField(jAudioGainConfig,
                                                        gAudioGainConfigFields.mRampDurationMs);
-    jintArray jValues = (jintArray)env->GetObjectField(jAudioGainConfig,
-                                                       gAudioGainConfigFields.mValues);
+    jintArray jValues = static_cast<jintArray>(
+            env->GetObjectField(jAudioGainConfig, gAudioGainConfigFields.mValues));
     int *nValues = env->GetIntArrayElements(jValues, NULL);
     size_t size = env->GetArrayLength(jValues);
     memcpy(nAudioGainConfig->values, nValues, size * sizeof(int));
@@ -920,8 +922,8 @@
     jobject jAudioPort = env->GetObjectField(jAudioPortConfig, gAudioPortConfigFields.mPort);
     jobject jHandle = env->GetObjectField(jAudioPort, gAudioPortFields.mHandle);
     nAudioPortConfig->id = env->GetIntField(jHandle, gAudioHandleFields.mId);
-    nAudioPortConfig->role = (audio_port_role_t)env->GetIntField(jAudioPort,
-                                                                 gAudioPortFields.mRole);
+    nAudioPortConfig->role =
+            static_cast<audio_port_role_t>(env->GetIntField(jAudioPort, gAudioPortFields.mRole));
     if (env->IsInstanceOf(jAudioPort, gAudioDevicePortClass)) {
         nAudioPortConfig->type = AUDIO_PORT_TYPE_DEVICE;
     } else if (env->IsInstanceOf(jAudioPort, gAudioMixPortClass)) {
@@ -929,7 +931,7 @@
     } else {
         env->DeleteLocalRef(jAudioPort);
         env->DeleteLocalRef(jHandle);
-        return (jint)AUDIO_JAVA_ERROR;
+        return AUDIO_JAVA_ERROR;
     }
     ALOGV("convertAudioPortConfigToNative handle %d role %d type %d",
           nAudioPortConfig->id, nAudioPortConfig->role, nAudioPortConfig->type);
@@ -984,7 +986,7 @@
     }
     env->DeleteLocalRef(jAudioPort);
     env->DeleteLocalRef(jHandle);
-    return (jint)AUDIO_JAVA_SUCCESS;
+    return AUDIO_JAVA_SUCCESS;
 }
 
 /**
@@ -1005,15 +1007,15 @@
     }
     // Supports AUDIO_PORT_TYPE_DEVICE only
     if (nAudioPortConfig->type != AUDIO_PORT_TYPE_DEVICE) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     jobject jAudioDevicePort = env->GetObjectField(jAudioPortConfig,
             gAudioPortConfigFields.mPort);
-    nAudioPortConfig->ext.device.type =
-            (audio_devices_t)env->GetIntField(jAudioDevicePort, gAudioPortFields.mType);
-    jstring jDeviceAddress = (jstring)env->GetObjectField(jAudioDevicePort,
-            gAudioPortFields.mAddress);
+    nAudioPortConfig->ext.device.type = static_cast<audio_devices_t>(
+            env->GetIntField(jAudioDevicePort, gAudioPortFields.mType));
+    jstring jDeviceAddress =
+            static_cast<jstring>(env->GetObjectField(jAudioDevicePort, gAudioPortFields.mAddress));
     const char *nDeviceAddress = env->GetStringUTFChars(jDeviceAddress, NULL);
     strncpy(nAudioPortConfig->ext.device.address,
             nDeviceAddress, AUDIO_DEVICE_MAX_ADDRESS_LEN - 1);
@@ -1023,45 +1025,41 @@
     return jStatus;
 }
 
-static jint convertAudioPortConfigFromNative(JNIEnv *env,
-                                                 jobject jAudioPort,
-                                                 jobject *jAudioPortConfig,
-                                                 const struct audio_port_config *nAudioPortConfig)
-{
-    jint jStatus = AUDIO_JAVA_SUCCESS;
-    jobject jAudioGainConfig = NULL;
-    jobject jAudioGain = NULL;
+static jint convertAudioPortConfigFromNative(JNIEnv *env, ScopedLocalRef<jobject> *jAudioPort,
+                                             ScopedLocalRef<jobject> *jAudioPortConfig,
+                                             const struct audio_port_config *nAudioPortConfig) {
     jintArray jGainValues;
     bool audioportCreated = false;
 
     ALOGV("convertAudioPortConfigFromNative jAudioPort %p", jAudioPort);
 
-    if (jAudioPort == NULL) {
-        jobject jHandle = env->NewObject(gAudioHandleClass, gAudioHandleCstor,
-                                                 nAudioPortConfig->id);
+    if (*jAudioPort == nullptr) {
+        ScopedLocalRef<jobject> jHandle(env,
+                                        env->NewObject(gAudioHandleClass, gAudioHandleCstor,
+                                                       nAudioPortConfig->id));
 
         ALOGV("convertAudioPortConfigFromNative handle %d is a %s", nAudioPortConfig->id,
               nAudioPortConfig->type == AUDIO_PORT_TYPE_DEVICE ? "device" : "mix");
 
         if (jHandle == NULL) {
-            return (jint)AUDIO_JAVA_ERROR;
+            return AUDIO_JAVA_ERROR;
         }
         // create placeholder port and port config objects with just the correct handle
         // and configuration data. The actual AudioPortConfig objects will be
         // constructed by java code with correct class type (device, mix etc...)
         // and reference to AudioPort instance in this client
-        jAudioPort = env->NewObject(gAudioPortClass, gAudioPortCstor,
-                                           jHandle, // handle
-                                           0,       // role
-                                           NULL,    // name
-                                           NULL,    // samplingRates
-                                           NULL,    // channelMasks
-                                           NULL,    // channelIndexMasks
-                                           NULL,    // formats
-                                           NULL);   // gains
-        env->DeleteLocalRef(jHandle);
-        if (jAudioPort == NULL) {
-            return (jint)AUDIO_JAVA_ERROR;
+        jAudioPort->reset(env->NewObject(gAudioPortClass, gAudioPortCstor,
+                                         jHandle.get(), // handle
+                                         0,             // role
+                                         nullptr,       // name
+                                         nullptr,       // samplingRates
+                                         nullptr,       // channelMasks
+                                         nullptr,       // channelIndexMasks
+                                         nullptr,       // formats
+                                         nullptr));     // gains
+
+        if (*jAudioPort == nullptr) {
+            return AUDIO_JAVA_ERROR;
         }
         ALOGV("convertAudioPortConfigFromNative jAudioPort created for handle %d",
               nAudioPortConfig->id);
@@ -1069,6 +1067,9 @@
         audioportCreated = true;
     }
 
+    ScopedLocalRef<jobject> jAudioGainConfig(env, nullptr);
+    ScopedLocalRef<jobject> jAudioGain(env, nullptr);
+
     bool useInMask = audio_port_config_has_input_direction(nAudioPortConfig);
 
     audio_channel_mask_t nMask;
@@ -1082,36 +1083,28 @@
               gainIndex, nAudioPortConfig->gain.mode);
         if (audioportCreated) {
             ALOGV("convertAudioPortConfigFromNative creating gain");
-            jAudioGain = env->NewObject(gAudioGainClass, gAudioGainCstor,
-                                               gainIndex,
-                                               0,
-                                               0,
-                                               0,
-                                               0,
-                                               0,
-                                               0,
-                                               0,
-                                               0);
+            jAudioGain.reset(env->NewObject(gAudioGainClass, gAudioGainCstor, gainIndex, 0 /*mode*/,
+                                            0 /*channelMask*/, 0 /*minValue*/, 0 /*maxValue*/,
+                                            0 /*defaultValue*/, 0 /*stepValue*/,
+                                            0 /*rampDurationMinMs*/, 0 /*rampDurationMaxMs*/));
             if (jAudioGain == NULL) {
                 ALOGV("convertAudioPortConfigFromNative creating gain FAILED");
-                jStatus = (jint)AUDIO_JAVA_ERROR;
-                goto exit;
+                return AUDIO_JAVA_ERROR;
             }
         } else {
             ALOGV("convertAudioPortConfigFromNative reading gain from port");
-            jobjectArray jGains = (jobjectArray)env->GetObjectField(jAudioPort,
-                                                                      gAudioPortFields.mGains);
+            ScopedLocalRef<jobjectArray>
+                    jGains(env,
+                           static_cast<jobjectArray>(env->GetObjectField(jAudioPort->get(),
+                                                                         gAudioPortFields.mGains)));
             if (jGains == NULL) {
                 ALOGV("convertAudioPortConfigFromNative could not get gains from port");
-                jStatus = (jint)AUDIO_JAVA_ERROR;
-                goto exit;
+                return AUDIO_JAVA_ERROR;
             }
-            jAudioGain = env->GetObjectArrayElement(jGains, gainIndex);
-            env->DeleteLocalRef(jGains);
+            jAudioGain.reset(env->GetObjectArrayElement(jGains.get(), gainIndex));
             if (jAudioGain == NULL) {
                 ALOGV("convertAudioPortConfigFromNative could not get gain at index %d", gainIndex);
-                jStatus = (jint)AUDIO_JAVA_ERROR;
-                goto exit;
+                return AUDIO_JAVA_ERROR;
             }
         }
         int numValues;
@@ -1123,8 +1116,7 @@
         jGainValues = env->NewIntArray(numValues);
         if (jGainValues == NULL) {
             ALOGV("convertAudioPortConfigFromNative could not create gain values %d", numValues);
-            jStatus = (jint)AUDIO_JAVA_ERROR;
-            goto exit;
+            return AUDIO_JAVA_ERROR;
         }
         env->SetIntArrayRegion(jGainValues, 0, numValues,
                                nAudioPortConfig->gain.values);
@@ -1138,19 +1130,14 @@
             ALOGV("convertAudioPortConfigFromNative OUT mask java %x native %x", jMask, nMask);
         }
 
-        jAudioGainConfig = env->NewObject(gAudioGainConfigClass,
-                                        gAudioGainConfigCstor,
-                                        gainIndex,
-                                        jAudioGain,
-                                        nAudioPortConfig->gain.mode,
-                                        jMask,
-                                        jGainValues,
-                                        nAudioPortConfig->gain.ramp_duration_ms);
+        jAudioGainConfig.reset(env->NewObject(gAudioGainConfigClass, gAudioGainConfigCstor,
+                                              gainIndex, jAudioGain.get(),
+                                              nAudioPortConfig->gain.mode, jMask, jGainValues,
+                                              nAudioPortConfig->gain.ramp_duration_ms));
         env->DeleteLocalRef(jGainValues);
         if (jAudioGainConfig == NULL) {
             ALOGV("convertAudioPortConfigFromNative could not create gain config");
-            jStatus = (jint)AUDIO_JAVA_ERROR;
-            goto exit;
+            return AUDIO_JAVA_ERROR;
         }
     }
     jclass clazz;
@@ -1160,17 +1147,16 @@
         methodID = gAudioPortConfigCstor;
         ALOGV("convertAudioPortConfigFromNative building a generic port config");
     } else {
-        if (env->IsInstanceOf(jAudioPort, gAudioDevicePortClass)) {
+        if (env->IsInstanceOf(jAudioPort->get(), gAudioDevicePortClass)) {
             clazz = gAudioDevicePortConfigClass;
             methodID = gAudioDevicePortConfigCstor;
             ALOGV("convertAudioPortConfigFromNative building a device config");
-        } else if (env->IsInstanceOf(jAudioPort, gAudioMixPortClass)) {
+        } else if (env->IsInstanceOf(jAudioPort->get(), gAudioMixPortClass)) {
             clazz = gAudioMixPortConfigClass;
             methodID = gAudioMixPortConfigCstor;
             ALOGV("convertAudioPortConfigFromNative building a mix config");
         } else {
-            jStatus = (jint)AUDIO_JAVA_ERROR;
-            goto exit;
+            return AUDIO_JAVA_ERROR;
         }
     }
     nMask = (nAudioPortConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)
@@ -1184,8 +1170,8 @@
         ALOGV("convertAudioPortConfigFromNative OUT mask java %x native %x", jMask, nMask);
     }
 
-    *jAudioPortConfig =
-            env->NewObject(clazz, methodID, jAudioPort,
+    jAudioPortConfig->reset(
+            env->NewObject(clazz, methodID, jAudioPort->get(),
                            (nAudioPortConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)
                                    ? nAudioPortConfig->sample_rate
                                    : AUDIO_CONFIG_BASE_INITIALIZER.sample_rate,
@@ -1194,31 +1180,14 @@
                                    (nAudioPortConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)
                                            ? nAudioPortConfig->format
                                            : AUDIO_CONFIG_BASE_INITIALIZER.format),
-                           jAudioGainConfig);
+                           jAudioGainConfig.get()));
     if (*jAudioPortConfig == NULL) {
         ALOGV("convertAudioPortConfigFromNative could not create new port config");
-        jStatus = (jint)AUDIO_JAVA_ERROR;
+        return AUDIO_JAVA_ERROR;
     } else {
         ALOGV("convertAudioPortConfigFromNative OK");
     }
-
-exit:
-    if (audioportCreated) {
-        env->DeleteLocalRef(jAudioPort);
-        if (jAudioGain != NULL) {
-            env->DeleteLocalRef(jAudioGain);
-        }
-    }
-    if (jAudioGainConfig != NULL) {
-        env->DeleteLocalRef(jAudioGainConfig);
-    }
-    return jStatus;
-}
-
-// TODO: pull out to separate file
-template <typename T, size_t N>
-static constexpr size_t array_size(const T (&)[N]) {
-    return N;
+    return AUDIO_JAVA_SUCCESS;
 }
 
 static jintArray convertEncapsulationInfoFromNative(JNIEnv *env, uint32_t encapsulationInfo) {
@@ -1232,7 +1201,8 @@
         }
     }
     jintArray result = env->NewIntArray(encapsulation.size());
-    env->SetIntArrayRegion(result, 0, encapsulation.size(), (jint *)encapsulation.data());
+    env->SetIntArrayRegion(result, 0, encapsulation.size(),
+                           reinterpret_cast<jint *>(encapsulation.data()));
     return result;
 }
 
@@ -1240,8 +1210,8 @@
                                              std::stringstream &ss) {
     ss << " num_audio_profiles " << nAudioPort->num_audio_profiles << " num_gains "
        << nAudioPort->num_gains;
-    if (nAudioPort->num_audio_profiles > array_size(nAudioPort->audio_profiles) ||
-        nAudioPort->num_gains > array_size(nAudioPort->gains)) {
+    if (nAudioPort->num_audio_profiles > std::size(nAudioPort->audio_profiles) ||
+        nAudioPort->num_gains > std::size(nAudioPort->gains)) {
         return true;
     }
     for (size_t i = 0; i < nAudioPort->num_audio_profiles; ++i) {
@@ -1249,16 +1219,16 @@
            << " num_sample_rates " << nAudioPort->audio_profiles[i].num_sample_rates
            << " num_channel_masks " << nAudioPort->audio_profiles[i].num_channel_masks;
         if (nAudioPort->audio_profiles[i].num_sample_rates >
-                    array_size(nAudioPort->audio_profiles[i].sample_rates) ||
+                    std::size(nAudioPort->audio_profiles[i].sample_rates) ||
             nAudioPort->audio_profiles[i].num_channel_masks >
-                    array_size(nAudioPort->audio_profiles[i].channel_masks)) {
+                    std::size(nAudioPort->audio_profiles[i].channel_masks)) {
             return true;
         }
     }
     return false;
 }
 
-static jint convertAudioProfileFromNative(JNIEnv *env, jobject *jAudioProfile,
+static jint convertAudioProfileFromNative(JNIEnv *env, ScopedLocalRef<jobject> *jAudioProfile,
                                           const audio_profile *nAudioProfile, bool useInMask) {
     size_t numPositionMasks = 0;
     size_t numIndexMasks = 0;
@@ -1289,7 +1259,8 @@
 
     if (nAudioProfile->num_sample_rates) {
         env->SetIntArrayRegion(jSamplingRates.get(), 0 /*start*/, nAudioProfile->num_sample_rates,
-                               (jint *)nAudioProfile->sample_rates);
+                               const_cast<jint *>(reinterpret_cast<const jint *>(
+                                       nAudioProfile->sample_rates)));
     }
 
     // put the masks in the output arrays
@@ -1311,10 +1282,9 @@
         ALOGW("Unknown encapsulation type for JAVA API: %u", nAudioProfile->encapsulation_type);
     }
 
-    *jAudioProfile = env->NewObject(gAudioProfileClass, gAudioProfileCstor, audioFormat,
-                                    jSamplingRates.get(), jChannelMasks.get(),
-                                    jChannelIndexMasks.get(), encapsulationType);
-
+    jAudioProfile->reset(env->NewObject(gAudioProfileClass, gAudioProfileCstor, audioFormat,
+                                        jSamplingRates.get(), jChannelMasks.get(),
+                                        jChannelIndexMasks.get(), encapsulationType));
     if (*jAudioProfile == nullptr) {
         return AUDIO_JAVA_ERROR;
     }
@@ -1322,18 +1292,8 @@
     return AUDIO_JAVA_SUCCESS;
 }
 
-static jint convertAudioPortFromNative(JNIEnv *env, jobject *jAudioPort,
+static jint convertAudioPortFromNative(JNIEnv *env, ScopedLocalRef<jobject> *jAudioPort,
                                        const struct audio_port_v7 *nAudioPort) {
-    jint jStatus = (jint)AUDIO_JAVA_SUCCESS;
-    jintArray jEncapsulationModes = NULL;
-    jintArray jEncapsulationMetadataTypes = NULL;
-    jobjectArray jGains = NULL;
-    jobject jHandle = NULL;
-    jobject jAudioPortConfig = NULL;
-    jstring jDeviceName = NULL;
-    jobject jAudioProfiles = NULL;
-    jobject jAudioDescriptors = nullptr;
-    ScopedLocalRef<jobject> jPcmFloatProfileFromExtendedInteger(env, nullptr);
     bool hasFloat = false;
     bool useInMask;
 
@@ -1357,30 +1317,30 @@
         } else {
             ALOGE("%s", s.c_str());
         }
-        jStatus = (jint)AUDIO_JAVA_ERROR;
-        goto exit;
+        return AUDIO_JAVA_ERROR;
     }
 
     useInMask = audio_has_input_direction(nAudioPort->type, nAudioPort->role);
-    jAudioProfiles = env->NewObject(gArrayListClass, gArrayListMethods.cstor);
+    ScopedLocalRef<jobject> jAudioProfiles(env,
+                                           env->NewObject(gArrayListClass,
+                                                          gArrayListMethods.cstor));
     if (jAudioProfiles == nullptr) {
-        jStatus = (jint)AUDIO_JAVA_ERROR;
-        goto exit;
+        return AUDIO_JAVA_ERROR;
     }
 
+    ScopedLocalRef<jobject> jPcmFloatProfileFromExtendedInteger(env, nullptr);
     for (size_t i = 0; i < nAudioPort->num_audio_profiles; ++i) {
-        jobject jAudioProfile = nullptr;
-        jStatus = convertAudioProfileFromNative(env, &jAudioProfile, &nAudioPort->audio_profiles[i],
-                                                useInMask);
+        ScopedLocalRef<jobject> jAudioProfile(env);
+        jint jStatus = convertAudioProfileFromNative(env, &jAudioProfile,
+                                                     &nAudioPort->audio_profiles[i], useInMask);
         if (jStatus == AUDIO_JAVA_BAD_VALUE) {
             // skipping Java layer unsupported audio formats
             continue;
         }
         if (jStatus != NO_ERROR) {
-            jStatus = (jint)AUDIO_JAVA_ERROR;
-            goto exit;
+            return AUDIO_JAVA_ERROR;
         }
-        env->CallBooleanMethod(jAudioProfiles, gArrayListMethods.add, jAudioProfile);
+        env->CallBooleanMethod(jAudioProfiles.get(), gArrayListMethods.add, jAudioProfile.get());
 
         if (nAudioPort->audio_profiles[i].format == AUDIO_FORMAT_PCM_FLOAT) {
             hasFloat = true;
@@ -1389,21 +1349,23 @@
                    audio_bytes_per_sample(nAudioPort->audio_profiles[i].format) > 2) {
             ScopedLocalRef<jintArray>
                     jSamplingRates(env,
-                                   (jintArray)
-                                           env->GetObjectField(jAudioProfile,
-                                                               gAudioProfileFields.mSamplingRates));
+                                   static_cast<jintArray>(
+                                           env->GetObjectField(jAudioProfile.get(),
+                                                               gAudioProfileFields
+                                                                       .mSamplingRates)));
             ScopedLocalRef<jintArray>
                     jChannelMasks(env,
-                                  (jintArray)
-                                          env->GetObjectField(jAudioProfile,
-                                                              gAudioProfileFields.mChannelMasks));
+                                  static_cast<jintArray>(
+                                          env->GetObjectField(jAudioProfile.get(),
+                                                              gAudioProfileFields.mChannelMasks)));
             ScopedLocalRef<jintArray>
                     jChannelIndexMasks(env,
-                                       (jintArray)env->GetObjectField(jAudioProfile,
-                                                                      gAudioProfileFields
-                                                                              .mChannelIndexMasks));
+                                       static_cast<jintArray>(
+                                               env->GetObjectField(jAudioProfile.get(),
+                                                                   gAudioProfileFields
+                                                                           .mChannelIndexMasks)));
             int encapsulationType =
-                    env->GetIntField(jAudioProfile, gAudioProfileFields.mEncapsulationType);
+                    env->GetIntField(jAudioProfile.get(), gAudioProfileFields.mEncapsulationType);
 
             jPcmFloatProfileFromExtendedInteger.reset(
                     env->NewObject(gAudioProfileClass, gAudioProfileCstor,
@@ -1411,24 +1373,21 @@
                                    jSamplingRates.get(), jChannelMasks.get(),
                                    jChannelIndexMasks.get(), encapsulationType));
         }
-
-        if (jAudioProfile != nullptr) {
-            env->DeleteLocalRef(jAudioProfile);
-        }
     }
     if (!hasFloat && jPcmFloatProfileFromExtendedInteger.get() != nullptr) {
         // R and earlier compatibility - add ENCODING_PCM_FLOAT to the end
         // (replacing the zero pad). This ensures pre-S apps that look
         // for ENCODING_PCM_FLOAT continue to see that encoding if the device supports
         // extended precision integers.
-        env->CallBooleanMethod(jAudioProfiles, gArrayListMethods.add,
+        env->CallBooleanMethod(jAudioProfiles.get(), gArrayListMethods.add,
                                jPcmFloatProfileFromExtendedInteger.get());
     }
 
-    jAudioDescriptors = env->NewObject(gArrayListClass, gArrayListMethods.cstor);
+    ScopedLocalRef<jobject> jAudioDescriptors(env,
+                                              env->NewObject(gArrayListClass,
+                                                             gArrayListMethods.cstor));
     if (jAudioDescriptors == nullptr) {
-        jStatus = (jint)AUDIO_JAVA_ERROR;
-        goto exit;
+        return AUDIO_JAVA_ERROR;
     }
     for (size_t i = 0; i < nAudioPort->num_extra_audio_descriptors; ++i) {
         const auto &extraAudioDescriptor = nAudioPort->extra_audio_descriptors[i];
@@ -1458,15 +1417,16 @@
                                         env->NewObject(gAudioDescriptorClass, gAudioDescriptorCstor,
                                                        standard, encapsulationType,
                                                        jDescriptor.get()));
-        env->CallBooleanMethod(jAudioDescriptors, gArrayListMethods.add, jAudioDescriptor.get());
+        env->CallBooleanMethod(jAudioDescriptors.get(), gArrayListMethods.add,
+                               jAudioDescriptor.get());
     }
 
     // gains
-    jGains = env->NewObjectArray(nAudioPort->num_gains,
-                                          gAudioGainClass, NULL);
-    if (jGains == NULL) {
-        jStatus = (jint)AUDIO_JAVA_ERROR;
-        goto exit;
+    ScopedLocalRef<jobjectArray> jGains(env,
+                                        env->NewObjectArray(nAudioPort->num_gains, gAudioGainClass,
+                                                            nullptr));
+    if (jGains == nullptr) {
+        return AUDIO_JAVA_ERROR;
     }
 
     for (size_t j = 0; j < nAudioPort->num_gains; j++) {
@@ -1491,88 +1451,71 @@
                                                  nAudioPort->gains[j].min_ramp_ms,
                                                  nAudioPort->gains[j].max_ramp_ms);
         if (jGain == NULL) {
-            jStatus = (jint)AUDIO_JAVA_ERROR;
-            goto exit;
+            return AUDIO_JAVA_ERROR;
         }
-        env->SetObjectArrayElement(jGains, j, jGain);
+        env->SetObjectArrayElement(jGains.get(), j, jGain);
         env->DeleteLocalRef(jGain);
     }
 
-    jHandle = env->NewObject(gAudioHandleClass, gAudioHandleCstor,
-                                             nAudioPort->id);
-    if (jHandle == NULL) {
-        jStatus = (jint)AUDIO_JAVA_ERROR;
-        goto exit;
+    ScopedLocalRef<jobject> jHandle(env,
+                                    env->NewObject(gAudioHandleClass, gAudioHandleCstor,
+                                                   nAudioPort->id));
+    if (jHandle == nullptr) {
+        return AUDIO_JAVA_ERROR;
     }
 
-    jDeviceName = env->NewStringUTF(nAudioPort->name);
-
+    ScopedLocalRef<jstring> jDeviceName(env, env->NewStringUTF(nAudioPort->name));
     if (nAudioPort->type == AUDIO_PORT_TYPE_DEVICE) {
-        ALOGV("convertAudioPortFromNative is a device %08x", nAudioPort->ext.device.type);
-        jstring jAddress = env->NewStringUTF(nAudioPort->ext.device.address);
-        jEncapsulationModes =
-                convertEncapsulationInfoFromNative(env, nAudioPort->ext.device.encapsulation_modes);
-        jEncapsulationMetadataTypes =
+        ScopedLocalRef<jintArray> jEncapsulationModes(
+                env,
+                convertEncapsulationInfoFromNative(env,
+                                                   nAudioPort->ext.device.encapsulation_modes));
+        ScopedLocalRef<jintArray> jEncapsulationMetadataTypes(
+                env,
                 convertEncapsulationInfoFromNative(env,
                                                    nAudioPort->ext.device
-                                                           .encapsulation_metadata_types);
-        *jAudioPort =
-                env->NewObject(gAudioDevicePortClass, gAudioDevicePortCstor, jHandle, jDeviceName,
-                               jAudioProfiles, jGains, nAudioPort->ext.device.type, jAddress,
-                               jEncapsulationModes, jEncapsulationMetadataTypes, jAudioDescriptors);
-        env->DeleteLocalRef(jAddress);
+                                                           .encapsulation_metadata_types));
+        ALOGV("convertAudioPortFromNative is a device %08x", nAudioPort->ext.device.type);
+        ScopedLocalRef<jstring> jAddress(env, env->NewStringUTF(nAudioPort->ext.device.address));
+        jAudioPort->reset(env->NewObject(gAudioDevicePortClass, gAudioDevicePortCstor,
+                                         jHandle.get(), jDeviceName.get(), jAudioProfiles.get(),
+                                         jGains.get(), nAudioPort->ext.device.type, jAddress.get(),
+                                         jEncapsulationModes.get(),
+                                         jEncapsulationMetadataTypes.get(),
+                                         jAudioDescriptors.get()));
     } else if (nAudioPort->type == AUDIO_PORT_TYPE_MIX) {
         ALOGV("convertAudioPortFromNative is a mix");
-        *jAudioPort = env->NewObject(gAudioMixPortClass, gAudioMixPortCstor, jHandle,
-                                     nAudioPort->ext.mix.handle, nAudioPort->role, jDeviceName,
-                                     jAudioProfiles, jGains);
+        jAudioPort->reset(env->NewObject(gAudioMixPortClass, gAudioMixPortCstor, jHandle.get(),
+                                         nAudioPort->ext.mix.handle, nAudioPort->role,
+                                         jDeviceName.get(), jAudioProfiles.get(), jGains.get()));
     } else {
         ALOGE("convertAudioPortFromNative unknown nAudioPort type %d", nAudioPort->type);
-        jStatus = (jint)AUDIO_JAVA_ERROR;
-        goto exit;
+        return AUDIO_JAVA_ERROR;
     }
     if (*jAudioPort == NULL) {
-        jStatus = (jint)AUDIO_JAVA_ERROR;
-        goto exit;
+        return AUDIO_JAVA_ERROR;
     }
 
-    jStatus = convertAudioPortConfigFromNative(env,
-                                                       *jAudioPort,
-                                                       &jAudioPortConfig,
+    ScopedLocalRef<jobject> jAudioPortConfig(env, nullptr);
+
+    if (int jStatus = convertAudioPortConfigFromNative(env, jAudioPort, &jAudioPortConfig,
                                                        &nAudioPort->active_config);
-    if (jStatus != AUDIO_JAVA_SUCCESS) {
-        goto exit;
+        jStatus != AUDIO_JAVA_SUCCESS) {
+        return jStatus;
     }
 
-    env->SetObjectField(*jAudioPort, gAudioPortFields.mActiveConfig, jAudioPortConfig);
+    env->SetObjectField(jAudioPort->get(), gAudioPortFields.mActiveConfig, jAudioPortConfig.get());
+    return AUDIO_JAVA_SUCCESS;
+}
 
-exit:
-    if (jDeviceName != NULL) {
-        env->DeleteLocalRef(jDeviceName);
+static bool setGeneration(JNIEnv *env, jintArray jGeneration, unsigned int generation1) {
+    ScopedIntArrayRW nGeneration(env, jGeneration);
+    if (nGeneration.get() == nullptr) {
+        return false;
+    } else {
+        nGeneration[0] = generation1;
+        return true;
     }
-    if (jEncapsulationModes != NULL) {
-        env->DeleteLocalRef(jEncapsulationModes);
-    }
-    if (jEncapsulationMetadataTypes != NULL) {
-        env->DeleteLocalRef(jEncapsulationMetadataTypes);
-    }
-    if (jAudioProfiles != NULL) {
-        env->DeleteLocalRef(jAudioProfiles);
-    }
-    if (jGains != NULL) {
-        env->DeleteLocalRef(jGains);
-    }
-    if (jHandle != NULL) {
-        env->DeleteLocalRef(jHandle);
-    }
-    if (jAudioPortConfig != NULL) {
-        env->DeleteLocalRef(jAudioPortConfig);
-    }
-    if (jAudioDescriptors != nullptr) {
-        env->DeleteLocalRef(jAudioDescriptors);
-    }
-
-    return jStatus;
 }
 
 static jint
@@ -1583,23 +1526,22 @@
 
     if (jPorts == NULL) {
         ALOGE("listAudioPorts NULL AudioPort ArrayList");
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     if (!env->IsInstanceOf(jPorts, gArrayListClass)) {
         ALOGE("listAudioPorts not an arraylist");
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     if (jGeneration == NULL || env->GetArrayLength(jGeneration) != 1) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     status_t status;
-    unsigned int generation1;
+    unsigned int generation1 = 0;
     unsigned int generation;
     unsigned int numPorts;
-    jint *nGeneration;
-    struct audio_port_v7 *nPorts = nullptr;
+    std::vector<audio_port_v7> nPorts;
     int attempts = MAX_PORT_GENERATION_SYNC_ATTEMPTS;
     jint jStatus;
 
@@ -1618,43 +1560,29 @@
             break;
         }
         if (numPorts == 0) {
-            jStatus = (jint)AUDIO_JAVA_SUCCESS;
-            goto exit;
+            return setGeneration(env, jGeneration, generation1) ? AUDIO_JAVA_SUCCESS
+                                                                : AUDIO_JAVA_ERROR;
         }
-        nPorts = (struct audio_port_v7 *)realloc(nPorts, numPorts * sizeof(struct audio_port_v7));
+        nPorts.resize(numPorts);
 
         status = AudioSystem::listAudioPorts(AUDIO_PORT_ROLE_NONE, AUDIO_PORT_TYPE_NONE, &numPorts,
-                                             nPorts, &generation);
+                                             &nPorts[0], &generation);
         ALOGV("listAudioPorts AudioSystem::listAudioPorts numPorts %d generation %d generation1 %d",
               numPorts, generation, generation1);
     } while (generation1 != generation && status == NO_ERROR);
 
     jStatus = nativeToJavaStatus(status);
-    if (jStatus != AUDIO_JAVA_SUCCESS) {
-        goto exit;
-    }
-
-    for (size_t i = 0; i < numPorts; i++) {
-        jobject jAudioPort = NULL;
-        jStatus = convertAudioPortFromNative(env, &jAudioPort, &nPorts[i]);
-        if (jStatus != AUDIO_JAVA_SUCCESS) {
-            goto exit;
-        }
-        env->CallBooleanMethod(jPorts, gArrayListMethods.add, jAudioPort);
-        if (jAudioPort != NULL) {
-            env->DeleteLocalRef(jAudioPort);
+    if (jStatus == AUDIO_JAVA_SUCCESS) {
+        for (size_t i = 0; i < numPorts; i++) {
+            ScopedLocalRef<jobject> jAudioPort(env, nullptr);
+            jStatus = convertAudioPortFromNative(env, &jAudioPort, &nPorts[i]);
+            if (jStatus != AUDIO_JAVA_SUCCESS) break;
+            env->CallBooleanMethod(jPorts, gArrayListMethods.add, jAudioPort.get());
         }
     }
-
-exit:
-    nGeneration = env->GetIntArrayElements(jGeneration, NULL);
-    if (nGeneration == NULL) {
-        jStatus = (jint)AUDIO_JAVA_ERROR;
-    } else {
-        nGeneration[0] = generation1;
-        env->ReleaseIntArrayElements(jGeneration, nGeneration, 0);
+    if (!setGeneration(env, jGeneration, generation1)) {
+        jStatus = AUDIO_JAVA_ERROR;
     }
-    free(nPorts);
     return jStatus;
 }
 
@@ -1667,64 +1595,56 @@
 
     ALOGV("createAudioPatch");
     if (jPatches == NULL || jSources == NULL || jSinks == NULL) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     if (env->GetArrayLength(jPatches) != 1) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     jint numSources = env->GetArrayLength(jSources);
     if (numSources == 0 || numSources > AUDIO_PATCH_PORTS_MAX) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     jint numSinks = env->GetArrayLength(jSinks);
     if (numSinks == 0 || numSinks > AUDIO_PATCH_PORTS_MAX) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
-    audio_patch_handle_t handle = (audio_patch_handle_t)0;
-    jobject jPatch = env->GetObjectArrayElement(jPatches, 0);
-    jobject jPatchHandle = NULL;
-    if (jPatch != NULL) {
-        if (!env->IsInstanceOf(jPatch, gAudioPatchClass)) {
-            return (jint)AUDIO_JAVA_BAD_VALUE;
+    audio_patch_handle_t handle = static_cast<audio_patch_handle_t>(AUDIO_PATCH_HANDLE_NONE);
+    ScopedLocalRef<jobject> jPatch(env, env->GetObjectArrayElement(jPatches, 0));
+    ScopedLocalRef<jobject> jPatchHandle(env, nullptr);
+    if (jPatch != nullptr) {
+        if (!env->IsInstanceOf(jPatch.get(), gAudioPatchClass)) {
+            return AUDIO_JAVA_BAD_VALUE;
         }
-        jPatchHandle = env->GetObjectField(jPatch, gAudioPatchFields.mHandle);
-        handle = (audio_patch_handle_t)env->GetIntField(jPatchHandle, gAudioHandleFields.mId);
+        jPatchHandle.reset(env->GetObjectField(jPatch.get(), gAudioPatchFields.mHandle));
+        handle = static_cast<audio_patch_handle_t>(
+                env->GetIntField(jPatchHandle.get(), gAudioHandleFields.mId));
     }
 
     struct audio_patch nPatch = { .id = handle };
 
-    jobject jSource = NULL;
-    jobject jSink = NULL;
-
     for (jint i = 0; i < numSources; i++) {
-        jSource = env->GetObjectArrayElement(jSources, i);
-        if (!env->IsInstanceOf(jSource, gAudioPortConfigClass)) {
-            jStatus = (jint)AUDIO_JAVA_BAD_VALUE;
-            goto exit;
+        ScopedLocalRef<jobject> jSource(env, env->GetObjectArrayElement(jSources, i));
+        if (!env->IsInstanceOf(jSource.get(), gAudioPortConfigClass)) {
+            return AUDIO_JAVA_BAD_VALUE;
         }
-        jStatus = convertAudioPortConfigToNative(env, &nPatch.sources[i], jSource, false);
-        env->DeleteLocalRef(jSource);
-        jSource = NULL;
+        jStatus = convertAudioPortConfigToNative(env, &nPatch.sources[i], jSource.get(), false);
         if (jStatus != AUDIO_JAVA_SUCCESS) {
-            goto exit;
+            return jStatus;
         }
         nPatch.num_sources++;
     }
 
     for (jint i = 0; i < numSinks; i++) {
-        jSink = env->GetObjectArrayElement(jSinks, i);
-        if (!env->IsInstanceOf(jSink, gAudioPortConfigClass)) {
-            jStatus = (jint)AUDIO_JAVA_BAD_VALUE;
-            goto exit;
+        ScopedLocalRef<jobject> jSink(env, env->GetObjectArrayElement(jSinks, i));
+        if (!env->IsInstanceOf(jSink.get(), gAudioPortConfigClass)) {
+            return AUDIO_JAVA_BAD_VALUE;
         }
-        jStatus = convertAudioPortConfigToNative(env, &nPatch.sinks[i], jSink, false);
-        env->DeleteLocalRef(jSink);
-        jSink = NULL;
+        jStatus = convertAudioPortConfigToNative(env, &nPatch.sinks[i], jSink.get(), false);
         if (jStatus != AUDIO_JAVA_SUCCESS) {
-            goto exit;
+            return jStatus;
         }
         nPatch.num_sinks++;
     }
@@ -1735,38 +1655,22 @@
 
     jStatus = nativeToJavaStatus(status);
     if (jStatus != AUDIO_JAVA_SUCCESS) {
-        goto exit;
+        return jStatus;
     }
 
-    if (jPatchHandle == NULL) {
-        jPatchHandle = env->NewObject(gAudioHandleClass, gAudioHandleCstor,
-                                           handle);
-        if (jPatchHandle == NULL) {
-            jStatus = (jint)AUDIO_JAVA_ERROR;
-            goto exit;
+    if (jPatchHandle == nullptr) {
+        jPatchHandle.reset(env->NewObject(gAudioHandleClass, gAudioHandleCstor, handle));
+        if (jPatchHandle == nullptr) {
+            return AUDIO_JAVA_ERROR;
         }
-        jPatch = env->NewObject(gAudioPatchClass, gAudioPatchCstor, jPatchHandle, jSources, jSinks);
-        if (jPatch == NULL) {
-            jStatus = (jint)AUDIO_JAVA_ERROR;
-            goto exit;
+        jPatch.reset(env->NewObject(gAudioPatchClass, gAudioPatchCstor, jPatchHandle.get(),
+                                    jSources, jSinks));
+        if (jPatch == nullptr) {
+            return AUDIO_JAVA_ERROR;
         }
-        env->SetObjectArrayElement(jPatches, 0, jPatch);
+        env->SetObjectArrayElement(jPatches, 0, jPatch.get());
     } else {
-        env->SetIntField(jPatchHandle, gAudioHandleFields.mId, handle);
-    }
-
-exit:
-    if (jPatchHandle != NULL) {
-        env->DeleteLocalRef(jPatchHandle);
-    }
-    if (jPatch != NULL) {
-        env->DeleteLocalRef(jPatch);
-    }
-    if (jSource != NULL) {
-        env->DeleteLocalRef(jSource);
-    }
-    if (jSink != NULL) {
-        env->DeleteLocalRef(jSink);
+        env->SetIntField(jPatchHandle.get(), gAudioHandleFields.mId, handle);
     }
     return jStatus;
 }
@@ -1777,16 +1681,17 @@
 {
     ALOGV("releaseAudioPatch");
     if (jPatch == NULL) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
-    audio_patch_handle_t handle = (audio_patch_handle_t)0;
+    audio_patch_handle_t handle = static_cast<audio_patch_handle_t>(AUDIO_PATCH_HANDLE_NONE);
     jobject jPatchHandle = NULL;
     if (!env->IsInstanceOf(jPatch, gAudioPatchClass)) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     jPatchHandle = env->GetObjectField(jPatch, gAudioPatchFields.mHandle);
-    handle = (audio_patch_handle_t)env->GetIntField(jPatchHandle, gAudioHandleFields.mId);
+    handle = static_cast<audio_patch_handle_t>(
+            env->GetIntField(jPatchHandle, gAudioHandleFields.mId));
     env->DeleteLocalRef(jPatchHandle);
 
     ALOGV("AudioSystem::releaseAudioPatch");
@@ -1803,28 +1708,22 @@
     ALOGV("listAudioPatches");
     if (jPatches == NULL) {
         ALOGE("listAudioPatches NULL AudioPatch ArrayList");
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     if (!env->IsInstanceOf(jPatches, gArrayListClass)) {
         ALOGE("listAudioPatches not an arraylist");
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     if (jGeneration == NULL || env->GetArrayLength(jGeneration) != 1) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     status_t status;
     unsigned int generation1;
     unsigned int generation;
     unsigned int numPatches;
-    jint *nGeneration;
-    struct audio_patch *nPatches = NULL;
-    jobjectArray jSources = NULL;
-    jobject jSource = NULL;
-    jobjectArray jSinks = NULL;
-    jobject jSink = NULL;
-    jobject jPatch = NULL;
+    std::vector<audio_patch> nPatches;
     int attempts = MAX_PORT_GENERATION_SYNC_ATTEMPTS;
     jint jStatus;
 
@@ -1845,15 +1744,13 @@
             break;
         }
         if (numPatches == 0) {
-            jStatus = (jint)AUDIO_JAVA_SUCCESS;
-            goto exit;
+            return setGeneration(env, jGeneration, generation1) ? AUDIO_JAVA_SUCCESS
+                                                                : AUDIO_JAVA_ERROR;
         }
 
-        nPatches = (struct audio_patch *)realloc(nPatches, numPatches * sizeof(struct audio_patch));
+        nPatches.resize(numPatches);
 
-        status = AudioSystem::listAudioPatches(&numPatches,
-                                               nPatches,
-                                               &generation);
+        status = AudioSystem::listAudioPatches(&numPatches, nPatches.data(), &generation);
         ALOGV("listAudioPatches AudioSystem::listAudioPatches numPatches %d generation %d generation1 %d",
               numPatches, generation, generation1);
 
@@ -1861,15 +1758,21 @@
 
     jStatus = nativeToJavaStatus(status);
     if (jStatus != AUDIO_JAVA_SUCCESS) {
-        goto exit;
+        if (!setGeneration(env, jGeneration, generation1)) {
+            jStatus = AUDIO_JAVA_ERROR;
+        }
+        return jStatus;
     }
 
     for (size_t i = 0; i < numPatches; i++) {
+        ScopedLocalRef<jobject> jPatch(env, nullptr);
+        ScopedLocalRef<jobjectArray> jSources(env, nullptr);
+        ScopedLocalRef<jobjectArray> jSinks(env, nullptr);
         jobject patchHandle = env->NewObject(gAudioHandleClass, gAudioHandleCstor,
                                                  nPatches[i].id);
         if (patchHandle == NULL) {
-            jStatus = AUDIO_JAVA_ERROR;
-            goto exit;
+            setGeneration(env, jGeneration, generation1);
+            return AUDIO_JAVA_ERROR;
         }
         ALOGV("listAudioPatches patch %zu num_sources %d num_sinks %d",
               i, nPatches[i].num_sources, nPatches[i].num_sinks);
@@ -1877,96 +1780,66 @@
         env->SetIntField(patchHandle, gAudioHandleFields.mId, nPatches[i].id);
 
         // load sources
-        jSources = env->NewObjectArray(nPatches[i].num_sources,
-                                       gAudioPortConfigClass, NULL);
-        if (jSources == NULL) {
-            jStatus = AUDIO_JAVA_ERROR;
-            goto exit;
+        jSources.reset(env->NewObjectArray(nPatches[i].num_sources, gAudioPortConfigClass, NULL));
+        if (jSources == nullptr) {
+            setGeneration(env, jGeneration, generation1);
+            return AUDIO_JAVA_ERROR;
         }
 
         for (size_t j = 0; j < nPatches[i].num_sources; j++) {
-            jStatus = convertAudioPortConfigFromNative(env,
-                                                      NULL,
-                                                      &jSource,
-                                                      &nPatches[i].sources[j]);
+            ScopedLocalRef<jobject> jSource(env, nullptr);
+            ScopedLocalRef<jobject> jAudioPort(env, nullptr);
+            jStatus = convertAudioPortConfigFromNative(env, &jAudioPort, &jSource,
+                                                       &nPatches[i].sources[j]);
             if (jStatus != AUDIO_JAVA_SUCCESS) {
-                goto exit;
+                if (!setGeneration(env, jGeneration, generation1)) {
+                    jStatus = AUDIO_JAVA_ERROR;
+                }
+                return jStatus;
             }
-            env->SetObjectArrayElement(jSources, j, jSource);
-            env->DeleteLocalRef(jSource);
-            jSource = NULL;
+            env->SetObjectArrayElement(jSources.get(), j, jSource.get());
             ALOGV("listAudioPatches patch %zu source %zu is a %s handle %d",
                   i, j,
                   nPatches[i].sources[j].type == AUDIO_PORT_TYPE_DEVICE ? "device" : "mix",
                   nPatches[i].sources[j].id);
         }
         // load sinks
-        jSinks = env->NewObjectArray(nPatches[i].num_sinks,
-                                     gAudioPortConfigClass, NULL);
-        if (jSinks == NULL) {
-            jStatus = AUDIO_JAVA_ERROR;
-            goto exit;
+        jSinks.reset(env->NewObjectArray(nPatches[i].num_sinks, gAudioPortConfigClass, NULL));
+        if (jSinks == nullptr) {
+            setGeneration(env, jGeneration, generation1);
+            return AUDIO_JAVA_ERROR;
         }
 
         for (size_t j = 0; j < nPatches[i].num_sinks; j++) {
-            jStatus = convertAudioPortConfigFromNative(env,
-                                                      NULL,
-                                                      &jSink,
-                                                      &nPatches[i].sinks[j]);
+            ScopedLocalRef<jobject> jSink(env, nullptr);
+            ScopedLocalRef<jobject> jAudioPort(env, nullptr);
+            jStatus = convertAudioPortConfigFromNative(env, &jAudioPort, &jSink,
+                                                       &nPatches[i].sinks[j]);
 
             if (jStatus != AUDIO_JAVA_SUCCESS) {
-                goto exit;
+                if (!setGeneration(env, jGeneration, generation1)) {
+                    jStatus = AUDIO_JAVA_ERROR;
+                }
+                return jStatus;
             }
-            env->SetObjectArrayElement(jSinks, j, jSink);
-            env->DeleteLocalRef(jSink);
-            jSink = NULL;
+            env->SetObjectArrayElement(jSinks.get(), j, jSink.get());
             ALOGV("listAudioPatches patch %zu sink %zu is a %s handle %d",
                   i, j,
                   nPatches[i].sinks[j].type == AUDIO_PORT_TYPE_DEVICE ? "device" : "mix",
                   nPatches[i].sinks[j].id);
         }
 
-        jPatch = env->NewObject(gAudioPatchClass, gAudioPatchCstor,
-                                       patchHandle, jSources, jSinks);
-        env->DeleteLocalRef(jSources);
-        jSources = NULL;
-        env->DeleteLocalRef(jSinks);
-        jSinks = NULL;
-        if (jPatch == NULL) {
-            jStatus = AUDIO_JAVA_ERROR;
-            goto exit;
+        jPatch.reset(env->NewObject(gAudioPatchClass, gAudioPatchCstor, patchHandle, jSources.get(),
+                                    jSinks.get()));
+        if (jPatch == nullptr) {
+            setGeneration(env, jGeneration, generation1);
+            return AUDIO_JAVA_ERROR;
         }
-        env->CallBooleanMethod(jPatches, gArrayListMethods.add, jPatch);
-        env->DeleteLocalRef(jPatch);
-        jPatch = NULL;
+        env->CallBooleanMethod(jPatches, gArrayListMethods.add, jPatch.get());
     }
-
-exit:
-
-    nGeneration = env->GetIntArrayElements(jGeneration, NULL);
-    if (nGeneration == NULL) {
+    if (!setGeneration(env, jGeneration, generation1)) {
         jStatus = AUDIO_JAVA_ERROR;
-    } else {
-        nGeneration[0] = generation1;
-        env->ReleaseIntArrayElements(jGeneration, nGeneration, 0);
     }
-
-    if (jSources != NULL) {
-        env->DeleteLocalRef(jSources);
-    }
-    if (jSource != NULL) {
-        env->DeleteLocalRef(jSource);
-    }
-    if (jSinks != NULL) {
-        env->DeleteLocalRef(jSinks);
-    }
-    if (jSink != NULL) {
-        env->DeleteLocalRef(jSink);
-    }
-    if (jPatch != NULL) {
-        env->DeleteLocalRef(jPatch);
-    }
-    free(nPatches);
     return jStatus;
 }
 
@@ -2015,7 +1888,7 @@
     }
     auto paa = JNIAudioAttributeHelper::makeUnique();
     jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jAudioAttributes, paa.get());
-    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+    if (jStatus != AUDIO_JAVA_SUCCESS) {
         return jStatus;
     }
     audio_port_handle_t handle;
@@ -2032,8 +1905,7 @@
 android_media_AudioSystem_stopAudioSource(JNIEnv *env, jobject clazz, jint handle)
 {
     ALOGV("stopAudioSource");
-    status_t status = AudioSystem::stopAudioSource(
-            static_cast <audio_port_handle_t>(handle));
+    status_t status = AudioSystem::stopAudioSource(static_cast<audio_port_handle_t>(handle));
     ALOGV("AudioSystem::stopAudioSource() returned %d", status);
     return nativeToJavaStatus(status);
 }
@@ -2065,7 +1937,7 @@
 static jint
 android_media_AudioSystem_getAudioHwSyncForSession(JNIEnv *env, jobject thiz, jint sessionId)
 {
-    return (jint) AudioSystem::getAudioHwSyncForSession((audio_session_t) sessionId);
+    return AudioSystem::getAudioHwSyncForSession(static_cast<audio_session_t>(sessionId));
 }
 
 static void
@@ -2110,11 +1982,11 @@
 {
     nAudioMix->mMixType = env->GetIntField(jAudioMix, gAudioMixFields.mMixType);
     nAudioMix->mRouteFlags = env->GetIntField(jAudioMix, gAudioMixFields.mRouteFlags);
-    nAudioMix->mDeviceType = (audio_devices_t)
-            env->GetIntField(jAudioMix, gAudioMixFields.mDeviceType);
+    nAudioMix->mDeviceType =
+            static_cast<audio_devices_t>(env->GetIntField(jAudioMix, gAudioMixFields.mDeviceType));
 
-    jstring jDeviceAddress = (jstring)env->GetObjectField(jAudioMix,
-                                                           gAudioMixFields.mDeviceAddress);
+    jstring jDeviceAddress =
+            static_cast<jstring>(env->GetObjectField(jAudioMix, gAudioMixFields.mDeviceAddress));
     const char *nDeviceAddress = env->GetStringUTFChars(jDeviceAddress, NULL);
     nAudioMix->mDeviceAddress = String8(nDeviceAddress);
     env->ReleaseStringUTFChars(jDeviceAddress, nDeviceAddress);
@@ -2133,8 +2005,8 @@
     nAudioMix->mVoiceCommunicationCaptureAllowed =
             env->GetBooleanField(jRule, gAudioMixingRuleFields.mVoiceCommunicationCaptureAllowed);
     env->DeleteLocalRef(jRule);
-    jobjectArray jCriteria = (jobjectArray)env->CallObjectMethod(jRuleCriteria,
-                                                                 gArrayListMethods.toArray);
+    jobjectArray jCriteria = static_cast<jobjectArray>(
+            env->CallObjectMethod(jRuleCriteria, gArrayListMethods.toArray));
     env->DeleteLocalRef(jRuleCriteria);
 
     jint numCriteria = env->GetArrayLength(jCriteria);
@@ -2165,8 +2037,8 @@
 
             auto paa = JNIAudioAttributeHelper::makeUnique();
             jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jAttributes, paa.get());
-            if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
-                return jStatus;
+            if (jStatus != AUDIO_JAVA_SUCCESS) {
+                    return jStatus;
             }
             if (match_rule == RULE_MATCH_ATTRIBUTE_USAGE) {
                 nCriterion.mValue.mUsage = paa->usage;
@@ -2184,7 +2056,7 @@
 
     env->DeleteLocalRef(jCriteria);
 
-    return (jint)AUDIO_JAVA_SUCCESS;
+    return AUDIO_JAVA_SUCCESS;
 }
 
 static jint
@@ -2194,34 +2066,29 @@
     ALOGV("registerPolicyMixes");
 
     if (jMixesList == NULL) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     if (!env->IsInstanceOf(jMixesList, gArrayListClass)) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
-    jobjectArray jMixes = (jobjectArray)env->CallObjectMethod(jMixesList,
-                                                              gArrayListMethods.toArray);
+    jobjectArray jMixes =
+            static_cast<jobjectArray>(env->CallObjectMethod(jMixesList, gArrayListMethods.toArray));
     jint numMixes = env->GetArrayLength(jMixes);
     if (numMixes > MAX_MIXES_PER_POLICY) {
         numMixes = MAX_MIXES_PER_POLICY;
     }
 
     status_t status;
-    jint jStatus;
-    jobject jAudioMix = NULL;
     Vector <AudioMix> mixes;
     for (jint i = 0; i < numMixes; i++) {
-        jAudioMix = env->GetObjectArrayElement(jMixes, i);
-        if (!env->IsInstanceOf(jAudioMix, gAudioMixClass)) {
-            jStatus = (jint)AUDIO_JAVA_BAD_VALUE;
-            goto exit;
+        ScopedLocalRef<jobject> jAudioMix(env, env->GetObjectArrayElement(jMixes, i));
+        if (!env->IsInstanceOf(jAudioMix.get(), gAudioMixClass)) {
+            return AUDIO_JAVA_BAD_VALUE;
         }
         AudioMix mix;
-        jStatus = convertAudioMixToNative(env, &mix, jAudioMix);
-        env->DeleteLocalRef(jAudioMix);
-        jAudioMix = NULL;
-        if (jStatus != AUDIO_JAVA_SUCCESS) {
-            goto exit;
+        if (jint jStatus = convertAudioMixToNative(env, &mix, jAudioMix.get());
+            jStatus != AUDIO_JAVA_SUCCESS) {
+            return jStatus;
         }
         mixes.add(mix);
     }
@@ -2230,16 +2097,7 @@
     status = AudioSystem::registerPolicyMixes(mixes, registration);
     ALOGV("AudioSystem::registerPolicyMixes() returned %d", status);
 
-    jStatus = nativeToJavaStatus(status);
-    if (jStatus != AUDIO_JAVA_SUCCESS) {
-        goto exit;
-    }
-
-exit:
-    if (jAudioMix != NULL) {
-        env->DeleteLocalRef(jAudioMix);
-    }
-    return jStatus;
+    return nativeToJavaStatus(status);
 }
 
 static jint android_media_AudioSystem_setUidDeviceAffinities(JNIEnv *env, jobject clazz,
@@ -2249,14 +2107,14 @@
     if (results != NO_ERROR) {
         return results;
     }
-    status_t status = AudioSystem::setUidDeviceAffinities((uid_t) uid, deviceVector);
-    return (jint) nativeToJavaStatus(status);
+    status_t status = AudioSystem::setUidDeviceAffinities(uid, deviceVector);
+    return nativeToJavaStatus(status);
 }
 
 static jint android_media_AudioSystem_removeUidDeviceAffinities(JNIEnv *env, jobject clazz,
         jint uid) {
-    status_t status = AudioSystem::removeUidDeviceAffinities((uid_t) uid);
-    return (jint) nativeToJavaStatus(status);
+    status_t status = AudioSystem::removeUidDeviceAffinities(static_cast<uid_t>(uid));
+    return nativeToJavaStatus(status);
 }
 
 static jint android_media_AudioSystem_setUserIdDeviceAffinities(JNIEnv *env, jobject clazz,
@@ -2267,14 +2125,14 @@
     if (results != NO_ERROR) {
         return results;
     }
-    status_t status = AudioSystem::setUserIdDeviceAffinities((int)userId, deviceVector);
-    return (jint)nativeToJavaStatus(status);
+    status_t status = AudioSystem::setUserIdDeviceAffinities(userId, deviceVector);
+    return nativeToJavaStatus(status);
 }
 
 static jint android_media_AudioSystem_removeUserIdDeviceAffinities(JNIEnv *env, jobject clazz,
                                                                    jint userId) {
-    status_t status = AudioSystem::removeUserIdDeviceAffinities((int)userId);
-    return (jint)nativeToJavaStatus(status);
+    status_t status = AudioSystem::removeUserIdDeviceAffinities(userId);
+    return nativeToJavaStatus(status);
 }
 
 static jint
@@ -2287,19 +2145,18 @@
 android_media_AudioSystem_getStreamVolumeDB(JNIEnv *env, jobject thiz,
                                             jint stream, jint index, jint device)
 {
-    return (jfloat)AudioSystem::getStreamVolumeDB((audio_stream_type_t)stream,
-                                                  (int)index,
-                                                  (audio_devices_t)device);
+    return AudioSystem::getStreamVolumeDB(static_cast<audio_stream_type_t>(stream), index,
+                                          static_cast<audio_devices_t>(device));
 }
 
 static jint android_media_AudioSystem_getOffloadSupport(JNIEnv *env, jobject thiz, jint encoding,
                                                         jint sampleRate, jint channelMask,
                                                         jint channelIndexMask, jint streamType) {
     audio_offload_info_t format = AUDIO_INFO_INITIALIZER;
-    format.format = (audio_format_t) audioFormatToNative(encoding);
-    format.sample_rate = (uint32_t) sampleRate;
+    format.format = static_cast<audio_format_t>(audioFormatToNative(encoding));
+    format.sample_rate = sampleRate;
     format.channel_mask = nativeChannelMaskFromJavaChannelMasks(channelMask, channelIndexMask);
-    format.stream_type = (audio_stream_type_t) streamType;
+    format.stream_type = static_cast<audio_stream_type_t>(streamType);
     format.has_video = false;
     format.is_streaming = false;
     // offload duration unknown at this point:
@@ -2316,11 +2173,11 @@
 
     if (jMicrophonesInfo == NULL) {
         ALOGE("jMicrophonesInfo NULL MicrophoneInfo ArrayList");
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     if (!env->IsInstanceOf(jMicrophonesInfo, gArrayListClass)) {
         ALOGE("getMicrophones not an arraylist");
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     jint jStatus;
@@ -2332,7 +2189,7 @@
         return jStatus;
     }
     if (microphones.size() == 0) {
-        jStatus = (jint)AUDIO_JAVA_SUCCESS;
+        jStatus = AUDIO_JAVA_SUCCESS;
         return jStatus;
     }
     for (size_t i = 0; i < microphones.size(); i++) {
@@ -2354,7 +2211,7 @@
     jint jStatus = AUDIO_JAVA_SUCCESS;
     if (!env->IsInstanceOf(jEncodingFormatList, gArrayListClass)) {
         ALOGE("%s: jEncodingFormatList not an ArrayList", __FUNCTION__);
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     std::vector<audio_format_t> encodingFormats;
     status_t status =
@@ -2473,12 +2330,10 @@
 android_media_AudioSystem_setSurroundFormatEnabled(JNIEnv *env, jobject thiz,
                                                    jint audioFormat, jboolean enabled)
 {
-    status_t status = AudioSystem::setSurroundFormatEnabled(audioFormatToNative(audioFormat),
-                                                            (bool)enabled);
-    if (status != NO_ERROR) {
-        ALOGE_IF(status != NO_ERROR, "AudioSystem::setSurroundFormatEnabled error %d", status);
-    }
-    return (jint)nativeToJavaStatus(status);
+    status_t status =
+            AudioSystem::setSurroundFormatEnabled(audioFormatToNative(audioFormat), enabled);
+    ALOGE_IF(status != NO_ERROR, "AudioSystem::setSurroundFormatEnabled error %d", status);
+    return nativeToJavaStatus(status);
 }
 
 static jint android_media_AudioSystem_getMaxChannelCount(JNIEnv *env, jobject thiz) {
@@ -2519,7 +2374,7 @@
 
     status_t status = AudioSystem::setAssistantServicesUids(nativeUidsVector);
 
-    return (jint)nativeToJavaStatus(status);
+    return nativeToJavaStatus(status);
 }
 
 static jint android_media_AudioSystem_setActiveAssistantServicesUids(JNIEnv *env, jobject thiz,
@@ -2528,7 +2383,7 @@
 
     status_t status = AudioSystem::setActiveAssistantServicesUids(nativeActiveUidsVector);
 
-    return (jint)nativeToJavaStatus(status);
+    return nativeToJavaStatus(status);
 }
 
 static jint
@@ -2536,12 +2391,12 @@
     std::vector<uid_t> nativeUidsVector = convertJIntArrayToUidVector(env, uids);
 
     status_t status = AudioSystem::setA11yServicesUids(nativeUidsVector);
-    return (jint)nativeToJavaStatus(status);
+    return nativeToJavaStatus(status);
 }
 
 static jint android_media_AudioSystem_setCurrentImeUid(JNIEnv *env, jobject thiz, jint uid) {
     status_t status = AudioSystem::setCurrentImeUid(uid);
-    return (jint)nativeToJavaStatus(status);
+    return nativeToJavaStatus(status);
 }
 
 static jboolean
@@ -2559,7 +2414,7 @@
     std::vector<audio_usage_t> nativeSystemUsagesVector;
 
     if (systemUsages == nullptr) {
-        return (jint) AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     int *nativeSystemUsages = nullptr;
@@ -2576,7 +2431,7 @@
     }
 
     status_t status = AudioSystem::setSupportedSystemUsages(nativeSystemUsagesVector);
-    return (jint)nativeToJavaStatus(status);
+    return nativeToJavaStatus(status);
 }
 
 static jint
@@ -2587,16 +2442,16 @@
 static jint
 android_media_AudioSystem_setRttEnabled(JNIEnv *env, jobject thiz, jboolean enabled)
 {
-    return (jint) check_AudioSystem_Command(AudioSystem::setRttEnabled(enabled));
+    return check_AudioSystem_Command(AudioSystem::setRttEnabled(enabled));
 }
 
 static jint
 android_media_AudioSystem_setAudioHalPids(JNIEnv *env, jobject clazz, jintArray jPids)
 {
     if (jPids == NULL) {
-        return (jint) AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
-    pid_t *nPidsArray = (pid_t *) env->GetIntArrayElements(jPids, NULL);
+    pid_t *nPidsArray = reinterpret_cast<pid_t *>(env->GetIntArrayElements(jPids, nullptr));
     std::vector<pid_t> nPids(nPidsArray, nPidsArray + env->GetArrayLength(jPids));
     status_t status = AudioSystem::setAudioHalPids(nPids);
     env->ReleaseIntArrayElements(jPids, nPidsArray, 0);
@@ -2620,19 +2475,17 @@
         return results;
     }
     int status = check_AudioSystem_Command(
-            AudioSystem::setDevicesRoleForStrategy((product_strategy_t)strategy,
-                                                   (device_role_t)role, nDevices));
-    return (jint) status;
+            AudioSystem::setDevicesRoleForStrategy(static_cast<product_strategy_t>(strategy),
+                                                   static_cast<device_role_t>(role), nDevices));
+    return status;
 }
 
 static jint android_media_AudioSystem_removeDevicesRoleForStrategy(JNIEnv *env, jobject thiz,
                                                                    jint strategy, jint role) {
-    return (jint)
-            check_AudioSystem_Command(AudioSystem::removeDevicesRoleForStrategy((product_strategy_t)
-                                                                                        strategy,
-                                                                                (device_role_t)
-                                                                                        role),
-                                      {NAME_NOT_FOUND});
+    return check_AudioSystem_Command(
+            AudioSystem::removeDevicesRoleForStrategy(static_cast<product_strategy_t>(strategy),
+                                                      static_cast<device_role_t>(role)),
+            {NAME_NOT_FOUND});
 }
 
 static jint android_media_AudioSystem_getDevicesForRoleAndStrategy(JNIEnv *env, jobject thiz,
@@ -2640,10 +2493,10 @@
                                                                    jobject jDevices) {
     AudioDeviceTypeAddrVector nDevices;
     status_t status = check_AudioSystem_Command(
-            AudioSystem::getDevicesForRoleAndStrategy((product_strategy_t)strategy,
-                                                      (device_role_t)role, nDevices));
+            AudioSystem::getDevicesForRoleAndStrategy(static_cast<product_strategy_t>(strategy),
+                                                      static_cast<device_role_t>(role), nDevices));
     if (status != NO_ERROR) {
-        return (jint) status;
+        return status;
     }
     for (const auto &device : nDevices) {
         jobject jAudioDeviceAttributes = NULL;
@@ -2666,9 +2519,10 @@
         return results;
     }
     int status = check_AudioSystem_Command(
-            AudioSystem::setDevicesRoleForCapturePreset((audio_source_t)capturePreset,
-                                                        (device_role_t)role, nDevices));
-    return (jint)status;
+            AudioSystem::setDevicesRoleForCapturePreset(static_cast<audio_source_t>(capturePreset),
+                                                        static_cast<device_role_t>(role),
+                                                        nDevices));
+    return status;
 }
 
 static jint android_media_AudioSystem_addDevicesRoleForCapturePreset(
@@ -2680,9 +2534,10 @@
         return results;
     }
     int status = check_AudioSystem_Command(
-            AudioSystem::addDevicesRoleForCapturePreset((audio_source_t)capturePreset,
-                                                        (device_role_t)role, nDevices));
-    return (jint)status;
+            AudioSystem::addDevicesRoleForCapturePreset(static_cast<audio_source_t>(capturePreset),
+                                                        static_cast<device_role_t>(role),
+                                                        nDevices));
+    return status;
 }
 
 static jint android_media_AudioSystem_removeDevicesRoleForCapturePreset(
@@ -2694,17 +2549,20 @@
         return results;
     }
     int status = check_AudioSystem_Command(
-            AudioSystem::removeDevicesRoleForCapturePreset((audio_source_t)capturePreset,
-                                                           (device_role_t)role, nDevices));
-    return (jint)status;
+            AudioSystem::removeDevicesRoleForCapturePreset(static_cast<audio_source_t>(
+                                                                   capturePreset),
+                                                           static_cast<device_role_t>(role),
+                                                           nDevices));
+    return status;
 }
 
 static jint android_media_AudioSystem_clearDevicesRoleForCapturePreset(JNIEnv *env, jobject thiz,
                                                                        jint capturePreset,
                                                                        jint role) {
-    return (jint)check_AudioSystem_Command(
-            AudioSystem::clearDevicesRoleForCapturePreset((audio_source_t)capturePreset,
-                                                          (device_role_t)role));
+    return static_cast<jint>(check_AudioSystem_Command(
+            AudioSystem::clearDevicesRoleForCapturePreset(static_cast<audio_source_t>(
+                                                                  capturePreset),
+                                                          static_cast<device_role_t>(role))));
 }
 
 static jint android_media_AudioSystem_getDevicesForRoleAndCapturePreset(JNIEnv *env, jobject thiz,
@@ -2713,10 +2571,12 @@
                                                                         jobject jDevices) {
     AudioDeviceTypeAddrVector nDevices;
     status_t status = check_AudioSystem_Command(
-            AudioSystem::getDevicesForRoleAndCapturePreset((audio_source_t)capturePreset,
-                                                           (device_role_t)role, nDevices));
+            AudioSystem::getDevicesForRoleAndCapturePreset(static_cast<audio_source_t>(
+                                                                   capturePreset),
+                                                           static_cast<device_role_t>(role),
+                                                           nDevices));
     if (status != NO_ERROR) {
-        return (jint)status;
+        return status;
     }
     for (const auto &device : nDevices) {
         jobject jAudioDeviceAttributes = NULL;
@@ -2741,12 +2601,12 @@
     // components call this method often
     if (jDeviceArray == nullptr || maxResultSize == 0) {
         ALOGE("%s invalid array to store AudioDeviceAttributes", __FUNCTION__);
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
     jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
-    if (jStatus != (jint) AUDIO_JAVA_SUCCESS) {
+    if (jStatus != AUDIO_JAVA_SUCCESS) {
         return jStatus;
     }
 
@@ -2775,7 +2635,7 @@
 static jint android_media_AudioSystem_setVibratorInfos(JNIEnv *env, jobject thiz,
                                                        jobject jVibrators) {
     if (!env->IsInstanceOf(jVibrators, gListClass)) {
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     const jint size = env->CallIntMethod(jVibrators, gListMethods.size);
     std::vector<media::AudioVibratorInfo> vibratorInfos;
@@ -2783,7 +2643,7 @@
         ScopedLocalRef<jobject> jVibrator(env,
                                           env->CallObjectMethod(jVibrators, gListMethods.get, i));
         if (!env->IsInstanceOf(jVibrator.get(), gVibratorClass)) {
-            return (jint)AUDIO_JAVA_BAD_VALUE;
+            return AUDIO_JAVA_BAD_VALUE;
         }
         media::AudioVibratorInfo vibratorInfo;
         vibratorInfo.id = env->CallIntMethod(jVibrator.get(), gVibratorMethods.getId);
@@ -2794,7 +2654,7 @@
                 env->CallFloatMethod(jVibrator.get(), gVibratorMethods.getMaxAmplitude);
         vibratorInfos.push_back(vibratorInfo);
     }
-    return (jint)check_AudioSystem_Command(AudioSystem::setVibratorInfos(vibratorInfos));
+    return check_AudioSystem_Command(AudioSystem::setVibratorInfos(vibratorInfos));
 }
 
 static jobject android_media_AudioSystem_getSpatializer(JNIEnv *env, jobject thiz,
@@ -2816,8 +2676,8 @@
                                                        jobjectArray jDeviceArray) {
     JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
     jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
-    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
-       return false;
+    if (jStatus != AUDIO_JAVA_SUCCESS) {
+        return false;
     }
 
     AudioDeviceTypeAddrVector nDevices;
@@ -2830,7 +2690,7 @@
             return false;
         }
         jStatus = createAudioDeviceTypeAddrFromJava(env, &device, jDevice);
-        if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+        if (jStatus != AUDIO_JAVA_SUCCESS) {
             return false;
         }
         nDevices.push_back(device);
@@ -2873,7 +2733,7 @@
                                                                jobject jFormat, jobject jaa) {
     JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
     jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
-    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+    if (jStatus != AUDIO_JAVA_SUCCESS) {
         return DIRECT_NOT_SUPPORTED;
     }
 
@@ -2896,20 +2756,20 @@
 
     if (jAudioAttributes == nullptr) {
         ALOGE("jAudioAttributes is NULL");
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     if (jAudioProfilesList == nullptr) {
         ALOGE("jAudioProfilesList is NULL");
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
     if (!env->IsInstanceOf(jAudioProfilesList, gArrayListClass)) {
         ALOGE("jAudioProfilesList not an ArrayList");
-        return (jint)AUDIO_JAVA_BAD_VALUE;
+        return AUDIO_JAVA_BAD_VALUE;
     }
 
     JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
     jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jAudioAttributes, paa.get());
-    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
+    if (jStatus != AUDIO_JAVA_SUCCESS) {
         return jStatus;
     }
 
@@ -2922,7 +2782,7 @@
     }
 
     for (const auto &audioProfile : audioProfiles) {
-        jobject jAudioProfile;
+        ScopedLocalRef<jobject> jAudioProfile(env);
         jint jConvertProfileStatus = convertAudioProfileFromNative(
                                         env, &jAudioProfile, &audioProfile, false);
         if (jConvertProfileStatus == AUDIO_JAVA_BAD_VALUE) {
@@ -2932,8 +2792,7 @@
         if (jConvertProfileStatus != AUDIO_JAVA_SUCCESS) {
             return jConvertProfileStatus;
         }
-        env->CallBooleanMethod(jAudioProfilesList, gArrayListMethods.add, jAudioProfile);
-        env->DeleteLocalRef(jAudioProfile);
+        env->CallBooleanMethod(jAudioProfilesList, gArrayListMethods.add, jAudioProfile.get());
     }
     return jStatus;
 }
@@ -2949,8 +2808,7 @@
 
 static int android_media_AudioSystem_setBluetoothVariableLatencyEnabled(JNIEnv *env, jobject thiz,
                                                                         jboolean enabled) {
-    return (jint)check_AudioSystem_Command(
-            AudioSystem::setBluetoothVariableLatencyEnabled(enabled));
+    return check_AudioSystem_Command(AudioSystem::setBluetoothVariableLatencyEnabled(enabled));
 }
 
 static jboolean android_media_AudioSystem_isBluetoothVariableLatencyEnabled(JNIEnv *env,
@@ -2964,178 +2822,165 @@
 
 // ----------------------------------------------------------------------------
 
+#define MAKE_AUDIO_SYSTEM_METHOD(x) \
+    MAKE_JNI_NATIVE_METHOD_AUTOSIG(#x, android_media_AudioSystem_##x)
+
 static const JNINativeMethod gMethods[] =
-        {{"setParameters", "(Ljava/lang/String;)I",
-          (void *)android_media_AudioSystem_setParameters},
-         {"getParameters", "(Ljava/lang/String;)Ljava/lang/String;",
-          (void *)android_media_AudioSystem_getParameters},
-         {"muteMicrophone", "(Z)I", (void *)android_media_AudioSystem_muteMicrophone},
-         {"isMicrophoneMuted", "()Z", (void *)android_media_AudioSystem_isMicrophoneMuted},
-         {"isStreamActive", "(II)Z", (void *)android_media_AudioSystem_isStreamActive},
-         {"isStreamActiveRemotely", "(II)Z",
-          (void *)android_media_AudioSystem_isStreamActiveRemotely},
-         {"isSourceActive", "(I)Z", (void *)android_media_AudioSystem_isSourceActive},
-         {"newAudioSessionId", "()I", (void *)android_media_AudioSystem_newAudioSessionId},
-         {"newAudioPlayerId", "()I", (void *)android_media_AudioSystem_newAudioPlayerId},
-         {"newAudioRecorderId", "()I", (void *)android_media_AudioSystem_newAudioRecorderId},
-         {"setDeviceConnectionState", "(ILandroid/os/Parcel;I)I",
-          (void *)android_media_AudioSystem_setDeviceConnectionState},
-         {"getDeviceConnectionState", "(ILjava/lang/String;)I",
-          (void *)android_media_AudioSystem_getDeviceConnectionState},
-         {"handleDeviceConfigChange", "(ILjava/lang/String;Ljava/lang/String;I)I",
-          (void *)android_media_AudioSystem_handleDeviceConfigChange},
-         {"setPhoneState", "(II)I", (void *)android_media_AudioSystem_setPhoneState},
-         {"setForceUse", "(II)I", (void *)android_media_AudioSystem_setForceUse},
-         {"getForceUse", "(I)I", (void *)android_media_AudioSystem_getForceUse},
-         {"initStreamVolume", "(III)I", (void *)android_media_AudioSystem_initStreamVolume},
-         {"setStreamVolumeIndex", "(III)I", (void *)android_media_AudioSystem_setStreamVolumeIndex},
-         {"getStreamVolumeIndex", "(II)I", (void *)android_media_AudioSystem_getStreamVolumeIndex},
-         {"setVolumeIndexForAttributes", "(Landroid/media/AudioAttributes;II)I",
-          (void *)android_media_AudioSystem_setVolumeIndexForAttributes},
-         {"getVolumeIndexForAttributes", "(Landroid/media/AudioAttributes;I)I",
-          (void *)android_media_AudioSystem_getVolumeIndexForAttributes},
-         {"getMinVolumeIndexForAttributes", "(Landroid/media/AudioAttributes;)I",
-          (void *)android_media_AudioSystem_getMinVolumeIndexForAttributes},
-         {"getMaxVolumeIndexForAttributes", "(Landroid/media/AudioAttributes;)I",
-          (void *)android_media_AudioSystem_getMaxVolumeIndexForAttributes},
-         {"setMasterVolume", "(F)I", (void *)android_media_AudioSystem_setMasterVolume},
-         {"getMasterVolume", "()F", (void *)android_media_AudioSystem_getMasterVolume},
-         {"setMasterMute", "(Z)I", (void *)android_media_AudioSystem_setMasterMute},
-         {"getMasterMute", "()Z", (void *)android_media_AudioSystem_getMasterMute},
-         {"setMasterMono", "(Z)I", (void *)android_media_AudioSystem_setMasterMono},
-         {"getMasterMono", "()Z", (void *)android_media_AudioSystem_getMasterMono},
-         {"setMasterBalance", "(F)I", (void *)android_media_AudioSystem_setMasterBalance},
-         {"getMasterBalance", "()F", (void *)android_media_AudioSystem_getMasterBalance},
-         {"getPrimaryOutputSamplingRate", "()I",
-          (void *)android_media_AudioSystem_getPrimaryOutputSamplingRate},
-         {"getPrimaryOutputFrameCount", "()I",
-          (void *)android_media_AudioSystem_getPrimaryOutputFrameCount},
-         {"getOutputLatency", "(I)I", (void *)android_media_AudioSystem_getOutputLatency},
-         {"setLowRamDevice", "(ZJ)I", (void *)android_media_AudioSystem_setLowRamDevice},
-         {"checkAudioFlinger", "()I", (void *)android_media_AudioSystem_checkAudioFlinger},
-         {"setAudioFlingerBinder", "(Landroid/os/IBinder;)V",
-          (void *)android_media_AudioSystem_setAudioFlingerBinder},
-         {"listAudioPorts", "(Ljava/util/ArrayList;[I)I",
-          (void *)android_media_AudioSystem_listAudioPorts},
-         {"createAudioPatch",
-          "([Landroid/media/AudioPatch;[Landroid/media/AudioPortConfig;[Landroid/media/"
-          "AudioPortConfig;)I",
-          (void *)android_media_AudioSystem_createAudioPatch},
-         {"releaseAudioPatch", "(Landroid/media/AudioPatch;)I",
-          (void *)android_media_AudioSystem_releaseAudioPatch},
-         {"listAudioPatches", "(Ljava/util/ArrayList;[I)I",
-          (void *)android_media_AudioSystem_listAudioPatches},
-         {"setAudioPortConfig", "(Landroid/media/AudioPortConfig;)I",
-          (void *)android_media_AudioSystem_setAudioPortConfig},
-         {"startAudioSource", "(Landroid/media/AudioPortConfig;Landroid/media/AudioAttributes;)I",
-          (void *)android_media_AudioSystem_startAudioSource},
-         {"stopAudioSource", "(I)I", (void *)android_media_AudioSystem_stopAudioSource},
-         {"getAudioHwSyncForSession", "(I)I",
-          (void *)android_media_AudioSystem_getAudioHwSyncForSession},
-         {"registerPolicyMixes", "(Ljava/util/ArrayList;Z)I",
-          (void *)android_media_AudioSystem_registerPolicyMixes},
-         {"setUidDeviceAffinities", "(I[I[Ljava/lang/String;)I",
-          (void *)android_media_AudioSystem_setUidDeviceAffinities},
-         {"removeUidDeviceAffinities", "(I)I",
-          (void *)android_media_AudioSystem_removeUidDeviceAffinities},
-         {"native_register_dynamic_policy_callback", "()V",
-          (void *)android_media_AudioSystem_registerDynPolicyCallback},
-         {"native_register_recording_callback", "()V",
-          (void *)android_media_AudioSystem_registerRecordingCallback},
-         {"native_register_routing_callback", "()V",
-          (void *)android_media_AudioSystem_registerRoutingCallback},
-         {"native_register_vol_range_init_req_callback", "()V",
-          (void *)android_media_AudioSystem_registerVolRangeInitReqCallback},
-         {"systemReady", "()I", (void *)android_media_AudioSystem_systemReady},
-         {"getStreamVolumeDB", "(III)F", (void *)android_media_AudioSystem_getStreamVolumeDB},
-         {"native_get_offload_support", "(IIIII)I",
-          (void *)android_media_AudioSystem_getOffloadSupport},
-         {"getMicrophones", "(Ljava/util/ArrayList;)I",
-          (void *)android_media_AudioSystem_getMicrophones},
-         {"getSurroundFormats", "(Ljava/util/Map;)I",
-          (void *)android_media_AudioSystem_getSurroundFormats},
-         {"getReportedSurroundFormats", "(Ljava/util/ArrayList;)I",
-          (void *)android_media_AudioSystem_getReportedSurroundFormats},
-         {"setSurroundFormatEnabled", "(IZ)I",
-          (void *)android_media_AudioSystem_setSurroundFormatEnabled},
-         {"setAssistantServicesUids", "([I)I",
-          (void *)android_media_AudioSystem_setAssistantServicesUids},
-         {"setActiveAssistantServicesUids", "([I)I",
-          (void *)android_media_AudioSystem_setActiveAssistantServicesUids},
-         {"setA11yServicesUids", "([I)I", (void *)android_media_AudioSystem_setA11yServicesUids},
-         {"isHapticPlaybackSupported", "()Z",
-          (void *)android_media_AudioSystem_isHapticPlaybackSupported},
-         {"isUltrasoundSupported", "()Z", (void *)android_media_AudioSystem_isUltrasoundSupported},
-         {"getHwOffloadFormatsSupportedForBluetoothMedia", "(ILjava/util/ArrayList;)I",
-          (void *)android_media_AudioSystem_getHwOffloadFormatsSupportedForBluetoothMedia},
-         {"setSupportedSystemUsages", "([I)I",
-          (void *)android_media_AudioSystem_setSupportedSystemUsages},
-         {"setAllowedCapturePolicy", "(II)I",
-          (void *)android_media_AudioSystem_setAllowedCapturePolicy},
-         {"setRttEnabled", "(Z)I", (void *)android_media_AudioSystem_setRttEnabled},
-         {"setAudioHalPids", "([I)I", (void *)android_media_AudioSystem_setAudioHalPids},
-         {"isCallScreeningModeSupported", "()Z",
-          (void *)android_media_AudioSystem_isCallScreeningModeSupported},
-         {"setDevicesRoleForStrategy", "(II[I[Ljava/lang/String;)I",
-          (void *)android_media_AudioSystem_setDevicesRoleForStrategy},
-         {"removeDevicesRoleForStrategy", "(II)I",
-          (void *)android_media_AudioSystem_removeDevicesRoleForStrategy},
-         {"getDevicesForRoleAndStrategy", "(IILjava/util/List;)I",
-          (void *)android_media_AudioSystem_getDevicesForRoleAndStrategy},
-         {"setDevicesRoleForCapturePreset", "(II[I[Ljava/lang/String;)I",
-          (void *)android_media_AudioSystem_setDevicesRoleForCapturePreset},
-         {"addDevicesRoleForCapturePreset", "(II[I[Ljava/lang/String;)I",
-          (void *)android_media_AudioSystem_addDevicesRoleForCapturePreset},
-         {"removeDevicesRoleForCapturePreset", "(II[I[Ljava/lang/String;)I",
-          (void *)android_media_AudioSystem_removeDevicesRoleForCapturePreset},
-         {"clearDevicesRoleForCapturePreset", "(II)I",
-          (void *)android_media_AudioSystem_clearDevicesRoleForCapturePreset},
-         {"getDevicesForRoleAndCapturePreset", "(IILjava/util/List;)I",
-          (void *)android_media_AudioSystem_getDevicesForRoleAndCapturePreset},
-         {"getDevicesForAttributes",
-          "(Landroid/media/AudioAttributes;[Landroid/media/AudioDeviceAttributes;Z)I",
-          (void *)android_media_AudioSystem_getDevicesForAttributes},
-         {"setUserIdDeviceAffinities", "(I[I[Ljava/lang/String;)I",
-          (void *)android_media_AudioSystem_setUserIdDeviceAffinities},
-         {"removeUserIdDeviceAffinities", "(I)I",
-          (void *)android_media_AudioSystem_removeUserIdDeviceAffinities},
-         {"setCurrentImeUid", "(I)I", (void *)android_media_AudioSystem_setCurrentImeUid},
-         {"setVibratorInfos", "(Ljava/util/List;)I",
-          (void *)android_media_AudioSystem_setVibratorInfos},
-         {"nativeGetSpatializer",
-          "(Landroid/media/INativeSpatializerCallback;)Landroid/os/IBinder;",
-          (void *)android_media_AudioSystem_getSpatializer},
-         {"canBeSpatialized",
-          "(Landroid/media/AudioAttributes;Landroid/media/AudioFormat;"
-          "[Landroid/media/AudioDeviceAttributes;)Z",
-          (void *)android_media_AudioSystem_canBeSpatialized},
-         {"getDirectPlaybackSupport",
-          "(Landroid/media/AudioFormat;Landroid/media/AudioAttributes;)I",
-          (void *)android_media_AudioSystem_getDirectPlaybackSupport},
-         {"getDirectProfilesForAttributes",
-          "(Landroid/media/AudioAttributes;Ljava/util/ArrayList;)I",
-          (void *)android_media_AudioSystem_getDirectProfilesForAttributes},
-         {"supportsBluetoothVariableLatency", "()Z",
-          (void *)android_media_AudioSystem_supportsBluetoothVariableLatency},
-         {"setBluetoothVariableLatencyEnabled", "(Z)I",
-          (void *)android_media_AudioSystem_setBluetoothVariableLatencyEnabled},
-         {"isBluetoothVariableLatencyEnabled", "()Z",
-          (void *)android_media_AudioSystem_isBluetoothVariableLatencyEnabled}};
+        {MAKE_AUDIO_SYSTEM_METHOD(setParameters),
+         MAKE_AUDIO_SYSTEM_METHOD(getParameters),
+         MAKE_AUDIO_SYSTEM_METHOD(muteMicrophone),
+         MAKE_AUDIO_SYSTEM_METHOD(isMicrophoneMuted),
+         MAKE_AUDIO_SYSTEM_METHOD(isStreamActive),
+         MAKE_AUDIO_SYSTEM_METHOD(isStreamActiveRemotely),
+         MAKE_AUDIO_SYSTEM_METHOD(isSourceActive),
+         MAKE_AUDIO_SYSTEM_METHOD(newAudioSessionId),
+         MAKE_AUDIO_SYSTEM_METHOD(newAudioPlayerId),
+         MAKE_AUDIO_SYSTEM_METHOD(newAudioRecorderId),
+         MAKE_JNI_NATIVE_METHOD("setDeviceConnectionState", "(ILandroid/os/Parcel;I)I",
+                                android_media_AudioSystem_setDeviceConnectionState),
+         MAKE_AUDIO_SYSTEM_METHOD(getDeviceConnectionState),
+         MAKE_AUDIO_SYSTEM_METHOD(handleDeviceConfigChange),
+         MAKE_AUDIO_SYSTEM_METHOD(setPhoneState),
+         MAKE_AUDIO_SYSTEM_METHOD(setForceUse),
+         MAKE_AUDIO_SYSTEM_METHOD(getForceUse),
+         MAKE_AUDIO_SYSTEM_METHOD(initStreamVolume),
+         MAKE_AUDIO_SYSTEM_METHOD(setStreamVolumeIndex),
+         MAKE_AUDIO_SYSTEM_METHOD(getStreamVolumeIndex),
+         MAKE_JNI_NATIVE_METHOD("setVolumeIndexForAttributes",
+                                "(Landroid/media/AudioAttributes;II)I",
+                                android_media_AudioSystem_setVolumeIndexForAttributes),
+         MAKE_JNI_NATIVE_METHOD("getVolumeIndexForAttributes",
+                                "(Landroid/media/AudioAttributes;I)I",
+                                android_media_AudioSystem_getVolumeIndexForAttributes),
+         MAKE_JNI_NATIVE_METHOD("getMinVolumeIndexForAttributes",
+                                "(Landroid/media/AudioAttributes;)I",
+                                android_media_AudioSystem_getMinVolumeIndexForAttributes),
+         MAKE_JNI_NATIVE_METHOD("getMaxVolumeIndexForAttributes",
+                                "(Landroid/media/AudioAttributes;)I",
+                                android_media_AudioSystem_getMaxVolumeIndexForAttributes),
+         MAKE_AUDIO_SYSTEM_METHOD(setMasterVolume),
+         MAKE_AUDIO_SYSTEM_METHOD(getMasterVolume),
+         MAKE_AUDIO_SYSTEM_METHOD(setMasterMute),
+         MAKE_AUDIO_SYSTEM_METHOD(getMasterMute),
+         MAKE_AUDIO_SYSTEM_METHOD(setMasterMono),
+         MAKE_AUDIO_SYSTEM_METHOD(getMasterMono),
+         MAKE_AUDIO_SYSTEM_METHOD(setMasterBalance),
+         MAKE_AUDIO_SYSTEM_METHOD(getMasterBalance),
+         MAKE_AUDIO_SYSTEM_METHOD(getPrimaryOutputSamplingRate),
+         MAKE_AUDIO_SYSTEM_METHOD(getPrimaryOutputFrameCount),
+         MAKE_AUDIO_SYSTEM_METHOD(getOutputLatency),
+         MAKE_AUDIO_SYSTEM_METHOD(setLowRamDevice),
+         MAKE_AUDIO_SYSTEM_METHOD(checkAudioFlinger),
+         MAKE_JNI_NATIVE_METHOD("setAudioFlingerBinder", "(Landroid/os/IBinder;)V",
+                                android_media_AudioSystem_setAudioFlingerBinder),
+         MAKE_JNI_NATIVE_METHOD("listAudioPorts", "(Ljava/util/ArrayList;[I)I",
+                                android_media_AudioSystem_listAudioPorts),
+         MAKE_JNI_NATIVE_METHOD("createAudioPatch",
+                                "([Landroid/media/AudioPatch;[Landroid/media/"
+                                "AudioPortConfig;[Landroid/media/AudioPortConfig;)I",
+                                android_media_AudioSystem_createAudioPatch),
+         MAKE_JNI_NATIVE_METHOD("releaseAudioPatch", "(Landroid/media/AudioPatch;)I",
+                                android_media_AudioSystem_releaseAudioPatch),
+         MAKE_JNI_NATIVE_METHOD("listAudioPatches", "(Ljava/util/ArrayList;[I)I",
+                                android_media_AudioSystem_listAudioPatches),
+         MAKE_JNI_NATIVE_METHOD("setAudioPortConfig", "(Landroid/media/AudioPortConfig;)I",
+                                android_media_AudioSystem_setAudioPortConfig),
+         MAKE_JNI_NATIVE_METHOD("startAudioSource",
+                                "(Landroid/media/AudioPortConfig;Landroid/media/AudioAttributes;)I",
+                                android_media_AudioSystem_startAudioSource),
+         MAKE_AUDIO_SYSTEM_METHOD(stopAudioSource),
+         MAKE_AUDIO_SYSTEM_METHOD(getAudioHwSyncForSession),
+         MAKE_JNI_NATIVE_METHOD("registerPolicyMixes", "(Ljava/util/ArrayList;Z)I",
+                                android_media_AudioSystem_registerPolicyMixes),
+         MAKE_JNI_NATIVE_METHOD("setUidDeviceAffinities", "(I[I[Ljava/lang/String;)I",
+                                android_media_AudioSystem_setUidDeviceAffinities),
+         MAKE_AUDIO_SYSTEM_METHOD(removeUidDeviceAffinities),
+         MAKE_JNI_NATIVE_METHOD_AUTOSIG("native_register_dynamic_policy_callback",
+                                        android_media_AudioSystem_registerDynPolicyCallback),
+         MAKE_JNI_NATIVE_METHOD_AUTOSIG("native_register_recording_callback",
+                                        android_media_AudioSystem_registerRecordingCallback),
+         MAKE_JNI_NATIVE_METHOD_AUTOSIG("native_register_routing_callback",
+                                        android_media_AudioSystem_registerRoutingCallback),
+         MAKE_JNI_NATIVE_METHOD_AUTOSIG("native_register_vol_range_init_req_callback",
+                                        android_media_AudioSystem_registerVolRangeInitReqCallback),
+         MAKE_AUDIO_SYSTEM_METHOD(systemReady),
+         MAKE_AUDIO_SYSTEM_METHOD(getStreamVolumeDB),
+         MAKE_JNI_NATIVE_METHOD_AUTOSIG("native_get_offload_support",
+                                        android_media_AudioSystem_getOffloadSupport),
+         MAKE_JNI_NATIVE_METHOD("getMicrophones", "(Ljava/util/ArrayList;)I",
+                                android_media_AudioSystem_getMicrophones),
+         MAKE_JNI_NATIVE_METHOD("getSurroundFormats", "(Ljava/util/Map;)I",
+                                android_media_AudioSystem_getSurroundFormats),
+         MAKE_JNI_NATIVE_METHOD("getReportedSurroundFormats", "(Ljava/util/ArrayList;)I",
+                                android_media_AudioSystem_getReportedSurroundFormats),
+         MAKE_AUDIO_SYSTEM_METHOD(setSurroundFormatEnabled),
+         MAKE_AUDIO_SYSTEM_METHOD(setAssistantServicesUids),
+         MAKE_AUDIO_SYSTEM_METHOD(setActiveAssistantServicesUids),
+         MAKE_AUDIO_SYSTEM_METHOD(setA11yServicesUids),
+         MAKE_AUDIO_SYSTEM_METHOD(isHapticPlaybackSupported),
+         MAKE_AUDIO_SYSTEM_METHOD(isUltrasoundSupported),
+         MAKE_JNI_NATIVE_METHOD(
+                 "getHwOffloadFormatsSupportedForBluetoothMedia", "(ILjava/util/ArrayList;)I",
+                 android_media_AudioSystem_getHwOffloadFormatsSupportedForBluetoothMedia),
+         MAKE_AUDIO_SYSTEM_METHOD(setSupportedSystemUsages),
+         MAKE_AUDIO_SYSTEM_METHOD(setAllowedCapturePolicy),
+         MAKE_AUDIO_SYSTEM_METHOD(setRttEnabled),
+         MAKE_AUDIO_SYSTEM_METHOD(setAudioHalPids),
+         MAKE_AUDIO_SYSTEM_METHOD(isCallScreeningModeSupported),
+         MAKE_JNI_NATIVE_METHOD("setDevicesRoleForStrategy", "(II[I[Ljava/lang/String;)I",
+                                android_media_AudioSystem_setDevicesRoleForStrategy),
+         MAKE_AUDIO_SYSTEM_METHOD(removeDevicesRoleForStrategy),
+         MAKE_JNI_NATIVE_METHOD("getDevicesForRoleAndStrategy", "(IILjava/util/List;)I",
+                                android_media_AudioSystem_getDevicesForRoleAndStrategy),
+         MAKE_JNI_NATIVE_METHOD("setDevicesRoleForCapturePreset", "(II[I[Ljava/lang/String;)I",
+                                android_media_AudioSystem_setDevicesRoleForCapturePreset),
+         MAKE_JNI_NATIVE_METHOD("addDevicesRoleForCapturePreset", "(II[I[Ljava/lang/String;)I",
+                                android_media_AudioSystem_addDevicesRoleForCapturePreset),
+         MAKE_JNI_NATIVE_METHOD("removeDevicesRoleForCapturePreset", "(II[I[Ljava/lang/String;)I",
+                                android_media_AudioSystem_removeDevicesRoleForCapturePreset),
+         MAKE_AUDIO_SYSTEM_METHOD(clearDevicesRoleForCapturePreset),
+         MAKE_JNI_NATIVE_METHOD("getDevicesForRoleAndCapturePreset", "(IILjava/util/List;)I",
+                                android_media_AudioSystem_getDevicesForRoleAndCapturePreset),
+         MAKE_JNI_NATIVE_METHOD("getDevicesForAttributes",
+                                "(Landroid/media/AudioAttributes;[Landroid/media/"
+                                "AudioDeviceAttributes;Z)I",
+                                android_media_AudioSystem_getDevicesForAttributes),
+         MAKE_JNI_NATIVE_METHOD("setUserIdDeviceAffinities", "(I[I[Ljava/lang/String;)I",
+                                android_media_AudioSystem_setUserIdDeviceAffinities),
+         MAKE_AUDIO_SYSTEM_METHOD(removeUserIdDeviceAffinities),
+         MAKE_AUDIO_SYSTEM_METHOD(setCurrentImeUid),
+         MAKE_JNI_NATIVE_METHOD("setVibratorInfos", "(Ljava/util/List;)I",
+                                android_media_AudioSystem_setVibratorInfos),
+         MAKE_JNI_NATIVE_METHOD("nativeGetSpatializer",
+                                "(Landroid/media/INativeSpatializerCallback;)Landroid/os/IBinder;",
+                                android_media_AudioSystem_getSpatializer),
+         MAKE_JNI_NATIVE_METHOD("canBeSpatialized",
+                                "(Landroid/media/AudioAttributes;Landroid/media/AudioFormat;"
+                                "[Landroid/media/AudioDeviceAttributes;)Z",
+                                android_media_AudioSystem_canBeSpatialized),
+         MAKE_JNI_NATIVE_METHOD("getDirectPlaybackSupport",
+                                "(Landroid/media/AudioFormat;Landroid/media/AudioAttributes;)I",
+                                android_media_AudioSystem_getDirectPlaybackSupport),
+         MAKE_JNI_NATIVE_METHOD("getDirectProfilesForAttributes",
+                                "(Landroid/media/AudioAttributes;Ljava/util/ArrayList;)I",
+                                android_media_AudioSystem_getDirectProfilesForAttributes),
+         MAKE_AUDIO_SYSTEM_METHOD(supportsBluetoothVariableLatency),
+         MAKE_AUDIO_SYSTEM_METHOD(setBluetoothVariableLatencyEnabled),
+         MAKE_AUDIO_SYSTEM_METHOD(isBluetoothVariableLatencyEnabled)};
 
-static const JNINativeMethod gEventHandlerMethods[] = {
-    {"native_setup",
-        "(Ljava/lang/Object;)V",
-        (void *)android_media_AudioSystem_eventHandlerSetup},
-    {"native_finalize",
-        "()V",
-        (void *)android_media_AudioSystem_eventHandlerFinalize},
-};
+static const JNINativeMethod gEventHandlerMethods[] =
+        {MAKE_JNI_NATIVE_METHOD("native_setup", "(Ljava/lang/Object;)V",
+                                android_media_AudioSystem_eventHandlerSetup),
+         MAKE_JNI_NATIVE_METHOD_AUTOSIG("native_finalize",
+                                        android_media_AudioSystem_eventHandlerFinalize)};
 
-static const JNINativeMethod gFrameworkCapabilities[] = {
-        {"native_getMaxChannelCount", "()I", (void *)android_media_AudioSystem_getMaxChannelCount},
-        {"native_getMaxSampleRate", "()I", (void *)android_media_AudioSystem_getMaxSampleRate},
-        {"native_getMinSampleRate", "()I", (void *)android_media_AudioSystem_getMinSampleRate},
-};
+static const JNINativeMethod gFrameworkCapabilities[] =
+        {MAKE_JNI_NATIVE_METHOD_AUTOSIG("native_getMaxChannelCount",
+                                        android_media_AudioSystem_getMaxChannelCount),
+         MAKE_JNI_NATIVE_METHOD_AUTOSIG("native_getMaxSampleRate",
+                                        android_media_AudioSystem_getMaxSampleRate),
+         MAKE_JNI_NATIVE_METHOD_AUTOSIG("native_getMinSampleRate",
+                                        android_media_AudioSystem_getMinSampleRate)};
 
 int register_android_media_AudioSystem(JNIEnv *env)
 {
@@ -3310,7 +3155,7 @@
     gClsAudioTrackRoutingProxy =
             android::FindClassOrDie(env, "android/media/AudioTrackRoutingProxy");
     // make sure this reference doesn't get deleted
-    gClsAudioTrackRoutingProxy = (jclass)env->NewGlobalRef(gClsAudioTrackRoutingProxy);
+    gClsAudioTrackRoutingProxy = static_cast<jclass>(env->NewGlobalRef(gClsAudioTrackRoutingProxy));
 
     gMidAudioTrackRoutingProxy_ctor =
             android::GetMethodIDOrDie(env, gClsAudioTrackRoutingProxy, "<init>", "(J)V");
@@ -3321,7 +3166,8 @@
     gClsAudioRecordRoutingProxy =
             android::FindClassOrDie(env, "android/media/AudioRecordRoutingProxy");
     // make sure this reference doesn't get deleted
-    gClsAudioRecordRoutingProxy = (jclass)env->NewGlobalRef(gClsAudioRecordRoutingProxy);
+    gClsAudioRecordRoutingProxy =
+            static_cast<jclass>(env->NewGlobalRef(gClsAudioRecordRoutingProxy));
 
     gMidAudioRecordRoutingProxy_ctor =
             android::GetMethodIDOrDie(env, gClsAudioRecordRoutingProxy, "<init>", "(J)V");
diff --git a/core/jni/android_os_HwParcel.cpp b/core/jni/android_os_HwParcel.cpp
index 4c4443f..0e3c510 100644
--- a/core/jni/android_os_HwParcel.cpp
+++ b/core/jni/android_os_HwParcel.cpp
@@ -285,7 +285,7 @@
         hardware::Parcel *parcel =
             JHwParcel::GetNativeContext(env, thiz)->getParcel();
 
-        status_t err = parcel->writeInterfaceToken(nameCopy.string());
+        status_t err = parcel->writeInterfaceToken(nameCopy.c_str());
         signalExceptionForError(env, err);
     }
 }
@@ -687,9 +687,7 @@
 static jstring MakeStringObjFromHidlString(JNIEnv *env, const hidl_string &s) {
     String16 utf16String(s.c_str(), s.size());
 
-    return env->NewString(
-            reinterpret_cast<const jchar *>(utf16String.string()),
-            utf16String.size());
+    return env->NewString(reinterpret_cast<const jchar *>(utf16String.c_str()), utf16String.size());
 }
 
 static jstring JHwParcel_native_readString(JNIEnv *env, jobject thiz) {
diff --git a/core/jni/android_os_UEventObserver.cpp b/core/jni/android_os_UEventObserver.cpp
index 2df74b0..43a8be1 100644
--- a/core/jni/android_os_UEventObserver.cpp
+++ b/core/jni/android_os_UEventObserver.cpp
@@ -51,8 +51,8 @@
         const char* field = buffer;
         const char* end = buffer + length + 1;
         do {
-            if (strstr(field, match.string())) {
-                ALOGV("Matched uevent message with pattern: %s", match.string());
+            if (strstr(field, match.c_str())) {
+                ALOGV("Matched uevent message with pattern: %s", match.c_str());
                 return true;
             }
             field += strlen(field) + 1;
@@ -71,7 +71,11 @@
         }
         buffer[length] = '\0';
 
-        ALOGV("Received uevent message: %s", buffer);
+        IF_ALOGV() {
+            std::string message(buffer, length);
+            std::replace(message.begin(), message.end(), '\0', ' ');
+            ALOGV("Received uevent message: %s", message.c_str());
+        }
 
         if (isMatch(buffer, length)) {
             // Assume the message is ASCII.
diff --git a/core/jni/android_util_AssetManager.cpp b/core/jni/android_util_AssetManager.cpp
index 206ad17..971848d 100644
--- a/core/jni/android_util_AssetManager.cpp
+++ b/core/jni/android_util_AssetManager.cpp
@@ -272,7 +272,7 @@
   if (alloc.length() <= 0) {
     return nullptr;
   }
-  return env->NewStringUTF(alloc.string());
+  return env->NewStringUTF(alloc.c_str());
 }
 
 static jint NativeGetGlobalAssetManagerCount(JNIEnv* /*env*/, jobject /*clazz*/) {
@@ -427,7 +427,7 @@
   }
 
   for (size_t i = 0; i < file_count; i++) {
-    jstring java_string = env->NewStringUTF(asset_dir->getFileName(i).string());
+    jstring java_string = env->NewStringUTF(asset_dir->getFileName(i).c_str());
 
     // Check for errors creating the strings (if malformed or no memory).
     if (env->ExceptionCheck()) {
diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp
index 8bc52b8..55382cc 100644
--- a/core/jni/android_util_Binder.cpp
+++ b/core/jni/android_util_Binder.cpp
@@ -17,19 +17,8 @@
 #define LOG_TAG "JavaBinder"
 //#define LOG_NDEBUG 0
 
-#include "android_os_Parcel.h"
 #include "android_util_Binder.h"
 
-#include <atomic>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <mutex>
-#include <stdio.h>
-#include <string>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
 #include <android-base/stringprintf.h>
 #include <binder/BpBinder.h>
 #include <binder/IInterface.h>
@@ -40,8 +29,16 @@
 #include <binder/Stability.h>
 #include <binderthreadstate/CallerUtils.h>
 #include <cutils/atomic.h>
-#include <cutils/threads.h>
+#include <fcntl.h>
+#include <inttypes.h>
 #include <log/log.h>
+#include <nativehelper/JNIHelp.h>
+#include <nativehelper/ScopedLocalRef.h>
+#include <nativehelper/ScopedUtfChars.h>
+#include <stdio.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
 #include <utils/KeyedVector.h>
 #include <utils/List.h>
 #include <utils/Log.h>
@@ -49,10 +46,11 @@
 #include <utils/SystemClock.h>
 #include <utils/threads.h>
 
-#include <nativehelper/JNIHelp.h>
-#include <nativehelper/ScopedLocalRef.h>
-#include <nativehelper/ScopedUtfChars.h>
+#include <atomic>
+#include <mutex>
+#include <string>
 
+#include "android_os_Parcel.h"
 #include "core_jni_helpers.h"
 
 //#undef ALOGV
@@ -558,14 +556,48 @@
 };
 
 // ----------------------------------------------------------------------------
+#ifdef BINDER_DEATH_RECIPIENT_WEAK_FROM_JNI
+#if __BIONIC__
+#include <android/api-level.h>
+static bool target_sdk_is_at_least_vic() {
+    return android_get_application_target_sdk_version() >= __ANDROID_API_V__;
+}
+#else
+static constexpr bool target_sdk_is_at_least_vic() {
+    // If not built for Android (i.e. glibc host), follow the latest behavior as there's no compat
+    // requirement there.
+    return true;
+}
+#endif // __BIONIC__
+#endif // BINDER_DEATH_RECIPIENT_WEAK_FROM_JNI
 
 class JavaDeathRecipient : public IBinder::DeathRecipient
 {
 public:
     JavaDeathRecipient(JNIEnv* env, jobject object, const sp<DeathRecipientList>& list)
-        : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
-          mObjectWeak(NULL), mList(list)
-    {
+          : mVM(jnienv_to_javavm(env)), mObject(NULL), mObjectWeak(NULL), mList(list) {
+        // b/298374304: For apps targeting Android V or beyond, we no longer hold the global JNI ref
+        // to the death recipient objects. This is to prevent the memory leak which can happen when
+        // the death recipient object internally has a strong reference to the proxy object. Under
+        // the old behavior, you were unable to kill the binder service by dropping all references
+        // to the proxy object - because it is still strong referenced from JNI (here). The only way
+        // to cut the strong reference was to call unlinkDeath(), but it was easy to forget.
+        //
+        // Now, the strong reference to the death recipient is held in the Java-side proxy object.
+        // See BinderProxy.mDeathRecipients. From JNI, only the weak reference is kept. An
+        // implication of this is that you may not receive binderDied() if you drop all references
+        // to the proxy object before the service dies. This should be okay for most cases because
+        // you normally are not interested in the death of a binder service which you don't have any
+        // reference to. If however you want to get binderDied() regardless of the proxy object's
+        // lifecycle, keep a strong reference to the death recipient object by yourself.
+#ifdef BINDER_DEATH_RECIPIENT_WEAK_FROM_JNI
+        if (target_sdk_is_at_least_vic()) {
+            mObjectWeak = env->NewWeakGlobalRef(object);
+        } else
+#endif
+        {
+            mObject = env->NewGlobalRef(object);
+        }
         // These objects manage their own lifetimes so are responsible for final bookkeeping.
         // The list holds a strong reference to this object.
         LOGDEATH("Adding JDR %p to DRL %p", this, list.get());
@@ -578,26 +610,49 @@
     void binderDied(const wp<IBinder>& who)
     {
         LOGDEATH("Receiving binderDied() on JavaDeathRecipient %p\n", this);
-        if (mObject != NULL) {
-            JNIEnv* env = javavm_to_jnienv(mVM);
-            ScopedLocalRef<jobject> jBinderProxy(env, javaObjectForIBinder(env, who.promote()));
-            env->CallStaticVoidMethod(gBinderProxyOffsets.mClass,
-                                      gBinderProxyOffsets.mSendDeathNotice, mObject,
-                                      jBinderProxy.get());
-            if (env->ExceptionCheck()) {
-                jthrowable excep = env->ExceptionOccurred();
-                binder_report_exception(env, excep,
-                                        "*** Uncaught exception returned from death notification!");
-            }
+        if (mObject == NULL && mObjectWeak == NULL) {
+            return;
+        }
+        JNIEnv* env = javavm_to_jnienv(mVM);
+        ScopedLocalRef<jobject> jBinderProxy(env, javaObjectForIBinder(env, who.promote()));
 
-            // Serialize with our containing DeathRecipientList so that we can't
-            // delete the global ref on mObject while the list is being iterated.
+        // Hold a local reference to the recipient. This may fail if the recipient is weakly
+        // referenced, in which case we can't deliver the death notice.
+        ScopedLocalRef<jobject> jRecipient(env,
+                                           env->NewLocalRef(mObject != NULL ? mObject
+                                                                            : mObjectWeak));
+        if (jRecipient.get() == NULL) {
+            ALOGW("Binder died, but death recipient is already garbage collected. If your target "
+                  "sdk level is at or above 35, this can happen when you dropped all references to "
+                  "the binder service before it died. If you want to get a death notice for a "
+                  "binder service which you have no reference to, keep a strong reference to the "
+                  "death recipient by yourself.");
+            return;
+        }
+
+        if (mFired) {
+            ALOGW("Received multiple death notices for the same binder object. Binder driver bug?");
+            return;
+        }
+        mFired = true;
+
+        env->CallStaticVoidMethod(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mSendDeathNotice,
+                                  jRecipient.get(), jBinderProxy.get());
+        if (env->ExceptionCheck()) {
+            jthrowable excep = env->ExceptionOccurred();
+            binder_report_exception(env, excep,
+                                    "*** Uncaught exception returned from death notification!");
+        }
+
+        // Demote from strong ref (if exists) to weak after binderDied() has been delivered, to
+        // allow the DeathRecipient and BinderProxy to be GC'd if no longer needed. Do this in sync
+        // with our containing DeathRecipientList so that we can't delete the global ref on mObject
+        // while the list is being iterated.
+        if (mObject != NULL) {
             sp<DeathRecipientList> list = mList.promote();
             if (list != NULL) {
                 AutoMutex _l(list->lock());
 
-                // Demote from strong ref to weak after binderDied() has been delivered,
-                // to allow the DeathRecipient and BinderProxy to be GC'd if no longer needed.
                 mObjectWeak = env->NewWeakGlobalRef(mObject);
                 env->DeleteGlobalRef(mObject);
                 mObject = NULL;
@@ -664,9 +719,19 @@
 
 private:
     JavaVM* const mVM;
-    jobject mObject;  // Initial strong ref to Java-side DeathRecipient. Cleared on binderDied().
-    jweak mObjectWeak; // Weak ref to the same Java-side DeathRecipient after binderDied().
+
+    // If target sdk version < 35, the Java-side DeathRecipient is strongly referenced from mObject
+    // upon linkToDeath() and then after binderDied() is called, the strong reference is demoted to
+    // a weak reference (mObjectWeak).
+    // If target sdk version >= 35, the strong reference is never made here (i.e. mObject == NULL
+    // always). Instead, the strong reference to the Java-side DeathRecipient is made in
+    // BinderProxy.mDeathRecipients. In the native world, only the weak reference is kept.
+    jobject mObject;
+    jweak mObjectWeak;
     wp<DeathRecipientList> mList;
+
+    // Whether binderDied was called or not.
+    bool mFired = false;
 };
 
 // ----------------------------------------------------------------------------
@@ -954,8 +1019,10 @@
             String8 msg;
             msg.appendFormat("Unknown binder error code. 0x%" PRIx32, err);
             // RemoteException is a checked exception, only throw from certain methods.
-            jniThrowException(env, canThrowRemoteException
-                    ? "android/os/RemoteException" : "java/lang/RuntimeException", msg.string());
+            jniThrowException(env,
+                              canThrowRemoteException ? "android/os/RemoteException"
+                                                      : "java/lang/RuntimeException",
+                              msg.c_str());
             break;
     }
 }
@@ -1287,8 +1354,7 @@
     IBinder* target = getBPNativeData(env, obj)->mObject.get();
     if (target != NULL) {
         const String16& desc = target->getInterfaceDescriptor();
-        return env->NewString(reinterpret_cast<const jchar*>(desc.string()),
-                              desc.size());
+        return env->NewString(reinterpret_cast<const jchar*>(desc.c_str()), desc.size());
     }
     jniThrowException(env, "java/lang/RuntimeException",
             "No binder found for object");
@@ -1305,103 +1371,6 @@
     return alive ? JNI_TRUE : JNI_FALSE;
 }
 
-static int getprocname(pid_t pid, char *buf, size_t len) {
-    char filename[32];
-    FILE *f;
-
-    snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
-    f = fopen(filename, "re");
-    if (!f) {
-        *buf = '\0';
-        return 1;
-    }
-    if (!fgets(buf, len, f)) {
-        *buf = '\0';
-        fclose(f);
-        return 2;
-    }
-    fclose(f);
-    return 0;
-}
-
-static bool push_eventlog_string(char** pos, const char* end, const char* str) {
-    jint len = strlen(str);
-    int space_needed = 1 + sizeof(len) + len;
-    if (end - *pos < space_needed) {
-        ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
-             end - *pos, space_needed);
-        return false;
-    }
-    **pos = EVENT_TYPE_STRING;
-    (*pos)++;
-    memcpy(*pos, &len, sizeof(len));
-    *pos += sizeof(len);
-    memcpy(*pos, str, len);
-    *pos += len;
-    return true;
-}
-
-static bool push_eventlog_int(char** pos, const char* end, jint val) {
-    int space_needed = 1 + sizeof(val);
-    if (end - *pos < space_needed) {
-        ALOGW("not enough space for int.  remain=%" PRIdPTR "; needed=%d",
-             end - *pos, space_needed);
-        return false;
-    }
-    **pos = EVENT_TYPE_INT;
-    (*pos)++;
-    memcpy(*pos, &val, sizeof(val));
-    *pos += sizeof(val);
-    return true;
-}
-
-// From frameworks/base/core/java/android/content/EventLogTags.logtags:
-
-static const bool kEnableBinderSample = false;
-
-#define LOGTAG_BINDER_OPERATION 52004
-
-static void conditionally_log_binder_call(int64_t start_millis,
-                                          IBinder* target, jint code) {
-    int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
-
-    int sample_percent;
-    if (duration_ms >= 500) {
-        sample_percent = 100;
-    } else {
-        sample_percent = 100 * duration_ms / 500;
-        if (sample_percent == 0) {
-            return;
-        }
-        if (sample_percent < (random() % 100 + 1)) {
-            return;
-        }
-    }
-
-    char process_name[40];
-    getprocname(getpid(), process_name, sizeof(process_name));
-    String8 desc(target->getInterfaceDescriptor());
-
-    char buf[LOGGER_ENTRY_MAX_PAYLOAD];
-    buf[0] = EVENT_TYPE_LIST;
-    buf[1] = 5;
-    char* pos = &buf[2];
-    char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1];  // leave room for final \n
-    if (!push_eventlog_string(&pos, end, desc.string())) return;
-    if (!push_eventlog_int(&pos, end, code)) return;
-    if (!push_eventlog_int(&pos, end, duration_ms)) return;
-    if (!push_eventlog_string(&pos, end, process_name)) return;
-    if (!push_eventlog_int(&pos, end, sample_percent)) return;
-    *(pos++) = '\n';   // conventional with EVENT_TYPE_LIST apparently.
-    android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
-}
-
-// We only measure binder call durations to potentially log them if
-// we're on the main thread.
-static bool should_time_binder_calls() {
-  return (getpid() == gettid());
-}
-
 static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
         jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
 {
@@ -1428,29 +1397,10 @@
     ALOGV("Java code calling transact on %p in Java object %p with code %" PRId32 "\n",
             target, obj, code);
 
-
-    bool time_binder_calls;
-    int64_t start_millis;
-    if (kEnableBinderSample) {
-        // Only log the binder call duration for things on the Java-level main thread.
-        // But if we don't
-        time_binder_calls = should_time_binder_calls();
-
-        if (time_binder_calls) {
-            start_millis = uptimeMillis();
-        }
-    }
-
     //printf("Transact from Java code to %p sending: ", target); data->print();
     status_t err = target->transact(code, *data, reply, flags);
     //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
 
-    if (kEnableBinderSample) {
-        if (time_binder_calls) {
-            conditionally_log_binder_call(start_millis, target, code);
-        }
-    }
-
     if (err == NO_ERROR) {
         return JNI_TRUE;
     } else if (err == UNKNOWN_TRANSACTION) {
@@ -1568,17 +1518,19 @@
 
 // ----------------------------------------------------------------------------
 
+// clang-format off
 static const JNINativeMethod gBinderProxyMethods[] = {
      /* name, signature, funcPtr */
     {"pingBinder",          "()Z", (void*)android_os_BinderProxy_pingBinder},
     {"isBinderAlive",       "()Z", (void*)android_os_BinderProxy_isBinderAlive},
     {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
     {"transactNative",      "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
-    {"linkToDeath",         "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
-    {"unlinkToDeath",       "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
+    {"linkToDeathNative",   "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
+    {"unlinkToDeathNative", "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
     {"getNativeFinalizer",  "()J", (void*)android_os_BinderProxy_getNativeFinalizer},
     {"getExtension",        "()Landroid/os/IBinder;", (void*)android_os_BinderProxy_getExtension},
 };
+// clang-format on
 
 const char* const kBinderProxyPathName = "android/os/BinderProxy";
 
diff --git a/core/jni/android_util_Process.cpp b/core/jni/android_util_Process.cpp
index b9d5ee4..66f5df3 100644
--- a/core/jni/android_util_Process.cpp
+++ b/core/jni/android_util_Process.cpp
@@ -148,7 +148,7 @@
 
     const size_t N = name8.size();
     if (N > 0) {
-        const char* str = name8.string();
+        const char* str = name8.c_str();
         for (size_t i=0; i<N; i++) {
             if (str[i] < '0' || str[i] > '9') {
                 struct passwd* pwd = getpwnam(str);
@@ -180,7 +180,7 @@
 
     const size_t N = name8.size();
     if (N > 0) {
-        const char* str = name8.string();
+        const char* str = name8.c_str();
         for (size_t i=0; i<N; i++) {
             if (str[i] < '0' || str[i] > '9') {
                 struct group* grp = getgrnam(str);
@@ -583,8 +583,8 @@
         env->ReleaseStringCritical(name, str);
     }
 
-    if (!name8.isEmpty()) {
-        AndroidRuntime::getRuntime()->setArgv0(name8.string(), true /* setProcName */);
+    if (!name8.empty()) {
+        AndroidRuntime::getRuntime()->setArgv0(name8.c_str(), true /* setProcName */);
     }
 }
 
@@ -690,7 +690,7 @@
         return;
     }
 
-    int fd = open(file.string(), O_RDONLY | O_CLOEXEC);
+    int fd = open(file.c_str(), O_RDONLY | O_CLOEXEC);
 
     if (fd >= 0) {
         //ALOGI("Clearing %" PRId32 " sizes", count);
@@ -704,7 +704,7 @@
         close(fd);
 
         if (len < 0) {
-            ALOGW("Unable to read %s", file.string());
+            ALOGW("Unable to read %s", file.c_str());
             len = 0;
         }
         buffer[len] = 0;
@@ -717,7 +717,7 @@
             //ALOGI("Parsing at: %s", p);
             for (i=0; i<count; i++) {
                 const String8& field = fields[i];
-                if (strncmp(p, field.string(), field.length()) == 0) {
+                if (strncmp(p, field.c_str(), field.length()) == 0) {
                     p += field.length();
                     while (*p == ' ' || *p == '\t') p++;
                     char* num = p;
@@ -729,7 +729,7 @@
                     }
                     char* end;
                     sizesArray[i] = strtoll(num, &end, 10);
-                    //ALOGI("Field %s = %" PRId64, field.string(), sizesArray[i]);
+                    // ALOGI("Field %s = %" PRId64, field.c_str(), sizesArray[i]);
                     foundCount++;
                     break;
                 }
@@ -746,7 +746,7 @@
 
         free(buffer);
     } else {
-        ALOGW("Unable to open %s", file.string());
+        ALOGW("Unable to open %s", file.c_str());
     }
 
     //ALOGI("Done!");
diff --git a/core/jni/android_view_DisplayEventReceiver.cpp b/core/jni/android_view_DisplayEventReceiver.cpp
index be7bee3..c57256f 100644
--- a/core/jni/android_view_DisplayEventReceiver.cpp
+++ b/core/jni/android_view_DisplayEventReceiver.cpp
@@ -227,7 +227,7 @@
     if (status) {
         String8 message;
         message.appendFormat("Failed to initialize display event receiver.  status=%d", status);
-        jniThrowRuntimeException(env, message.string());
+        jniThrowRuntimeException(env, message.c_str());
         return 0;
     }
 
@@ -249,7 +249,7 @@
     if (status) {
         String8 message;
         message.appendFormat("Failed to schedule next vertical sync pulse.  status=%d", status);
-        jniThrowRuntimeException(env, message.string());
+        jniThrowRuntimeException(env, message.c_str());
     }
 }
 
diff --git a/core/jni/android_view_InputEventSender.cpp b/core/jni/android_view_InputEventSender.cpp
index ad54004..5c1edc6 100644
--- a/core/jni/android_view_InputEventSender.cpp
+++ b/core/jni/android_view_InputEventSender.cpp
@@ -334,7 +334,7 @@
     if (status) {
         String8 message;
         message.appendFormat("Failed to initialize input event sender.  status=%d", status);
-        jniThrowRuntimeException(env, message.string());
+        jniThrowRuntimeException(env, message.c_str());
         return 0;
     }
 
diff --git a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp
index a50c011..9210498 100644
--- a/core/jni/com_android_internal_content_NativeLibraryHelper.cpp
+++ b/core/jni/com_android_internal_content_NativeLibraryHelper.cpp
@@ -174,6 +174,7 @@
 static install_status_t
 copyFileIfChanged(JNIEnv *env, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char* fileName)
 {
+    static const size_t kPageSize = getpagesize();
     void** args = reinterpret_cast<void**>(arg);
     jstring* javaNativeLibPath = (jstring*) args[0];
     jboolean extractNativeLibs = *(jboolean*) args[1];
@@ -200,9 +201,9 @@
             return INSTALL_FAILED_INVALID_APK;
         }
 
-        if (offset % PAGE_SIZE != 0) {
-            ALOGE("Library '%s' is not page-aligned - will not be able to open it directly from"
-                " apk.\n", fileName);
+        if (offset % kPageSize != 0) {
+            ALOGE("Library '%s' is not PAGE(%zu)-aligned - will not be able to open it directly "
+                  "from apk.\n", fileName, kPageSize);
             return INSTALL_FAILED_INVALID_APK;
         }
 
diff --git a/core/jni/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index a5d979c..418000f 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -356,6 +356,7 @@
     GWP_ASAN_LEVEL_DEFAULT = 3 << 21,
     NATIVE_HEAP_ZERO_INIT_ENABLED = 1 << 23,
     PROFILEABLE = 1 << 24,
+    DEBUG_ENABLE_PTRACE = 1 << 25,
 };
 
 enum UnsolicitedZygoteMessageTypes : uint32_t {
@@ -1805,15 +1806,10 @@
     if (!is_system_server && getuid() == 0) {
         const int rc = createProcessGroup(uid, getpid());
         if (rc != 0) {
-            if (rc == -ESRCH) {
-                // If process is dead, treat this as a non-fatal error
-                ALOGE("createProcessGroup(%d, %d) failed: %s", uid, /* pid= */ 0, strerror(-rc));
-            } else {
-                fail_fn(rc == -EROFS ? CREATE_ERROR("createProcessGroup failed, kernel missing "
-                                                    "CONFIG_CGROUP_CPUACCT?")
-                                     : CREATE_ERROR("createProcessGroup(%d, %d) failed: %s", uid,
-                                                    /* pid= */ 0, strerror(-rc)));
-            }
+            fail_fn(rc == -EROFS ? CREATE_ERROR("createProcessGroup failed, kernel missing "
+                                                "CONFIG_CGROUP_CPUACCT?")
+                                 : CREATE_ERROR("createProcessGroup(%d, %d) failed: %s", uid,
+                                                /* pid= */ 0, strerror(-rc)));
         }
     }
 
@@ -1887,8 +1883,10 @@
     }
 
     // Set process properties to enable debugging if required.
-    if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_JDWP) != 0) {
+    if ((runtime_flags & RuntimeFlags::DEBUG_ENABLE_PTRACE) != 0) {
         EnableDebugger();
+        // Don't pass unknown flag to the ART runtime.
+        runtime_flags &= ~RuntimeFlags::DEBUG_ENABLE_PTRACE;
     }
     if ((runtime_flags & RuntimeFlags::PROFILE_FROM_SHELL) != 0) {
         // simpleperf needs the process to be dumpable to profile it.
diff --git a/core/jni/fd_utils.cpp b/core/jni/fd_utils.cpp
index 40f6e4f..8e4addd 100644
--- a/core/jni/fd_utils.cpp
+++ b/core/jni/fd_utils.cpp
@@ -17,6 +17,7 @@
 #include "fd_utils.h"
 
 #include <algorithm>
+#include <utility>
 
 #include <fcntl.h>
 #include <grp.h>
@@ -174,7 +175,7 @@
 class FileDescriptorInfo {
  public:
   // Create a FileDescriptorInfo for a given file descriptor.
-  static FileDescriptorInfo* CreateFromFd(int fd, fail_fn_t fail_fn);
+  static std::unique_ptr<FileDescriptorInfo> CreateFromFd(int fd, fail_fn_t fail_fn);
 
   // Checks whether the file descriptor associated with this object refers to
   // the same description.
@@ -213,7 +214,7 @@
   DISALLOW_COPY_AND_ASSIGN(FileDescriptorInfo);
 };
 
-FileDescriptorInfo* FileDescriptorInfo::CreateFromFd(int fd, fail_fn_t fail_fn) {
+std::unique_ptr<FileDescriptorInfo> FileDescriptorInfo::CreateFromFd(int fd, fail_fn_t fail_fn) {
   struct stat f_stat;
   // This should never happen; the zygote should always have the right set
   // of permissions required to stat all its open files.
@@ -234,7 +235,7 @@
                                             socket_name.c_str(), fd));
     }
 
-    return new FileDescriptorInfo(fd);
+    return std::unique_ptr<FileDescriptorInfo>(new FileDescriptorInfo(fd));
   }
 
   // We only handle allowlisted regular files and character devices. Allowlisted
@@ -315,7 +316,8 @@
   int open_flags = fs_flags & (kOpenFlags);
   fs_flags = fs_flags & (~(kOpenFlags));
 
-  return new FileDescriptorInfo(f_stat, file_path, fd, open_flags, fd_flags, fs_flags, offset);
+  return std::unique_ptr<FileDescriptorInfo>(
+    new FileDescriptorInfo(f_stat, file_path, fd, open_flags, fd_flags, fs_flags, offset));
 }
 
 bool FileDescriptorInfo::RefersToSameFile() const {
@@ -482,11 +484,11 @@
 FileDescriptorTable* FileDescriptorTable::Create(const std::vector<int>& fds_to_ignore,
                                                  fail_fn_t fail_fn) {
   std::unique_ptr<std::set<int>> open_fds = GetOpenFdsIgnoring(fds_to_ignore, fail_fn);
-  std::unordered_map<int, FileDescriptorInfo*> open_fd_map;
+  std::unordered_map<int, std::unique_ptr<FileDescriptorInfo>> open_fd_map;
   for (auto fd : *open_fds) {
     open_fd_map[fd] = FileDescriptorInfo::CreateFromFd(fd, fail_fn);
   }
-  return new FileDescriptorTable(open_fd_map);
+  return new FileDescriptorTable(std::move(open_fd_map));
 }
 
 static std::unique_ptr<std::set<int>> GetOpenFdsIgnoring(const std::vector<int>& fds_to_ignore,
@@ -535,9 +537,9 @@
 
 // Reopens all file descriptors that are contained in the table.
 void FileDescriptorTable::ReopenOrDetach(fail_fn_t fail_fn) {
-  std::unordered_map<int, FileDescriptorInfo*>::const_iterator it;
+  std::unordered_map<int, std::unique_ptr<FileDescriptorInfo>>::const_iterator it;
   for (it = open_fd_map_.begin(); it != open_fd_map_.end(); ++it) {
-    const FileDescriptorInfo* info = it->second;
+    const FileDescriptorInfo* info = it->second.get();
     if (info == nullptr) {
       return;
     } else {
@@ -547,15 +549,11 @@
 }
 
 FileDescriptorTable::FileDescriptorTable(
-    const std::unordered_map<int, FileDescriptorInfo*>& map)
-    : open_fd_map_(map) {
+  std::unordered_map<int, std::unique_ptr<FileDescriptorInfo>> map)
+  : open_fd_map_(std::move(map)) {
 }
 
-FileDescriptorTable::~FileDescriptorTable() {
-    for (auto& it : open_fd_map_) {
-        delete it.second;
-    }
-}
+FileDescriptorTable::~FileDescriptorTable() {}
 
 void FileDescriptorTable::RestatInternal(std::set<int>& open_fds, fail_fn_t fail_fn) {
   // ART creates a file through memfd for optimization purposes. We make sure
@@ -569,7 +567,7 @@
   // (b) they refer to the same file.
   //
   // We'll only store the last error message.
-  std::unordered_map<int, FileDescriptorInfo*>::iterator it = open_fd_map_.begin();
+  std::unordered_map<int, std::unique_ptr<FileDescriptorInfo>>::iterator it = open_fd_map_.begin();
   while (it != open_fd_map_.end()) {
     std::set<int>::const_iterator element = open_fds.find(it->first);
     if (element == open_fds.end()) {
@@ -587,7 +585,6 @@
       if (!it->second->RefersToSameFile()) {
         // The file descriptor refers to a different description. We must
         // update our entry in the table.
-        delete it->second;
         it->second = FileDescriptorInfo::CreateFromFd(*element, fail_fn);
       } else {
         // It's the same file. Nothing to do here. Move on to the next open
diff --git a/core/jni/fd_utils.h b/core/jni/fd_utils.h
index a28ebf1..ac2d2a4 100644
--- a/core/jni/fd_utils.h
+++ b/core/jni/fd_utils.h
@@ -17,6 +17,7 @@
 #ifndef FRAMEWORKS_BASE_CORE_JNI_FD_UTILS_H_
 #define FRAMEWORKS_BASE_CORE_JNI_FD_UTILS_H_
 
+#include <memory>
 #include <set>
 #include <string>
 #include <unordered_map>
@@ -98,12 +99,12 @@
   void ReopenOrDetach(fail_fn_t fail_fn);
 
  private:
-  explicit FileDescriptorTable(const std::unordered_map<int, FileDescriptorInfo*>& map);
+  explicit FileDescriptorTable(std::unordered_map<int, std::unique_ptr<FileDescriptorInfo>> map);
 
   void RestatInternal(std::set<int>& open_fds, fail_fn_t fail_fn);
 
   // Invariant: All values in this unordered_map are non-NULL.
-  std::unordered_map<int, FileDescriptorInfo*> open_fd_map_;
+  std::unordered_map<int, std::unique_ptr<FileDescriptorInfo>> open_fd_map_;
 
   DISALLOW_COPY_AND_ASSIGN(FileDescriptorTable);
 };
diff --git a/core/proto/android/os/system_properties.proto b/core/proto/android/os/system_properties.proto
index 3cedba0..5a3539a 100644
--- a/core/proto/android/os/system_properties.proto
+++ b/core/proto/android/os/system_properties.proto
@@ -172,7 +172,7 @@
         optional Status tombstoned = 29;
         optional Status ueventd = 30;
         optional Status update_engine = 31;
-        optional Status update_verifier_nonencrypted = 32;
+        optional Status update_verifier = 32;
         optional Status virtual_touchpad = 33;
         optional Status vndservicemanager = 34;
         optional Status vold = 35;
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index c226112..c369a10 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -2225,6 +2225,14 @@
     <permission android:name="android.permission.MANAGE_ETHERNET_NETWORKS"
         android:protectionLevel="signature" />
 
+    <!-- Allows system apps to call methods to register itself as a mDNS offload engine.
+        <p>Not for use by third-party or privileged applications.
+        @SystemApi
+        @hide This should only be used by system apps.
+    -->
+    <permission android:name="android.permission.REGISTER_NSD_OFFLOAD_ENGINE"
+        android:protectionLevel="signature" />
+
     <!-- ======================================= -->
     <!-- Permissions for short range, peripheral networks -->
     <!-- ======================================= -->
diff --git a/core/res/OWNERS b/core/res/OWNERS
index b46902e..0df7c20 100644
--- a/core/res/OWNERS
+++ b/core/res/OWNERS
@@ -52,3 +52,6 @@
 # Telephony
 per-file res/values/config_telephony.xml = file:/platform/frameworks/opt/telephony:/OWNERS
 per-file res/xml/sms_short_codes.xml = file:/platform/frameworks/opt/telephony:/OWNERS
+
+# TV Input Framework
+per-file res/values/config_tv_external_input_logging.xml = file:/services/core/java/com/android/server/tv/OWNERS
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 6cb48db..1e77b92 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -1393,6 +1393,11 @@
     <!-- Is the lock-screen disabled for new users by default -->
     <bool name="config_disableLockscreenByDefault">false</bool>
 
+    <!-- Provides default value for double line clock in lock screen setting:
+         0 - Don't show double line clock
+         1 - Show double line clock in lock screen (default) -->
+    <integer name="config_doublelineClockDefault">1</integer>
+
     <!-- If true, enables verification of the lockscreen credential in the factory reset protection
         flow. This should be true if gatekeeper / weaver credentials can still be checked after a
         factory reset. -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 0cb8062..0ea342d 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2376,6 +2376,9 @@
   <java-symbol type="dimen" name="popup_enter_animation_from_y_delta" />
   <java-symbol type="dimen" name="popup_exit_animation_to_y_delta" />
 
+  <!-- For double line clock in lock screen -->
+  <java-symbol type="integer" name="config_doublelineClockDefault"/>
+
   <!-- ImfTest -->
   <java-symbol type="layout" name="auto_complete_list" />
 
diff --git a/core/res/res/xml/sms_short_codes.xml b/core/res/res/xml/sms_short_codes.xml
index 3b099e8..af8c69e 100644
--- a/core/res/res/xml/sms_short_codes.xml
+++ b/core/res/res/xml/sms_short_codes.xml
@@ -216,6 +216,9 @@
     <!-- Pakistan -->
     <shortcode country="pk" pattern="\\d{1,5}" free="2057" />
 
+    <!-- Palestine: 5 digits, known premium codes listed -->
+    <shortcode country="ps" pattern="\\d{1,5}" free="37477" />
+
     <!-- Poland: 4-5 digits (not confirmed), known premium codes listed, plus EU -->
     <shortcode country="pl" pattern="\\d{4,5}" premium="74240|79(?:10|866)|92525" free="116\\d{3}|8012|80921" />
 
diff --git a/core/tests/coretests/res/values-id/strings.xml b/core/tests/coretests/res/values-id/strings.xml
new file mode 100644
index 0000000..6d71c90
--- /dev/null
+++ b/core/tests/coretests/res/values-id/strings.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <!-- Used in ResourcesLocaleTest. -->
+    <string name="locale_test_res_1">Pengujian ID</string>
+</resources>
diff --git a/core/tests/coretests/res/values-in/strings.xml b/core/tests/coretests/res/values-in/strings.xml
new file mode 100644
index 0000000..6384660
--- /dev/null
+++ b/core/tests/coretests/res/values-in/strings.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <!-- Used in ResourcesLocaleTest. -->
+    <string name="locale_test_res_2">Pengujian IN</string>
+</resources>
diff --git a/core/tests/coretests/res/values/strings.xml b/core/tests/coretests/res/values/strings.xml
index e51eab6..09e1c69 100644
--- a/core/tests/coretests/res/values/strings.xml
+++ b/core/tests/coretests/res/values/strings.xml
@@ -131,6 +131,13 @@
 
     <string name="textview_hebrew_text">&#x05DD;&#x05DE;ab?!</string>
 
+    <!-- Used in ResourcesLocaleTest. Also defined in values-id. "id" is the new ISO code for Indonesian. -->
+    <string name="locale_test_res_1">Testing ID</string>
+    <!-- Used in ResourcesLocaleTest. Also defined in values-in. "in" is the deprecated ISO code for Indonesian. -->
+    <string name="locale_test_res_2">Testing IN</string>
+    <!-- Used in ResourcesLocaleTest. -->
+    <string name="locale_test_res_3">Testing EN</string>
+
     <!-- SizeAdaptiveLayout -->
     <string name="first">Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.</string>
     <string name="actor">Abe Lincoln</string>
diff --git a/core/tests/coretests/src/android/content/res/ResourcesLocaleTest.java b/core/tests/coretests/src/android/content/res/ResourcesLocaleTest.java
index 25c3db5..26e4349 100644
--- a/core/tests/coretests/src/android/content/res/ResourcesLocaleTest.java
+++ b/core/tests/coretests/src/android/content/res/ResourcesLocaleTest.java
@@ -16,6 +16,7 @@
 
 package android.content.res;
 
+import android.content.Context;
 import android.os.FileUtils;
 import android.os.LocaleList;
 import android.platform.test.annotations.Presubmit;
@@ -97,4 +98,24 @@
         assertEquals(Locale.forLanguageTag("pl-PL"),
                 resources.getConfiguration().getLocales().get(0));
     }
+
+    @SmallTest
+    public void testDeprecatedISOLanguageCode() {
+        assertResGetString(Locale.US, R.string.locale_test_res_1, "Testing ID");
+        assertResGetString(Locale.forLanguageTag("id"), R.string.locale_test_res_2, "Pengujian IN");
+        assertResGetString(Locale.forLanguageTag("id"), R.string.locale_test_res_3, "Testing EN");
+        assertResGetString(new Locale("id"), R.string.locale_test_res_2, "Pengujian IN");
+        assertResGetString(new Locale("id"), R.string.locale_test_res_3, "Testing EN");
+        // The new ISO code "id" isn't supported yet, and thus the values-id are ignored.
+        assertResGetString(new Locale("id"), R.string.locale_test_res_1, "Testing ID");
+        assertResGetString(Locale.forLanguageTag("id"), R.string.locale_test_res_1, "Testing ID");
+    }
+
+    private void assertResGetString(Locale locale, int resId, String expectedString) {
+        LocaleList locales = new LocaleList(locale);
+        final Configuration config = new Configuration();
+        config.setLocales(locales);
+        Context newContext = getContext().createConfigurationContext(config);
+        assertEquals(expectedString, newContext.getResources().getString(resId));
+    }
 }
diff --git a/core/tests/coretests/src/android/hardware/input/InputFlagsTest.java b/core/tests/coretests/src/android/hardware/input/InputFlagsTest.java
new file mode 100644
index 0000000..5aeab42
--- /dev/null
+++ b/core/tests/coretests/src/android/hardware/input/InputFlagsTest.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2023 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.hardware.input;
+
+import static com.android.hardware.input.Flags.keyboardA11yStickyKeysFlag;
+import static com.android.hardware.input.Flags.keyboardLayoutPreviewFlag;
+
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Tests for {@link com.android.hardware.input.Flags}
+ *
+ * Build/Install/Run:
+ *  atest FrameworksCoreTests:InputFlagsTest
+ */
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+@Presubmit
+public class InputFlagsTest {
+
+    /**
+     * Test that the flags work
+     */
+    @Test
+    public void testFlags() {
+        // No crash when accessing the flag.
+        keyboardLayoutPreviewFlag();
+        keyboardA11yStickyKeysFlag();
+    }
+}
+
diff --git a/core/tests/coretests/src/android/os/AidlTest.java b/core/tests/coretests/src/android/os/AidlTest.java
index 5f54b09..d0c3470 100644
--- a/core/tests/coretests/src/android/os/AidlTest.java
+++ b/core/tests/coretests/src/android/os/AidlTest.java
@@ -28,12 +28,14 @@
 
     private IAidlTest mRemote;
     private AidlObject mLocal;
+    private NonAutoGeneratedObject mNonAutoGenerated;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
         mLocal = new AidlObject();
         mRemote = IAidlTest.Stub.asInterface(mLocal);
+        mNonAutoGenerated = new NonAutoGeneratedObject("NonAutoGeneratedObject");
     }
 
     private static boolean check(TestParcelable p, int n, String s) {
@@ -84,6 +86,12 @@
         }
     }
 
+    private static class NonAutoGeneratedObject extends Binder {
+        NonAutoGeneratedObject(String descriptor) {
+            super(descriptor);
+        }
+    }
+
     private static class AidlObject extends IAidlTest.Stub {
         public IInterface queryLocalInterface(String descriptor) {
             // overriding this to return null makes asInterface always
@@ -194,7 +202,7 @@
                 TestParcelable[] a1, TestParcelable[] a2) {
             return null;
         }
-        
+
         public void voidSecurityException() {
             throw new SecurityException("gotcha!");
         }
@@ -396,7 +404,7 @@
         assertEquals("s2[1]", s2[1]);
         assertEquals("s2[2]", s2[2]);
     }
-    
+
     @SmallTest
     public void testVoidSecurityException() throws Exception {
         boolean good = false;
@@ -407,7 +415,7 @@
         }
         assertEquals(good, true);
     }
-    
+
     @SmallTest
     public void testIntSecurityException() throws Exception {
         boolean good = false;
@@ -420,7 +428,7 @@
     }
 
     @SmallTest
-    public void testGetTransactionName() throws Exception {
+    public void testGetTransactionNameAutoGenerated() throws Exception {
         assertEquals(15, mLocal.getMaxTransactionId());
 
         assertEquals("booleanArray",
@@ -430,12 +438,21 @@
         assertEquals("parcelableIn",
                 mLocal.getTransactionName(IAidlTest.Stub.TRANSACTION_parcelableIn));
 
-        assertEquals("IAidlTest:booleanArray",
+        assertEquals("AIDL::java::IAidlTest::booleanArray::server",
                 mLocal.getTransactionTraceName(IAidlTest.Stub.TRANSACTION_booleanArray));
-        assertEquals("IAidlTest:voidSecurityException",
+        assertEquals("AIDL::java::IAidlTest::voidSecurityException::server",
                 mLocal.getTransactionTraceName(IAidlTest.Stub.TRANSACTION_voidSecurityException));
-        assertEquals("IAidlTest:parcelableIn",
+        assertEquals("AIDL::java::IAidlTest::parcelableIn::server",
                 mLocal.getTransactionTraceName(IAidlTest.Stub.TRANSACTION_parcelableIn));
     }
-}
 
+    @SmallTest
+    public void testGetTransactionNameNonAutoGenerated() throws Exception {
+        assertEquals(0, mNonAutoGenerated.getMaxTransactionId());
+
+        assertEquals("AIDL::java::NonAutoGeneratedObject::#0::server",
+                mNonAutoGenerated.getTransactionTraceName(0));
+        assertEquals("AIDL::java::NonAutoGeneratedObject::#1::server",
+                mNonAutoGenerated.getTransactionTraceName(1));
+    }
+}
diff --git a/core/tests/coretests/src/android/os/OWNERS b/core/tests/coretests/src/android/os/OWNERS
index f2d6ff8..8b333f3 100644
--- a/core/tests/coretests/src/android/os/OWNERS
+++ b/core/tests/coretests/src/android/os/OWNERS
@@ -5,4 +5,7 @@
 per-file *Vibrat*.java = file:/services/core/java/com/android/server/vibrator/OWNERS
 
 # Power
-per-file PowerManager*.java = michaelwr@google.com, santoscordon@google.com
\ No newline at end of file
+per-file PowerManager*.java = michaelwr@google.com, santoscordon@google.com
+
+# PerformanceHintManager
+per-file PerformanceHintManagerTest.java = file:/ADPF_OWNERS
diff --git a/core/tests/coretests/src/android/security/keystore/OWNERS b/core/tests/coretests/src/android/security/keystore/OWNERS
new file mode 100644
index 0000000..d9e0116
--- /dev/null
+++ b/core/tests/coretests/src/android/security/keystore/OWNERS
@@ -0,0 +1 @@
+include /keystore/OWNERS
diff --git a/core/tests/coretests/src/android/service/euicc/OWNERS b/core/tests/coretests/src/android/service/euicc/OWNERS
new file mode 100644
index 0000000..41fc56b4
--- /dev/null
+++ b/core/tests/coretests/src/android/service/euicc/OWNERS
@@ -0,0 +1 @@
+include platform/frameworks/base:/telephony/java/android/service/euicc/OWNERS
diff --git a/core/tests/coretests/src/android/service/quicksettings/OWNERS b/core/tests/coretests/src/android/service/quicksettings/OWNERS
new file mode 100644
index 0000000..5665490
--- /dev/null
+++ b/core/tests/coretests/src/android/service/quicksettings/OWNERS
@@ -0,0 +1 @@
+include platform/frameworks/base:/core/java/android/service/quicksettings/OWNERS
diff --git a/core/tests/coretests/src/android/util/PatternsTest.java b/core/tests/coretests/src/android/util/PatternsTest.java
index 6cea2f3..dd8f73f 100644
--- a/core/tests/coretests/src/android/util/PatternsTest.java
+++ b/core/tests/coretests/src/android/util/PatternsTest.java
@@ -399,7 +399,7 @@
     @SmallTest
     public void testAutoLinkWebUrl_doesNotMatchUrlsWithoutProtocolAndWithUnknownTld()
             throws Exception {
-        String url = "thank.you";
+        String url = "thank.unknowntld";
         assertFalse("Should not match URL that does not start with a protocol and " +
                 "does not contain a known TLD",
                 Patterns.AUTOLINK_WEB_URL.matcher(url).matches());
@@ -422,7 +422,7 @@
     @SmallTest
     public void testAutoLinkWebUrl_doesNotMatchUrlsWithEmojiWithoutProtocolAndWithoutKnownTld()
             throws Exception {
-        String url = "Thank\u263A.you";
+        String url = "Thank\u263A.unknowntld";
         assertFalse("Should not match URLs containing emoji and with unknown TLD",
                 Patterns.AUTOLINK_WEB_URL.matcher(url).matches());
     }
diff --git a/core/tests/coretests/src/android/widget/RemoteViewsTest.java b/core/tests/coretests/src/android/widget/RemoteViewsTest.java
index bbf9f3c..ed2a32b 100644
--- a/core/tests/coretests/src/android/widget/RemoteViewsTest.java
+++ b/core/tests/coretests/src/android/widget/RemoteViewsTest.java
@@ -24,6 +24,10 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
 
 import android.app.ActivityOptions;
 import android.app.PendingIntent;
@@ -33,6 +37,8 @@
 import android.graphics.Bitmap;
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
+import android.graphics.drawable.Icon;
+import android.net.Uri;
 import android.os.AsyncTask;
 import android.os.Binder;
 import android.os.Looper;
@@ -58,6 +64,7 @@
 import java.util.Arrays;
 import java.util.Map;
 import java.util.concurrent.CountDownLatch;
+import java.util.function.Consumer;
 
 /**
  * Tests for RemoteViews.
@@ -693,4 +700,61 @@
             return null;
         }
     }
+
+    @Test
+    public void visitUris() {
+        RemoteViews views = new RemoteViews(mPackage, R.layout.remote_views_test);
+
+        final Uri imageUri = Uri.parse("content://media/image");
+        final Icon icon1 = Icon.createWithContentUri("content://media/icon1");
+        final Icon icon2 = Icon.createWithContentUri("content://media/icon2");
+        final Icon icon3 = Icon.createWithContentUri("content://media/icon3");
+        final Icon icon4 = Icon.createWithContentUri("content://media/icon4");
+        views.setImageViewUri(R.id.image, imageUri);
+        views.setTextViewCompoundDrawables(R.id.text, icon1, icon2, icon3, icon4);
+
+        Consumer<Uri> visitor = (Consumer<Uri>) spy(Consumer.class);
+        views.visitUris(visitor);
+        verify(visitor, times(1)).accept(eq(imageUri));
+        verify(visitor, times(1)).accept(eq(icon1.getUri()));
+        verify(visitor, times(1)).accept(eq(icon2.getUri()));
+        verify(visitor, times(1)).accept(eq(icon3.getUri()));
+        verify(visitor, times(1)).accept(eq(icon4.getUri()));
+    }
+
+    @Test
+    public void visitUris_separateOrientation() {
+        final RemoteViews landscape = new RemoteViews(mPackage, R.layout.remote_views_test);
+        final Uri imageUriL = Uri.parse("content://landscape/image");
+        final Icon icon1L = Icon.createWithContentUri("content://landscape/icon1");
+        final Icon icon2L = Icon.createWithContentUri("content://landscape/icon2");
+        final Icon icon3L = Icon.createWithContentUri("content://landscape/icon3");
+        final Icon icon4L = Icon.createWithContentUri("content://landscape/icon4");
+        landscape.setImageViewUri(R.id.image, imageUriL);
+        landscape.setTextViewCompoundDrawables(R.id.text, icon1L, icon2L, icon3L, icon4L);
+
+        final RemoteViews portrait = new RemoteViews(mPackage, 33);
+        final Uri imageUriP = Uri.parse("content://portrait/image");
+        final Icon icon1P = Icon.createWithContentUri("content://portrait/icon1");
+        final Icon icon2P = Icon.createWithContentUri("content://portrait/icon2");
+        final Icon icon3P = Icon.createWithContentUri("content://portrait/icon3");
+        final Icon icon4P = Icon.createWithContentUri("content://portrait/icon4");
+        portrait.setImageViewUri(R.id.image, imageUriP);
+        portrait.setTextViewCompoundDrawables(R.id.text, icon1P, icon2P, icon3P, icon4P);
+
+        RemoteViews views = new RemoteViews(landscape, portrait);
+
+        Consumer<Uri> visitor = (Consumer<Uri>) spy(Consumer.class);
+        views.visitUris(visitor);
+        verify(visitor, times(1)).accept(eq(imageUriL));
+        verify(visitor, times(1)).accept(eq(icon1L.getUri()));
+        verify(visitor, times(1)).accept(eq(icon2L.getUri()));
+        verify(visitor, times(1)).accept(eq(icon3L.getUri()));
+        verify(visitor, times(1)).accept(eq(icon4L.getUri()));
+        verify(visitor, times(1)).accept(eq(imageUriP));
+        verify(visitor, times(1)).accept(eq(icon1P.getUri()));
+        verify(visitor, times(1)).accept(eq(icon2P.getUri()));
+        verify(visitor, times(1)).accept(eq(icon3P.getUri()));
+        verify(visitor, times(1)).accept(eq(icon4P.getUri()));
+    }
 }
diff --git a/core/tests/coretests/src/android/window/flags/WindowFlagsTest.java b/core/tests/coretests/src/android/window/flags/WindowFlagsTest.java
new file mode 100644
index 0000000..a8b4032
--- /dev/null
+++ b/core/tests/coretests/src/android/window/flags/WindowFlagsTest.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2023 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.window.flags;
+
+import static com.android.window.flags.Flags.syncWindowConfigUpdateFlag;
+
+import android.platform.test.annotations.Presubmit;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Tests for {@link com.android.window.flags.Flags}
+ *
+ * Build/Install/Run:
+ *  atest FrameworksCoreTests:WindowFlagsTest
+ */
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+@Presubmit
+public class WindowFlagsTest {
+
+    @Test
+    public void testSyncWindowConfigUpdateFlag() {
+        // No crash when accessing the flag.
+        syncWindowConfigUpdateFlag();
+    }
+}
diff --git a/core/tests/coretests/src/com/android/internal/content/OWNERS b/core/tests/coretests/src/com/android/internal/content/OWNERS
index dd9ede5..4bb8343 100644
--- a/core/tests/coretests/src/com/android/internal/content/OWNERS
+++ b/core/tests/coretests/src/com/android/internal/content/OWNERS
@@ -1,4 +1,2 @@
 
-per-file PackageMonitorTest.java = file:/core/java/android/content/pm/OWNERS
-
 per-file Overlay* = file:/core/java/android/content/res/OWNERS
diff --git a/core/tests/coretests/src/com/android/internal/content/res/OverlayConfigTest.java b/core/tests/coretests/src/com/android/internal/content/res/OverlayConfigTest.java
index 0f30cfe..246a1e7 100644
--- a/core/tests/coretests/src/com/android/internal/content/res/OverlayConfigTest.java
+++ b/core/tests/coretests/src/com/android/internal/content/res/OverlayConfigTest.java
@@ -22,6 +22,7 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
+import android.content.pm.PackagePartitions;
 import android.os.FileUtils;
 import android.os.SystemProperties;
 import android.platform.test.annotations.Presubmit;
@@ -32,6 +33,7 @@
 import com.android.frameworks.coretests.R;
 import com.android.internal.content.om.OverlayConfig;
 import com.android.internal.content.om.OverlayConfig.IdmapInvocation;
+import com.android.internal.content.om.OverlayConfigParser.OverlayPartition;
 import com.android.internal.content.om.OverlayScanner;
 
 import org.junit.Rule;
@@ -46,6 +48,7 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
+import java.util.List;
 
 @Presubmit
 @RunWith(AndroidJUnit4.class)
@@ -88,6 +91,17 @@
         assertEquals(configIndex, config.configIndex);
     }
 
+    private String generatePartitionOrderString(List<OverlayPartition> partitions) {
+        StringBuilder partitionOrder = new StringBuilder();
+        for (int i = 0; i < partitions.size(); i++) {
+            partitionOrder.append(partitions.get(i).getName());
+            if (i < partitions.size() - 1) {
+                partitionOrder.append(", ");
+            }
+        }
+        return partitionOrder.toString();
+    }
+
     @Test
     public void testImmutableAfterNonImmutableFails() throws IOException {
         mExpectedException.expect(IllegalStateException.class);
@@ -685,4 +699,122 @@
         OverlayConfig.Configuration o3 = overlayConfig.getConfiguration("three");
         assertNotNull(o3);
     }
+
+    @Test
+    public void testSortPartitionsWithoutXml() throws IOException {
+        ArrayList<OverlayPartition> partitions = new ArrayList<>(
+                PackagePartitions.getOrderedPartitions(OverlayPartition::new));
+
+        final OverlayConfig overlayConfig = createConfigImpl();
+        String partitionOrderFilePath = String.format("%s/%s", mTestFolder.getRoot(),
+                "/product/overlay/partition_order.xml");
+        assertEquals(false, overlayConfig.sortPartitions(partitionOrderFilePath, partitions));
+        assertEquals("system, vendor, odm, oem, product, system_ext",
+                generatePartitionOrderString(partitions));
+    }
+
+    @Test
+    public void testSortPartitionsWithInvalidXmlRootElement() throws IOException {
+        ArrayList<OverlayPartition> partitions = new ArrayList<>(
+                PackagePartitions.getOrderedPartitions(OverlayPartition::new));
+        createFile("/product/overlay/partition_order.xml",
+                "<partition-list>\n"
+                        + "  <partition name=\"system_ext\"/>\n"
+                        + "  <partition name=\"vendor\"/>\n"
+                        + "  <partition name=\"oem\"/>\n"
+                        + "  <partition name=\"odm\"/>\n"
+                        + "  <partition name=\"product\"/>\n"
+                        + "  <partition name=\"system\"/>\n"
+                        + "</partition-list>\n");
+        final OverlayConfig overlayConfig = createConfigImpl();
+        String partitionOrderFilePath = String.format("%s/%s", mTestFolder.getRoot(),
+                "/product/overlay/partition_order.xml");
+        assertEquals(false, overlayConfig.sortPartitions(partitionOrderFilePath, partitions));
+        assertEquals("system, vendor, odm, oem, product, system_ext",
+                generatePartitionOrderString(partitions));
+    }
+
+    @Test
+    public void testSortPartitionsWithInvalidPartition() throws IOException {
+        ArrayList<OverlayPartition> partitions = new ArrayList<>(
+                PackagePartitions.getOrderedPartitions(OverlayPartition::new));
+        createFile("/product/overlay/partition_order.xml",
+                "<partition-order>\n"
+                        + "  <partition name=\"INVALID\"/>\n"
+                        + "  <partition name=\"vendor\"/>\n"
+                        + "  <partition name=\"oem\"/>\n"
+                        + "  <partition name=\"odm\"/>\n"
+                        + "  <partition name=\"product\"/>\n"
+                        + "  <partition name=\"system\"/>\n"
+                        + "</partition-order>\n");
+        final OverlayConfig overlayConfig = createConfigImpl();
+        String partitionOrderFilePath = String.format("%s/%s", mTestFolder.getRoot(),
+                "/product/overlay/partition_order.xml");
+        assertEquals(false, overlayConfig.sortPartitions(partitionOrderFilePath, partitions));
+        assertEquals("system, vendor, odm, oem, product, system_ext",
+                generatePartitionOrderString(partitions));
+    }
+
+    @Test
+    public void testSortPartitionsWithDuplicatePartition() throws IOException {
+        ArrayList<OverlayPartition> partitions = new ArrayList<>(
+                PackagePartitions.getOrderedPartitions(OverlayPartition::new));
+        createFile("/product/overlay/partition_order.xml",
+                "<partition-order>\n"
+                        + "  <partition name=\"system_ext\"/>\n"
+                        + "  <partition name=\"system\"/>\n"
+                        + "  <partition name=\"vendor\"/>\n"
+                        + "  <partition name=\"oem\"/>\n"
+                        + "  <partition name=\"odm\"/>\n"
+                        + "  <partition name=\"product\"/>\n"
+                        + "  <partition name=\"system\"/>\n"
+                        + "</partition-order>\n");
+        final OverlayConfig overlayConfig = createConfigImpl();
+        String partitionOrderFilePath = String.format("%s/%s", mTestFolder.getRoot(),
+                "/product/overlay/partition_order.xml");
+        assertEquals(false, overlayConfig.sortPartitions(partitionOrderFilePath, partitions));
+        assertEquals("system, vendor, odm, oem, product, system_ext",
+                generatePartitionOrderString(partitions));
+    }
+
+    @Test
+    public void testSortPartitionsWithMissingPartition() throws IOException {
+        ArrayList<OverlayPartition> partitions = new ArrayList<>(
+                PackagePartitions.getOrderedPartitions(OverlayPartition::new));
+        createFile("/product/overlay/partition_order.xml",
+                "<partition-order>\n"
+                        + "  <partition name=\"vendor\"/>\n"
+                        + "  <partition name=\"oem\"/>\n"
+                        + "  <partition name=\"odm\"/>\n"
+                        + "  <partition name=\"product\"/>\n"
+                        + "  <partition name=\"system\"/>\n"
+                        + "</partition-order>\n");
+        final OverlayConfig overlayConfig = createConfigImpl();
+        String partitionOrderFilePath = String.format("%s/%s", mTestFolder.getRoot(),
+                "/product/overlay/partition_order.xml");
+        assertEquals(false, overlayConfig.sortPartitions(partitionOrderFilePath, partitions));
+        assertEquals("system, vendor, odm, oem, product, system_ext",
+                generatePartitionOrderString(partitions));
+    }
+
+    @Test
+    public void testSortPartitionsWithCorrectPartitionOrderXml() throws IOException {
+        ArrayList<OverlayPartition> partitions = new ArrayList<>(
+                PackagePartitions.getOrderedPartitions(OverlayPartition::new));
+        createFile("/product/overlay/partition_order.xml",
+                "<partition-order>\n"
+                        + "  <partition name=\"system_ext\"/>\n"
+                        + "  <partition name=\"vendor\"/>\n"
+                        + "  <partition name=\"oem\"/>\n"
+                        + "  <partition name=\"odm\"/>\n"
+                        + "  <partition name=\"product\"/>\n"
+                        + "  <partition name=\"system\"/>\n"
+                        + "</partition-order>\n");
+        final OverlayConfig overlayConfig = createConfigImpl();
+        String partitionOrderFilePath = String.format("%s/%s", mTestFolder.getRoot(),
+                "/product/overlay/partition_order.xml");
+        assertEquals(true, overlayConfig.sortPartitions(partitionOrderFilePath, partitions));
+        assertEquals("system_ext, vendor, oem, odm, product, system",
+                generatePartitionOrderString(partitions));
+    }
 }
diff --git a/core/tests/fuzzers/ParcelFuzzer/ReadUtils.java b/core/tests/fuzzers/ParcelFuzzer/ReadUtils.java
index b5e5b25..cb98855 100644
--- a/core/tests/fuzzers/ParcelFuzzer/ReadUtils.java
+++ b/core/tests/fuzzers/ParcelFuzzer/ReadUtils.java
@@ -364,6 +364,12 @@
                         TestClassLoader loader = new TestClassLoader();
                         parcel.readParcelableArray(loader);
                     },
+                    (parcel, provider) -> {
+                        parcel.readParcelable(null);
+                    },
+                    (parcel, provider) -> {
+                        parcel.readParcelableArray(null);
+                    },
 
                     // read lists
                     (parcel, provider) -> {
diff --git a/core/tests/packagemonitortests/OWNERS b/core/tests/packagemonitortests/OWNERS
new file mode 100644
index 0000000..d825dfd
--- /dev/null
+++ b/core/tests/packagemonitortests/OWNERS
@@ -0,0 +1 @@
+include /services/core/java/com/android/server/pm/OWNERS
diff --git a/core/tests/utiltests/src/com/android/internal/util/FileRotatorTest.java b/core/tests/utiltests/src/com/android/internal/util/FileRotatorTest.java
index 95272132..73e47e16 100644
--- a/core/tests/utiltests/src/com/android/internal/util/FileRotatorTest.java
+++ b/core/tests/utiltests/src/com/android/internal/util/FileRotatorTest.java
@@ -366,6 +366,16 @@
         assertReadAll(rotate, "bar");
     }
 
+    public void testReadSorted() throws Exception {
+        write("rotator.1024-2048", "2");
+        write("rotator.2048-4096", "3");
+        write("rotator.512-1024", "1");
+
+        final FileRotator rotate = new FileRotator(
+                mBasePath, PREFIX, SECOND_IN_MILLIS, SECOND_IN_MILLIS);
+        assertReadAll(rotate, "1", "2", "3");
+    }
+
     public void testFileSystemInaccessible() throws Exception {
         File inaccessibleDir = null;
         String dirPath = getContext().getFilesDir() + File.separator + "inaccessible";
@@ -422,16 +432,7 @@
         }
 
         public void assertRead(String... expected) {
-            assertEquals(expected.length, mActual.size());
-
-            final ArrayList<String> actualCopy = new ArrayList<String>(mActual);
-            for (String value : expected) {
-                if (!actualCopy.remove(value)) {
-                    final String expectedString = Arrays.toString(expected);
-                    final String actualString = Arrays.toString(mActual.toArray());
-                    fail("expected: " + expectedString + " but was: " + actualString);
-                }
-            }
+            assertEquals(Arrays.asList(expected), mActual);
         }
     }
 }
diff --git a/data/fonts/Android.bp b/data/fonts/Android.bp
index f90a74d..3dd9ba9 100644
--- a/data/fonts/Android.bp
+++ b/data/fonts/Android.bp
@@ -52,3 +52,8 @@
     name: "fonts.xml",
     src: "fonts.xml",
 }
+
+prebuilt_etc {
+    name: "font_fallback.xml",
+    src: "font_fallback.xml",
+}
diff --git a/data/fonts/font_fallback.xml b/data/fonts/font_fallback.xml
new file mode 100644
index 0000000..1241736
--- /dev/null
+++ b/data/fonts/font_fallback.xml
@@ -0,0 +1,1626 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+    In this file, all fonts without names are added to the default list.
+    Fonts are chosen based on a match: full BCP-47 language tag including
+    script, then just language, and finally order (the first font containing
+    the glyph).
+
+    Order of appearance is also the tiebreaker for weight matching. This is
+    the reason why the 900 weights of Roboto precede the 700 weights - we
+    prefer the former when an 800 weight is requested. Since bold spans
+    effectively add 300 to the weight, this ensures that 900 is the bold
+    paired with the 500 weight, ensuring adequate contrast.
+
+    TODO(rsheeter) update comment; ordering to match 800 to 900 is no longer required
+-->
+<familyset version="23">
+    <!-- first font is default -->
+    <family name="sans-serif">
+        <font weight="100" style="normal">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="100" />
+        </font>
+        <font weight="200" style="normal">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="200" />
+        </font>
+        <font weight="300" style="normal">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="300" />
+        </font>
+        <font weight="400" style="normal">RobotoStatic-Regular.ttf</font>
+        <font weight="500" style="normal">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="500" />
+        </font>
+        <font weight="600" style="normal">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="600" />
+        </font>
+        <font weight="700" style="normal">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="700" />
+        </font>
+        <font weight="800" style="normal">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="800" />
+        </font>
+        <font weight="900" style="normal">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="900" />
+        </font>
+        <font weight="100" style="italic">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="1" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="100" />
+        </font>
+        <font weight="200" style="italic">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="1" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="200" />
+        </font>
+        <font weight="300" style="italic">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="1" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="300" />
+        </font>
+        <font weight="400" style="italic">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="1" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="400" />
+        </font>
+        <font weight="500" style="italic">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="1" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="500" />
+        </font>
+        <font weight="600" style="italic">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="1" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="600" />
+        </font>
+        <font weight="700" style="italic">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="1" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="700" />
+        </font>
+        <font weight="800" style="italic">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="1" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="800" />
+        </font>
+        <font weight="900" style="italic">Roboto-Regular.ttf
+          <axis tag="ital" stylevalue="1" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="900" />
+        </font>
+   </family>
+
+
+    <!-- Note that aliases must come after the fonts they reference. -->
+    <alias name="sans-serif-thin" to="sans-serif" weight="100" />
+    <alias name="sans-serif-light" to="sans-serif" weight="300" />
+    <alias name="sans-serif-medium" to="sans-serif" weight="500" />
+    <alias name="sans-serif-black" to="sans-serif" weight="900" />
+    <alias name="arial" to="sans-serif" />
+    <alias name="helvetica" to="sans-serif" />
+    <alias name="tahoma" to="sans-serif" />
+    <alias name="verdana" to="sans-serif" />
+
+    <family name="sans-serif-condensed">
+      <font weight="100" style="normal">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="0" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="100" />
+      </font>
+      <font weight="200" style="normal">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="0" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="200" />
+      </font>
+      <font weight="300" style="normal">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="0" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="300" />
+      </font>
+      <font weight="400" style="normal">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="0" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="400" />
+      </font>
+      <font weight="500" style="normal">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="0" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="500" />
+      </font>
+      <font weight="600" style="normal">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="0" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="600" />
+      </font>
+      <font weight="700" style="normal">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="0" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="700" />
+      </font>
+      <font weight="800" style="normal">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="0" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="800" />
+      </font>
+      <font weight="900" style="normal">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="0" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="900" />
+      </font>
+      <font weight="100" style="italic">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="1" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="100" />
+      </font>
+      <font weight="200" style="italic">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="1" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="200" />
+      </font>
+      <font weight="300" style="italic">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="1" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="300" />
+      </font>
+      <font weight="400" style="italic">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="1" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="400" />
+      </font>
+      <font weight="500" style="italic">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="1" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="500" />
+      </font>
+      <font weight="600" style="italic">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="1" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="600" />
+      </font>
+      <font weight="700" style="italic">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="1" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="700" />
+      </font>
+      <font weight="800" style="italic">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="1" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="800" />
+      </font>
+      <font weight="900" style="italic">Roboto-Regular.ttf
+        <axis tag="ital" stylevalue="1" />
+        <axis tag="wdth" stylevalue="75" />
+        <axis tag="wght" stylevalue="900" />
+      </font>
+    </family>
+    <alias name="sans-serif-condensed-light" to="sans-serif-condensed" weight="300" />
+    <alias name="sans-serif-condensed-medium" to="sans-serif-condensed" weight="500" />
+
+    <family name="serif">
+        <font weight="400" style="normal" postScriptName="NotoSerif">NotoSerif-Regular.ttf</font>
+        <font weight="700" style="normal">NotoSerif-Bold.ttf</font>
+        <font weight="400" style="italic">NotoSerif-Italic.ttf</font>
+        <font weight="700" style="italic">NotoSerif-BoldItalic.ttf</font>
+    </family>
+    <alias name="serif-bold" to="serif" weight="700" />
+    <alias name="times" to="serif" />
+    <alias name="times new roman" to="serif" />
+    <alias name="palatino" to="serif" />
+    <alias name="georgia" to="serif" />
+    <alias name="baskerville" to="serif" />
+    <alias name="goudy" to="serif" />
+    <alias name="fantasy" to="serif" />
+    <alias name="ITC Stone Serif" to="serif" />
+
+    <family name="monospace">
+        <font weight="400" style="normal">DroidSansMono.ttf</font>
+    </family>
+    <alias name="sans-serif-monospace" to="monospace" />
+    <alias name="monaco" to="monospace" />
+
+    <family name="serif-monospace">
+        <font weight="400" style="normal" postScriptName="CutiveMono-Regular">CutiveMono.ttf</font>
+    </family>
+    <alias name="courier" to="serif-monospace" />
+    <alias name="courier new" to="serif-monospace" />
+
+    <family name="casual">
+        <font weight="400" style="normal" postScriptName="ComingSoon-Regular">ComingSoon.ttf</font>
+    </family>
+
+    <family name="cursive">
+      <font weight="400" style="normal">DancingScript-Regular.ttf
+        <axis tag="wght" stylevalue="400" />
+      </font>
+      <font weight="700" style="normal">DancingScript-Regular.ttf
+        <axis tag="wght" stylevalue="700" />
+      </font>
+    </family>
+
+    <family name="sans-serif-smallcaps">
+        <font weight="400" style="normal">CarroisGothicSC-Regular.ttf</font>
+    </family>
+
+    <family name="source-sans-pro">
+        <font weight="400" style="normal">SourceSansPro-Regular.ttf</font>
+        <font weight="400" style="italic">SourceSansPro-Italic.ttf</font>
+        <font weight="600" style="normal">SourceSansPro-SemiBold.ttf</font>
+        <font weight="600" style="italic">SourceSansPro-SemiBoldItalic.ttf</font>
+        <font weight="700" style="normal">SourceSansPro-Bold.ttf</font>
+        <font weight="700" style="italic">SourceSansPro-BoldItalic.ttf</font>
+    </family>
+    <alias name="source-sans-pro-semi-bold" to="source-sans-pro" weight="600"/>
+
+    <family name="roboto-flex">
+        <font weight="100" style="normal">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="100" />
+        </font>
+        <font weight="200" style="normal">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="200" />
+        </font>
+        <font weight="300" style="normal">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="300" />
+        </font>
+        <font weight="400" style="normal">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="400" />
+        </font>
+        <font weight="500" style="normal">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="500" />
+        </font>
+        <font weight="600" style="normal">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="600" />
+        </font>
+        <font weight="700" style="normal">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="700" />
+        </font>
+        <font weight="800" style="normal">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="800" />
+        </font>
+        <font weight="900" style="normal">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="0" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="900" />
+        </font>
+        <font weight="100" style="italic">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="-10" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="100" />
+        </font>
+        <font weight="200" style="italic">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="-10" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="200" />
+        </font>
+        <font weight="300" style="italic">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="-10" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="300" />
+        </font>
+        <font weight="400" style="italic">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="-10" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="400" />
+        </font>
+        <font weight="500" style="italic">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="-10" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="500" />
+        </font>
+        <font weight="600" style="italic">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="-10" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="600" />
+        </font>
+        <font weight="700" style="italic">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="-10" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="700" />
+        </font>
+        <font weight="800" style="italic">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="-10" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="800" />
+        </font>
+        <font weight="900" style="italic">RobotoFlex-Regular.ttf
+          <axis tag="slnt" stylevalue="-10" />
+          <axis tag="wdth" stylevalue="100" />
+          <axis tag="wght" stylevalue="900" />
+        </font>
+    </family>
+
+    <!-- fallback fonts -->
+    <family lang="und-Arab" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoNaskhArabic">
+            NotoNaskhArabic-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoNaskhArabic-Bold.ttf</font>
+    </family>
+    <family lang="und-Arab" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoNaskhArabicUI">
+            NotoNaskhArabicUI-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoNaskhArabicUI-Bold.ttf</font>
+    </family>
+    <family lang="und-Ethi">
+        <font weight="400" style="normal" postScriptName="NotoSansEthiopic-Regular">
+            NotoSansEthiopic-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansEthiopic-Regular">
+            NotoSansEthiopic-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansEthiopic-Regular">
+            NotoSansEthiopic-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansEthiopic-Regular">
+            NotoSansEthiopic-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifEthiopic-Regular">NotoSerifEthiopic-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifEthiopic-Regular">NotoSerifEthiopic-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifEthiopic-Regular">NotoSerifEthiopic-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifEthiopic-Regular">NotoSerifEthiopic-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Hebr">
+        <font weight="400" style="normal" postScriptName="NotoSansHebrew">
+            NotoSansHebrew-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansHebrew-Bold.ttf</font>
+        <font weight="400" style="normal" fallbackFor="serif">NotoSerifHebrew-Regular.ttf</font>
+        <font weight="700" style="normal" fallbackFor="serif">NotoSerifHebrew-Bold.ttf</font>
+    </family>
+    <family lang="und-Thai" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansThai">NotoSansThai-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansThai-Bold.ttf</font>
+        <font weight="400" style="normal" fallbackFor="serif">
+            NotoSerifThai-Regular.ttf
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif">NotoSerifThai-Bold.ttf</font>
+    </family>
+    <family lang="und-Thai" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansThaiUI">
+            NotoSansThaiUI-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansThaiUI-Bold.ttf</font>
+    </family>
+    <family lang="und-Armn">
+        <font weight="400" style="normal" postScriptName="NotoSansArmenian-Regular">
+            NotoSansArmenian-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansArmenian-Regular">
+            NotoSansArmenian-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansArmenian-Regular">
+            NotoSansArmenian-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansArmenian-Regular">
+            NotoSansArmenian-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifArmenian-Regular">NotoSerifArmenian-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifArmenian-Regular">NotoSerifArmenian-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifArmenian-Regular">NotoSerifArmenian-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifArmenian-Regular">NotoSerifArmenian-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Geor,und-Geok">
+        <font weight="400" style="normal" postScriptName="NotoSansGeorgian-Regular">
+            NotoSansGeorgian-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansGeorgian-Regular">
+            NotoSansGeorgian-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansGeorgian-Regular">
+            NotoSansGeorgian-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansGeorgian-Regular">
+            NotoSansGeorgian-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGeorgian-Regular">NotoSerifGeorgian-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGeorgian-Regular">NotoSerifGeorgian-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGeorgian-Regular">NotoSerifGeorgian-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGeorgian-Regular">NotoSerifGeorgian-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Deva" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansDevanagari-Regular">
+            NotoSansDevanagari-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansDevanagari-Regular">
+            NotoSansDevanagari-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansDevanagari-Regular">
+            NotoSansDevanagari-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansDevanagari-Regular">
+            NotoSansDevanagari-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifDevanagari-Regular">NotoSerifDevanagari-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifDevanagari-Regular">NotoSerifDevanagari-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifDevanagari-Regular">NotoSerifDevanagari-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifDevanagari-Regular">NotoSerifDevanagari-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Deva" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansDevanagariUI-Regular">
+            NotoSansDevanagariUI-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansDevanagariUI-Regular">
+            NotoSansDevanagariUI-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansDevanagariUI-Regular">
+            NotoSansDevanagariUI-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansDevanagariUI-Regular">
+            NotoSansDevanagariUI-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+
+    <!-- All scripts of India should come after Devanagari, due to shared
+         danda characters.
+    -->
+    <family lang="und-Gujr" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansGujarati">
+            NotoSansGujarati-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansGujarati-Bold.ttf</font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGujarati-Regular">NotoSerifGujarati-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGujarati-Regular">NotoSerifGujarati-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGujarati-Regular">NotoSerifGujarati-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGujarati-Regular">NotoSerifGujarati-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Gujr" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansGujaratiUI">
+            NotoSansGujaratiUI-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansGujaratiUI-Bold.ttf</font>
+    </family>
+    <family lang="und-Guru" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansGurmukhi-Regular">
+            NotoSansGurmukhi-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansGurmukhi-Regular">
+            NotoSansGurmukhi-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansGurmukhi-Regular">
+            NotoSansGurmukhi-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansGurmukhi-Regular">
+            NotoSansGurmukhi-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGurmukhi-Regular">NotoSerifGurmukhi-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGurmukhi-Regular">NotoSerifGurmukhi-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGurmukhi-Regular">NotoSerifGurmukhi-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifGurmukhi-Regular">NotoSerifGurmukhi-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Guru" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansGurmukhiUI-Regular">
+            NotoSansGurmukhiUI-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansGurmukhiUI-Regular">
+            NotoSansGurmukhiUI-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansGurmukhiUI-Regular">
+            NotoSansGurmukhiUI-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansGurmukhiUI-Regular">
+            NotoSansGurmukhiUI-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Taml" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansTamil-Regular">
+            NotoSansTamil-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansTamil-Regular">
+            NotoSansTamil-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansTamil-Regular">
+            NotoSansTamil-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansTamil-Regular">
+            NotoSansTamil-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifTamil-Regular">NotoSerifTamil-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifTamil-Regular">NotoSerifTamil-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifTamil-Regular">NotoSerifTamil-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifTamil-Regular">NotoSerifTamil-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Taml" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansTamilUI-Regular">
+            NotoSansTamilUI-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansTamilUI-Regular">
+            NotoSansTamilUI-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansTamilUI-Regular">
+            NotoSansTamilUI-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansTamilUI-Regular">
+            NotoSansTamilUI-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Mlym" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansMalayalam-Regular">
+            NotoSansMalayalam-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansMalayalam-Regular">
+            NotoSansMalayalam-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansMalayalam-Regular">
+            NotoSansMalayalam-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansMalayalam-Regular">
+            NotoSansMalayalam-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifMalayalam-Regular">NotoSerifMalayalam-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifMalayalam-Regular">NotoSerifMalayalam-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifMalayalam-Regular">NotoSerifMalayalam-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifMalayalam-Regular">NotoSerifMalayalam-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Mlym" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansMalayalamUI-Regular">
+            NotoSansMalayalamUI-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansMalayalamUI-Regular">
+            NotoSansMalayalamUI-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansMalayalamUI-Regular">
+            NotoSansMalayalamUI-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansMalayalamUI-Regular">
+            NotoSansMalayalamUI-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Beng" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansBengali-Regular">
+            NotoSansBengali-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansBengali-Regular">
+            NotoSansBengali-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansBengali-Regular">
+            NotoSansBengali-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansBengali-Regular">
+            NotoSansBengali-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifBengali-Regular">NotoSerifBengali-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifBengali-Regular">NotoSerifBengali-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifBengali-Regular">NotoSerifBengali-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifBengali-Regular">NotoSerifBengali-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Beng" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansBengaliUI-Regular">
+            NotoSansBengaliUI-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansBengaliUI-Regular">
+            NotoSansBengaliUI-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansBengaliUI-Regular">
+            NotoSansBengaliUI-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansBengaliUI-Regular">
+            NotoSansBengaliUI-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Telu" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansTelugu-Regular">
+            NotoSansTelugu-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansTelugu-Regular">
+            NotoSansTelugu-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansTelugu-Regular">
+            NotoSansTelugu-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansTelugu-Regular">
+            NotoSansTelugu-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifTelugu-Regular">NotoSerifTelugu-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifTelugu-Regular">NotoSerifTelugu-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifTelugu-Regular">NotoSerifTelugu-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifTelugu-Regular">NotoSerifTelugu-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Telu" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansTeluguUI-Regular">
+            NotoSansTeluguUI-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansTeluguUI-Regular">
+            NotoSansTeluguUI-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansTeluguUI-Regular">
+            NotoSansTeluguUI-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansTeluguUI-Regular">
+            NotoSansTeluguUI-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Knda" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansKannada-Regular">
+            NotoSansKannada-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansKannada-Regular">
+            NotoSansKannada-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansKannada-Regular">
+            NotoSansKannada-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansKannada-Regular">
+            NotoSansKannada-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifKannada-Regular">NotoSerifKannada-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifKannada-Regular">NotoSerifKannada-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifKannada-Regular">NotoSerifKannada-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifKannada-Regular">NotoSerifKannada-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Knda" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansKannadaUI-Regular">
+            NotoSansKannadaUI-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansKannadaUI-Regular">
+            NotoSansKannadaUI-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansKannadaUI-Regular">
+            NotoSansKannadaUI-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansKannadaUI-Regular">
+            NotoSansKannadaUI-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Orya" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansOriya">NotoSansOriya-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansOriya-Bold.ttf</font>
+    </family>
+    <family lang="und-Orya" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansOriyaUI">
+            NotoSansOriyaUI-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansOriyaUI-Bold.ttf</font>
+    </family>
+    <family lang="und-Sinh" variant="elegant">
+        <font weight="400" style="normal" postScriptName="NotoSansSinhala-Regular">
+            NotoSansSinhala-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansSinhala-Regular">
+            NotoSansSinhala-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansSinhala-Regular">
+            NotoSansSinhala-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansSinhala-Regular">
+            NotoSansSinhala-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifSinhala-Regular">NotoSerifSinhala-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifSinhala-Regular">NotoSerifSinhala-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifSinhala-Regular">NotoSerifSinhala-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif"
+              postScriptName="NotoSerifSinhala-Regular">NotoSerifSinhala-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Sinh" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansSinhalaUI-Regular">
+            NotoSansSinhalaUI-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansSinhalaUI-Regular">
+            NotoSansSinhalaUI-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansSinhalaUI-Regular">
+            NotoSansSinhalaUI-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansSinhalaUI-Regular">
+            NotoSansSinhalaUI-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Khmr" variant="elegant">
+        <font weight="100" style="normal" postScriptName="NotoSansKhmer-Regular">
+            NotoSansKhmer-VF.ttf
+            <axis tag="wdth" stylevalue="100.0"/>
+            <axis tag="wght" stylevalue="26.0"/>
+        </font>
+        <font weight="200" style="normal" postScriptName="NotoSansKhmer-Regular">
+            NotoSansKhmer-VF.ttf
+            <axis tag="wdth" stylevalue="100.0"/>
+            <axis tag="wght" stylevalue="39.0"/>
+        </font>
+        <font weight="300" style="normal" postScriptName="NotoSansKhmer-Regular">
+            NotoSansKhmer-VF.ttf
+            <axis tag="wdth" stylevalue="100.0"/>
+            <axis tag="wght" stylevalue="58.0"/>
+        </font>
+        <font weight="400" style="normal" postScriptName="NotoSansKhmer-Regular">
+            NotoSansKhmer-VF.ttf
+            <axis tag="wdth" stylevalue="100.0"/>
+            <axis tag="wght" stylevalue="90.0"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansKhmer-Regular">
+            NotoSansKhmer-VF.ttf
+            <axis tag="wdth" stylevalue="100.0"/>
+            <axis tag="wght" stylevalue="108.0"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansKhmer-Regular">
+            NotoSansKhmer-VF.ttf
+            <axis tag="wdth" stylevalue="100.0"/>
+            <axis tag="wght" stylevalue="128.0"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansKhmer-Regular">
+            NotoSansKhmer-VF.ttf
+            <axis tag="wdth" stylevalue="100.0"/>
+            <axis tag="wght" stylevalue="151.0"/>
+        </font>
+        <font weight="800" style="normal" postScriptName="NotoSansKhmer-Regular">
+            NotoSansKhmer-VF.ttf
+            <axis tag="wdth" stylevalue="100.0"/>
+            <axis tag="wght" stylevalue="169.0"/>
+        </font>
+        <font weight="900" style="normal" postScriptName="NotoSansKhmer-Regular">
+            NotoSansKhmer-VF.ttf
+            <axis tag="wdth" stylevalue="100.0"/>
+            <axis tag="wght" stylevalue="190.0"/>
+        </font>
+        <font weight="400" style="normal" fallbackFor="serif">NotoSerifKhmer-Regular.otf</font>
+        <font weight="700" style="normal" fallbackFor="serif">NotoSerifKhmer-Bold.otf</font>
+    </family>
+    <family lang="und-Khmr" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansKhmerUI">
+            NotoSansKhmerUI-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansKhmerUI-Bold.ttf</font>
+    </family>
+    <family lang="und-Laoo" variant="elegant">
+        <font weight="400" style="normal">NotoSansLao-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansLao-Bold.ttf</font>
+        <font weight="400" style="normal" fallbackFor="serif">
+            NotoSerifLao-Regular.ttf
+        </font>
+        <font weight="700" style="normal" fallbackFor="serif">NotoSerifLao-Bold.ttf</font>
+    </family>
+    <family lang="und-Laoo" variant="compact">
+        <font weight="400" style="normal" postScriptName="NotoSansLaoUI">NotoSansLaoUI-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansLaoUI-Bold.ttf</font>
+    </family>
+    <family lang="und-Mymr" variant="elegant">
+        <font weight="400" style="normal">NotoSansMyanmar-Regular.otf</font>
+        <font weight="500" style="normal">NotoSansMyanmar-Medium.otf</font>
+        <font weight="700" style="normal">NotoSansMyanmar-Bold.otf</font>
+        <font weight="400" style="normal" fallbackFor="serif">NotoSerifMyanmar-Regular.otf</font>
+        <font weight="700" style="normal" fallbackFor="serif">NotoSerifMyanmar-Bold.otf</font>
+    </family>
+    <family lang="und-Mymr" variant="compact">
+        <font weight="400" style="normal">NotoSansMyanmarUI-Regular.otf</font>
+        <font weight="500" style="normal">NotoSansMyanmarUI-Medium.otf</font>
+        <font weight="700" style="normal">NotoSansMyanmarUI-Bold.otf</font>
+    </family>
+    <family lang="und-Thaa">
+        <font weight="400" style="normal" postScriptName="NotoSansThaana">
+            NotoSansThaana-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansThaana-Bold.ttf</font>
+    </family>
+    <family lang="und-Cham">
+        <font weight="400" style="normal" postScriptName="NotoSansCham">NotoSansCham-Regular.ttf
+        </font>
+        <font weight="700" style="normal">NotoSansCham-Bold.ttf</font>
+    </family>
+    <family lang="und-Ahom">
+        <font weight="400" style="normal">NotoSansAhom-Regular.otf</font>
+    </family>
+    <family lang="und-Adlm">
+        <font weight="400" style="normal" postScriptName="NotoSansAdlam-Regular">
+            NotoSansAdlam-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansAdlam-Regular">
+            NotoSansAdlam-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansAdlam-Regular">
+            NotoSansAdlam-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansAdlam-Regular">
+            NotoSansAdlam-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Avst">
+        <font weight="400" style="normal" postScriptName="NotoSansAvestan">
+            NotoSansAvestan-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Bali">
+        <font weight="400" style="normal" postScriptName="NotoSansBalinese">
+            NotoSansBalinese-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Bamu">
+        <font weight="400" style="normal" postScriptName="NotoSansBamum">NotoSansBamum-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Batk">
+        <font weight="400" style="normal" postScriptName="NotoSansBatak">NotoSansBatak-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Brah">
+        <font weight="400" style="normal" postScriptName="NotoSansBrahmi">
+            NotoSansBrahmi-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Bugi">
+        <font weight="400" style="normal" postScriptName="NotoSansBuginese">
+            NotoSansBuginese-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Buhd">
+        <font weight="400" style="normal" postScriptName="NotoSansBuhid">NotoSansBuhid-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Cans">
+        <font weight="400" style="normal">
+            NotoSansCanadianAboriginal-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Cari">
+        <font weight="400" style="normal" postScriptName="NotoSansCarian">
+            NotoSansCarian-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Cakm">
+        <font weight="400" style="normal">NotoSansChakma-Regular.otf</font>
+    </family>
+    <family lang="und-Cher">
+        <font weight="400" style="normal">NotoSansCherokee-Regular.ttf</font>
+    </family>
+    <family lang="und-Copt">
+        <font weight="400" style="normal" postScriptName="NotoSansCoptic">
+            NotoSansCoptic-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Xsux">
+        <font weight="400" style="normal" postScriptName="NotoSansCuneiform">
+            NotoSansCuneiform-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Cprt">
+        <font weight="400" style="normal" postScriptName="NotoSansCypriot">
+            NotoSansCypriot-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Dsrt">
+        <font weight="400" style="normal" postScriptName="NotoSansDeseret">
+            NotoSansDeseret-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Egyp">
+        <font weight="400" style="normal" postScriptName="NotoSansEgyptianHieroglyphs">
+            NotoSansEgyptianHieroglyphs-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Elba">
+        <font weight="400" style="normal">NotoSansElbasan-Regular.otf</font>
+    </family>
+    <family lang="und-Glag">
+        <font weight="400" style="normal" postScriptName="NotoSansGlagolitic">
+            NotoSansGlagolitic-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Goth">
+        <font weight="400" style="normal" postScriptName="NotoSansGothic">
+            NotoSansGothic-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Hano">
+        <font weight="400" style="normal" postScriptName="NotoSansHanunoo">
+            NotoSansHanunoo-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Armi">
+        <font weight="400" style="normal" postScriptName="NotoSansImperialAramaic">
+            NotoSansImperialAramaic-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Phli">
+        <font weight="400" style="normal" postScriptName="NotoSansInscriptionalPahlavi">
+            NotoSansInscriptionalPahlavi-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Prti">
+        <font weight="400" style="normal" postScriptName="NotoSansInscriptionalParthian">
+            NotoSansInscriptionalParthian-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Java">
+        <font weight="400" style="normal">NotoSansJavanese-Regular.otf</font>
+    </family>
+    <family lang="und-Kthi">
+        <font weight="400" style="normal" postScriptName="NotoSansKaithi">
+            NotoSansKaithi-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Kali">
+        <font weight="400" style="normal" postScriptName="NotoSansKayahLi">
+            NotoSansKayahLi-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Khar">
+        <font weight="400" style="normal" postScriptName="NotoSansKharoshthi">
+            NotoSansKharoshthi-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Lepc">
+        <font weight="400" style="normal" postScriptName="NotoSansLepcha">
+            NotoSansLepcha-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Limb">
+        <font weight="400" style="normal" postScriptName="NotoSansLimbu">NotoSansLimbu-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Linb">
+        <font weight="400" style="normal" postScriptName="NotoSansLinearB">
+            NotoSansLinearB-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Lisu">
+        <font weight="400" style="normal" postScriptName="NotoSansLisu">NotoSansLisu-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Lyci">
+        <font weight="400" style="normal" postScriptName="NotoSansLycian">
+            NotoSansLycian-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Lydi">
+        <font weight="400" style="normal" postScriptName="NotoSansLydian">
+            NotoSansLydian-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Mand">
+        <font weight="400" style="normal" postScriptName="NotoSansMandaic">
+            NotoSansMandaic-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Mtei">
+        <font weight="400" style="normal" postScriptName="NotoSansMeeteiMayek">
+            NotoSansMeeteiMayek-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Talu">
+        <font weight="400" style="normal" postScriptName="NotoSansNewTaiLue">
+            NotoSansNewTaiLue-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Nkoo">
+        <font weight="400" style="normal" postScriptName="NotoSansNKo">NotoSansNKo-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Ogam">
+        <font weight="400" style="normal" postScriptName="NotoSansOgham">NotoSansOgham-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Olck">
+        <font weight="400" style="normal" postScriptName="NotoSansOlChiki">
+            NotoSansOlChiki-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Ital">
+        <font weight="400" style="normal" postScriptName="NotoSansOldItalic">
+            NotoSansOldItalic-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Xpeo">
+        <font weight="400" style="normal" postScriptName="NotoSansOldPersian">
+            NotoSansOldPersian-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Sarb">
+        <font weight="400" style="normal" postScriptName="NotoSansOldSouthArabian">
+            NotoSansOldSouthArabian-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Orkh">
+        <font weight="400" style="normal" postScriptName="NotoSansOldTurkic">
+            NotoSansOldTurkic-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Osge">
+        <font weight="400" style="normal">NotoSansOsage-Regular.ttf</font>
+    </family>
+    <family lang="und-Osma">
+        <font weight="400" style="normal" postScriptName="NotoSansOsmanya">
+            NotoSansOsmanya-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Phnx">
+        <font weight="400" style="normal" postScriptName="NotoSansPhoenician">
+            NotoSansPhoenician-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Rjng">
+        <font weight="400" style="normal" postScriptName="NotoSansRejang">
+            NotoSansRejang-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Runr">
+        <font weight="400" style="normal" postScriptName="NotoSansRunic">NotoSansRunic-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Samr">
+        <font weight="400" style="normal" postScriptName="NotoSansSamaritan">
+            NotoSansSamaritan-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Saur">
+        <font weight="400" style="normal" postScriptName="NotoSansSaurashtra">
+            NotoSansSaurashtra-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Shaw">
+        <font weight="400" style="normal" postScriptName="NotoSansShavian">
+            NotoSansShavian-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Sund">
+        <font weight="400" style="normal" postScriptName="NotoSansSundanese">
+            NotoSansSundanese-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Sylo">
+        <font weight="400" style="normal" postScriptName="NotoSansSylotiNagri">
+            NotoSansSylotiNagri-Regular.ttf
+        </font>
+    </family>
+    <!-- Esrangela should precede Eastern and Western Syriac, since it's our default form. -->
+    <family lang="und-Syre">
+        <font weight="400" style="normal" postScriptName="NotoSansSyriacEstrangela">
+            NotoSansSyriacEstrangela-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Syrn">
+        <font weight="400" style="normal" postScriptName="NotoSansSyriacEastern">
+            NotoSansSyriacEastern-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Syrj">
+        <font weight="400" style="normal" postScriptName="NotoSansSyriacWestern">
+            NotoSansSyriacWestern-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Tglg">
+        <font weight="400" style="normal" postScriptName="NotoSansTagalog">
+            NotoSansTagalog-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Tagb">
+        <font weight="400" style="normal" postScriptName="NotoSansTagbanwa">
+            NotoSansTagbanwa-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Lana">
+        <font weight="400" style="normal" postScriptName="NotoSansTaiTham">
+            NotoSansTaiTham-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Tavt">
+        <font weight="400" style="normal" postScriptName="NotoSansTaiViet">
+            NotoSansTaiViet-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Tibt">
+        <font weight="400" style="normal" postScriptName="NotoSerifTibetan-Regular">
+            NotoSerifTibetan-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSerifTibetan-Regular">
+            NotoSerifTibetan-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSerifTibetan-Regular">
+            NotoSerifTibetan-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSerifTibetan-Regular">
+            NotoSerifTibetan-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Tfng">
+        <font weight="400" style="normal">NotoSansTifinagh-Regular.otf</font>
+    </family>
+    <family lang="und-Ugar">
+        <font weight="400" style="normal" postScriptName="NotoSansUgaritic">
+            NotoSansUgaritic-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Vaii">
+        <font weight="400" style="normal" postScriptName="NotoSansVai">NotoSansVai-Regular.ttf
+        </font>
+    </family>
+    <family>
+        <font weight="400" style="normal">NotoSansSymbols-Regular-Subsetted.ttf</font>
+    </family>
+    <family lang="zh-Hans">
+        <font weight="400" style="normal" index="2" postScriptName="NotoSansCJKjp-Regular">
+            NotoSansCJK-Regular.ttc
+        </font>
+        <font weight="400" style="normal" index="2" fallbackFor="serif"
+              postScriptName="NotoSerifCJKjp-Regular">NotoSerifCJK-Regular.ttc
+        </font>
+    </family>
+    <family lang="zh-Hant,zh-Bopo">
+        <font weight="400" style="normal" index="3" postScriptName="NotoSansCJKjp-Regular">
+            NotoSansCJK-Regular.ttc
+        </font>
+        <font weight="400" style="normal" index="3" fallbackFor="serif"
+              postScriptName="NotoSerifCJKjp-Regular">NotoSerifCJK-Regular.ttc
+        </font>
+    </family>
+    <family lang="ja">
+        <font weight="400" style="normal" index="0" postScriptName="NotoSansCJKjp-Regular">
+            NotoSansCJK-Regular.ttc
+        </font>
+        <font weight="400" style="normal" index="0" fallbackFor="serif"
+              postScriptName="NotoSerifCJKjp-Regular">NotoSerifCJK-Regular.ttc
+        </font>
+    </family>
+    <family lang="ko">
+        <font weight="400" style="normal" index="1" postScriptName="NotoSansCJKjp-Regular">
+            NotoSansCJK-Regular.ttc
+        </font>
+        <font weight="400" style="normal" index="1" fallbackFor="serif"
+              postScriptName="NotoSerifCJKjp-Regular">NotoSerifCJK-Regular.ttc
+        </font>
+    </family>
+    <family lang="und-Zsye">
+        <font weight="400" style="normal">NotoColorEmoji.ttf</font>
+    </family>
+    <family lang="und-Zsye">
+        <font weight="400" style="normal">NotoColorEmojiFlags.ttf</font>
+    </family>
+    <family lang="und-Zsym">
+        <font weight="400" style="normal">NotoSansSymbols-Regular-Subsetted2.ttf</font>
+    </family>
+    <!--
+        Tai Le, Yi, Mongolian, and Phags-pa are intentionally kept last, to make sure they don't
+        override the East Asian punctuation for Chinese.
+    -->
+    <family lang="und-Tale">
+        <font weight="400" style="normal" postScriptName="NotoSansTaiLe">NotoSansTaiLe-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Yiii">
+        <font weight="400" style="normal" postScriptName="NotoSansYi">NotoSansYi-Regular.ttf</font>
+    </family>
+    <family lang="und-Mong">
+        <font weight="400" style="normal" postScriptName="NotoSansMongolian">
+            NotoSansMongolian-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Phag">
+        <font weight="400" style="normal" postScriptName="NotoSansPhagsPa">
+            NotoSansPhagsPa-Regular.ttf
+        </font>
+    </family>
+    <family lang="und-Hluw">
+        <font weight="400" style="normal">NotoSansAnatolianHieroglyphs-Regular.otf</font>
+    </family>
+    <family lang="und-Bass">
+        <font weight="400" style="normal">NotoSansBassaVah-Regular.otf</font>
+    </family>
+    <family lang="und-Bhks">
+        <font weight="400" style="normal">NotoSansBhaiksuki-Regular.otf</font>
+    </family>
+    <family lang="und-Hatr">
+        <font weight="400" style="normal">NotoSansHatran-Regular.otf</font>
+    </family>
+    <family lang="und-Lina">
+        <font weight="400" style="normal">NotoSansLinearA-Regular.otf</font>
+    </family>
+    <family lang="und-Mani">
+        <font weight="400" style="normal">NotoSansManichaean-Regular.otf</font>
+    </family>
+    <family lang="und-Marc">
+        <font weight="400" style="normal">NotoSansMarchen-Regular.otf</font>
+    </family>
+    <family lang="und-Merc">
+        <font weight="400" style="normal">NotoSansMeroitic-Regular.otf</font>
+    </family>
+    <family lang="und-Plrd">
+        <font weight="400" style="normal">NotoSansMiao-Regular.otf</font>
+    </family>
+    <family lang="und-Mroo">
+        <font weight="400" style="normal">NotoSansMro-Regular.otf</font>
+    </family>
+    <family lang="und-Mult">
+        <font weight="400" style="normal">NotoSansMultani-Regular.otf</font>
+    </family>
+    <family lang="und-Nbat">
+        <font weight="400" style="normal">NotoSansNabataean-Regular.otf</font>
+    </family>
+    <family lang="und-Newa">
+        <font weight="400" style="normal">NotoSansNewa-Regular.otf</font>
+    </family>
+    <family lang="und-Narb">
+        <font weight="400" style="normal">NotoSansOldNorthArabian-Regular.otf</font>
+    </family>
+    <family lang="und-Perm">
+        <font weight="400" style="normal">NotoSansOldPermic-Regular.otf</font>
+    </family>
+    <family lang="und-Hmng">
+        <font weight="400" style="normal">NotoSansPahawhHmong-Regular.otf</font>
+    </family>
+    <family lang="und-Palm">
+        <font weight="400" style="normal">NotoSansPalmyrene-Regular.otf</font>
+    </family>
+    <family lang="und-Pauc">
+        <font weight="400" style="normal">NotoSansPauCinHau-Regular.otf</font>
+    </family>
+    <family lang="und-Shrd">
+        <font weight="400" style="normal">NotoSansSharada-Regular.otf</font>
+    </family>
+    <family lang="und-Sora">
+        <font weight="400" style="normal">NotoSansSoraSompeng-Regular.otf</font>
+    </family>
+    <family lang="und-Gong">
+        <font weight="400" style="normal">NotoSansGunjalaGondi-Regular.otf</font>
+    </family>
+    <family lang="und-Rohg">
+        <font weight="400" style="normal">NotoSansHanifiRohingya-Regular.otf</font>
+    </family>
+    <family lang="und-Khoj">
+        <font weight="400" style="normal">NotoSansKhojki-Regular.otf</font>
+    </family>
+    <family lang="und-Gonm">
+        <font weight="400" style="normal">NotoSansMasaramGondi-Regular.otf</font>
+    </family>
+    <family lang="und-Wcho">
+        <font weight="400" style="normal">NotoSansWancho-Regular.otf</font>
+    </family>
+    <family lang="und-Wara">
+        <font weight="400" style="normal">NotoSansWarangCiti-Regular.otf</font>
+    </family>
+    <family lang="und-Gran">
+        <font weight="400" style="normal">NotoSansGrantha-Regular.ttf</font>
+    </family>
+    <family lang="und-Modi">
+        <font weight="400" style="normal">NotoSansModi-Regular.ttf</font>
+    </family>
+    <family lang="und-Dogr">
+        <font weight="400" style="normal">NotoSerifDogra-Regular.ttf</font>
+    </family>
+    <family lang="und-Medf">
+        <font weight="400" style="normal" postScriptName="NotoSansMedefaidrin-Regular">
+            NotoSansMedefaidrin-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansMedefaidrin-Regular">
+            NotoSansMedefaidrin-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansMedefaidrin-Regular">
+            NotoSansMedefaidrin-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansMedefaidrin-Regular">
+            NotoSansMedefaidrin-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Soyo">
+        <font weight="400" style="normal" postScriptName="NotoSansSoyombo-Regular">
+            NotoSansSoyombo-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansSoyombo-Regular">
+            NotoSansSoyombo-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansSoyombo-Regular">
+            NotoSansSoyombo-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansSoyombo-Regular">
+            NotoSansSoyombo-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Takr">
+        <font weight="400" style="normal" postScriptName="NotoSansTakri-Regular">
+            NotoSansTakri-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSansTakri-Regular">
+            NotoSansTakri-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSansTakri-Regular">
+            NotoSansTakri-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSansTakri-Regular">
+            NotoSansTakri-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Hmnp">
+        <font weight="400" style="normal" postScriptName="NotoSerifHmongNyiakeng-Regular">
+            NotoSerifNyiakengPuachueHmong-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSerifHmongNyiakeng-Regular">
+            NotoSerifNyiakengPuachueHmong-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSerifHmongNyiakeng-Regular">
+            NotoSerifNyiakengPuachueHmong-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSerifHmongNyiakeng-Regular">
+            NotoSerifNyiakengPuachueHmong-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+    <family lang="und-Yezi">
+        <font weight="400" style="normal" postScriptName="NotoSerifYezidi-Regular">
+            NotoSerifYezidi-VF.ttf
+            <axis tag="wght" stylevalue="400"/>
+        </font>
+        <font weight="500" style="normal" postScriptName="NotoSerifYezidi-Regular">
+            NotoSerifYezidi-VF.ttf
+            <axis tag="wght" stylevalue="500"/>
+        </font>
+        <font weight="600" style="normal" postScriptName="NotoSerifYezidi-Regular">
+            NotoSerifYezidi-VF.ttf
+            <axis tag="wght" stylevalue="600"/>
+        </font>
+        <font weight="700" style="normal" postScriptName="NotoSerifYezidi-Regular">
+            NotoSerifYezidi-VF.ttf
+            <axis tag="wght" stylevalue="700"/>
+        </font>
+    </family>
+</familyset>
diff --git a/data/fonts/fonts.mk b/data/fonts/fonts.mk
index e884f2f..5d1cc66 100644
--- a/data/fonts/fonts.mk
+++ b/data/fonts/fonts.mk
@@ -17,4 +17,5 @@
 PRODUCT_PACKAGES := \
     DroidSansMono.ttf \
     AndroidClock.ttf \
+    font_fallback.xml \
     fonts.xml
diff --git a/data/fonts/fonts.xml b/data/fonts/fonts.xml
index ab323ad..3465627 100644
--- a/data/fonts/fonts.xml
+++ b/data/fonts/fonts.xml
@@ -1,5 +1,17 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
+    DEPRECATED: This XML file is no longer a source of the font files installed
+    in the system.
+
+    For the device vendors: please add your font configurations to the
+    platform/frameworks/base/data/font_fallback.xml and also add it to this XML
+    file as much as possible for apps that reads this XML file.
+
+    For the application developers: please stop reading this XML file and use
+    android.graphics.fonts.SystemFonts#getAvailableFonts Java API or
+    ASystemFontIterator_open NDK API for getting list of system installed
+    font files.
+
     WARNING: Parsing of this file by third-party apps is not supported. The
     file, and the font files it refers to, will be renamed and/or moved out
     from their respective location in the next Android release, and/or the
diff --git a/data/keyboards/qwerty.idc b/data/keyboards/qwerty.idc
deleted file mode 100644
index 375d785..0000000
--- a/data/keyboards/qwerty.idc
+++ /dev/null
@@ -1,28 +0,0 @@
-# Copyright (C) 2010 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.
-
-#
-# Emulator keyboard configuration file #1.
-#
-
-touch.deviceType = touchScreen
-touch.orientationAware = 1
-
-keyboard.layout = qwerty
-keyboard.characterMap = qwerty
-keyboard.orientationAware = 1
-keyboard.builtIn = 1
-
-cursor.mode = navigation
-cursor.orientationAware = 1
diff --git a/data/keyboards/qwerty.kcm b/data/keyboards/qwerty.kcm
deleted file mode 100644
index f3e1524..0000000
--- a/data/keyboards/qwerty.kcm
+++ /dev/null
@@ -1,508 +0,0 @@
-# Copyright (C) 2010 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.
-
-#
-# Emulator keyboard character map #1.
-#
-# This file is no longer used as the platform's default keyboard character map.
-# Refer to Generic.kcm and Virtual.kcm instead.
-#
-
-type ALPHA
-
-key A {
-    label:                              'A'
-    number:                             '2'
-    base:                               'a'
-    shift, capslock:                    'A'
-    alt:                                '#'
-    shift+alt, capslock+alt:            none
-}
-
-key B {
-    label:                              'B'
-    number:                             '2'
-    base:                               'b'
-    shift, capslock:                    'B'
-    alt:                                '<'
-    shift+alt, capslock+alt:            none
-}
-
-key C {
-    label:                              'C'
-    number:                             '2'
-    base:                               'c'
-    shift, capslock:                    'C'
-    alt:                                '9'
-    shift+alt, capslock+alt:            '\u00e7'
-}
-
-key D {
-    label:                              'D'
-    number:                             '3'
-    base:                               'd'
-    shift, capslock:                    'D'
-    alt:                                '5'
-    shift+alt, capslock+alt:            none
-}
-
-key E {
-    label:                              'E'
-    number:                             '3'
-    base:                               'e'
-    shift, capslock:                    'E'
-    alt:                                '2'
-    shift+alt, capslock+alt:            '\u0301'
-}
-
-key F {
-    label:                              'F'
-    number:                             '3'
-    base:                               'f'
-    shift, capslock:                    'F'
-    alt:                                '6'
-    shift+alt, capslock+alt:            '\u00a5'
-}
-
-key G {
-    label:                              'G'
-    number:                             '4'
-    base:                               'g'
-    shift, capslock:                    'G'
-    alt:                                '-'
-    shift+alt, capslock+alt:            '_'
-}
-
-key H {
-    label:                              'H'
-    number:                             '4'
-    base:                               'h'
-    shift, capslock:                    'H'
-    alt:                                '['
-    shift+alt, capslock+alt:            '{'
-}
-
-key I {
-    label:                              'I'
-    number:                             '4'
-    base:                               'i'
-    shift, capslock:                    'I'
-    alt:                                '$'
-    shift+alt, capslock+alt:            '\u0302'
-}
-
-key J {
-    label:                              'J'
-    number:                             '5'
-    base:                               'j'
-    shift, capslock:                    'J'
-    alt:                                ']'
-    shift+alt, capslock+alt:            '}'
-}
-
-key K {
-    label:                              'K'
-    number:                             '5'
-    base:                               'k'
-    shift, capslock:                    'K'
-    alt:                                '"'
-    shift+alt, capslock+alt:            '~'
-}
-
-key L {
-    label:                              'L'
-    number:                             '5'
-    base:                               'l'
-    shift, capslock:                    'L'
-    alt:                                '\''
-    shift+alt, capslock+alt:            '`'
-}
-
-key M {
-    label:                              'M'
-    number:                             '6'
-    base:                               'm'
-    shift, capslock:                    'M'
-    alt:                                '!'
-    shift+alt, capslock+alt:            none
-}
-
-key N {
-    label:                              'N'
-    number:                             '6'
-    base:                               'n'
-    shift, capslock:                    'N'
-    alt:                                '>'
-    shift+alt, capslock+alt:            '\u0303'
-}
-
-key O {
-    label:                              'O'
-    number:                             '6'
-    base:                               'o'
-    shift, capslock:                    'O'
-    alt:                                '('
-    shift+alt, capslock+alt:            none
-}
-
-key P {
-    label:                              'P'
-    number:                             '7'
-    base:                               'p'
-    shift, capslock:                    'P'
-    alt:                                ')'
-    shift+alt, capslock+alt:            none
-}
-
-key Q {
-    label:                              'Q'
-    number:                             '7'
-    base:                               'q'
-    shift, capslock:                    'Q'
-    alt:                                '*'
-    shift+alt, capslock+alt:            '\u0300'
-}
-
-key R {
-    label:                              'R'
-    number:                             '7'
-    base:                               'r'
-    shift, capslock:                    'R'
-    alt:                                '3'
-    shift+alt, capslock+alt:            '\u20ac'
-}
-
-key S {
-    label:                              'S'
-    number:                             '7'
-    base:                               's'
-    shift, capslock:                    'S'
-    alt:                                '4'
-    shift+alt, capslock+alt:            '\u00df'
-}
-
-key T {
-    label:                              'T'
-    number:                             '8'
-    base:                               't'
-    shift, capslock:                    'T'
-    alt:                                '+'
-    shift+alt, capslock+alt:            '\u00a3'
-}
-
-key U {
-    label:                              'U'
-    number:                             '8'
-    base:                               'u'
-    shift, capslock:                    'U'
-    alt:                                '&'
-    shift+alt, capslock+alt:            '\u0308'
-}
-
-key V {
-    label:                              'V'
-    number:                             '8'
-    base:                               'v'
-    shift, capslock:                    'V'
-    alt:                                '='
-    shift+alt, capslock+alt:            '^'
-}
-
-key W {
-    label:                              'W'
-    number:                             '9'
-    base:                               'w'
-    shift, capslock:                    'W'
-    alt:                                '1'
-    shift+alt, capslock+alt:            none
-}
-
-key X {
-    label:                              'X'
-    number:                             '9'
-    base:                               'x'
-    shift, capslock:                    'X'
-    alt:                                '8'
-    shift+alt, capslock+alt:            '\uef00'
-}
-
-key Y {
-    label:                              'Y'
-    number:                             '9'
-    base:                               'y'
-    shift, capslock:                    'Y'
-    alt:                                '%'
-    shift+alt, capslock+alt:            '\u00a1'
-}
-
-key Z {
-    label:                              'Z'
-    number:                             '9'
-    base:                               'z'
-    shift, capslock:                    'Z'
-    alt:                                '7'
-    shift+alt, capslock+alt:            none
-}
-
-key COMMA {
-    label:                              ','
-    number:                             ','
-    base:                               ','
-    shift:                              ';'
-    alt:                                ';'
-    shift+alt:                          '|'
-}
-
-key PERIOD {
-    label:                              '.'
-    number:                             '.'
-    base:                               '.'
-    shift:                              ':'
-    alt:                                ':'
-    shift+alt:                          '\u2026'
-}
-
-key AT {
-    label:                              '@'
-    number:                             '0'
-    base:                               '@'
-    shift:                              '0'
-    alt:                                '0'
-    shift+alt:                          '\u2022'
-}
-
-key SLASH {
-    label:                              '/'
-    number:                             '/'
-    base:                               '/'
-    shift:                              '?'
-    alt:                                '?'
-    shift+alt:                          '\\'
-}
-
-key SPACE {
-    label:                              ' '
-    number:                             ' '
-    base:                               ' '
-    shift:                              ' '
-    alt:                                '\uef01'
-    shift+alt:                          '\uef01'
-}
-
-key ENTER {
-    label:                              '\n'
-    number:                             '\n'
-    base:                               '\n'
-    shift:                              '\n'
-    alt:                                '\n'
-    shift+alt:                          '\n'
-}
-
-key TAB {
-    label:                              '\t'
-    number:                             '\t'
-    base:                               '\t'
-    shift:                              '\t'
-    alt:                                '\t'
-    shift+alt:                          '\t'
-}
-
-key 0 {
-    label:                              '0'
-    number:                             '0'
-    base:                               '0'
-    shift:                              ')'
-    alt:                                ')'
-    shift+alt:                          ')'
-}
-
-key 1 {
-    label:                              '1'
-    number:                             '1'
-    base:                               '1'
-    shift:                              '!'
-    alt:                                '!'
-    shift+alt:                          '!'
-}
-
-key 2 {
-    label:                              '2'
-    number:                             '2'
-    base:                               '2'
-    shift:                              '@'
-    alt:                                '@'
-    shift+alt:                          '@'
-}
-
-key 3 {
-    label:                              '3'
-    number:                             '3'
-    base:                               '3'
-    shift:                              '#'
-    alt:                                '#'
-    shift+alt:                          '#'
-}
-
-key 4 {
-    label:                              '4'
-    number:                             '4'
-    base:                               '4'
-    shift:                              '$'
-    alt:                                '$'
-    shift+alt:                          '$'
-}
-
-key 5 {
-    label:                              '5'
-    number:                             '5'
-    base:                               '5'
-    shift:                              '%'
-    alt:                                '%'
-    shift+alt:                          '%'
-}
-
-key 6 {
-    label:                              '6'
-    number:                             '6'
-    base:                               '6'
-    shift:                              '^'
-    alt:                                '^'
-    shift+alt:                          '^'
-}
-
-key 7 {
-    label:                              '7'
-    number:                             '7'
-    base:                               '7'
-    shift:                              '&'
-    alt:                                '&'
-    shift+alt:                          '&'
-}
-
-key 8 {
-    label:                              '8'
-    number:                             '8'
-    base:                               '8'
-    shift:                              '*'
-    alt:                                '*'
-    shift+alt:                          '*'
-}
-
-key 9 {
-    label:                              '9'
-    number:                             '9'
-    base:                               '9'
-    shift:                              '('
-    alt:                                '('
-    shift+alt:                          '('
-}
-
-key GRAVE {
-    label:                              '`'
-    number:                             '`'
-    base:                               '`'
-    shift:                              '~'
-    alt:                                '`'
-    shift+alt:                          '~'
-}
-
-key MINUS {
-    label:                              '-'
-    number:                             '-'
-    base:                               '-'
-    shift:                              '_'
-    alt:                                '-'
-    shift+alt:                          '_'
-}
-
-key EQUALS {
-    label:                              '='
-    number:                             '='
-    base:                               '='
-    shift:                              '+'
-    alt:                                '='
-    shift+alt:                          '+'
-}
-
-key LEFT_BRACKET {
-    label:                              '['
-    number:                             '['
-    base:                               '['
-    shift:                              '{'
-    alt:                                '['
-    shift+alt:                          '{'
-}
-
-key RIGHT_BRACKET {
-    label:                              ']'
-    number:                             ']'
-    base:                               ']'
-    shift:                              '}'
-    alt:                                ']'
-    shift+alt:                          '}'
-}
-
-key BACKSLASH {
-    label:                              '\\'
-    number:                             '\\'
-    base:                               '\\'
-    shift:                              '|'
-    alt:                                '\\'
-    shift+alt:                          '|'
-}
-
-key SEMICOLON {
-    label:                              ';'
-    number:                             ';'
-    base:                               ';'
-    shift:                              ':'
-    alt:                                ';'
-    shift+alt:                          ':'
-}
-
-key APOSTROPHE {
-    label:                              '\''
-    number:                             '\''
-    base:                               '\''
-    shift:                              '"'
-    alt:                                '\''
-    shift+alt:                          '"'
-}
-
-key STAR {
-    label:                              '*'
-    number:                             '*'
-    base:                               '*'
-    shift:                              '*'
-    alt:                                '*'
-    shift+alt:                          '*'
-}
-
-key POUND {
-    label:                              '#'
-    number:                             '#'
-    base:                               '#'
-    shift:                              '#'
-    alt:                                '#'
-    shift+alt:                          '#'
-}
-
-key PLUS {
-    label:                              '+'
-    number:                             '+'
-    base:                               '+'
-    shift:                              '+'
-    alt:                                '+'
-    shift+alt:                          '+'
-}
diff --git a/data/keyboards/qwerty.kl b/data/keyboards/qwerty.kl
deleted file mode 100644
index 2fd99ab..0000000
--- a/data/keyboards/qwerty.kl
+++ /dev/null
@@ -1,131 +0,0 @@
-# Copyright (C) 2010 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.
-
-#
-# Emulator keyboard layout #1.
-#
-# This file is no longer used as the platform's default keyboard layout.
-# Refer to Generic.kl instead.
-#
-
-key 399   GRAVE
-key 2     1
-key 3     2
-key 4     3
-key 5     4
-key 6     5
-key 7     6
-key 8     7
-key 9     8
-key 10    9
-key 11    0
-key 158   BACK
-key 230   SOFT_RIGHT
-key 60    SOFT_LEFT
-key 107   ENDCALL
-key 62    ENDCALL
-key 229   MENU
-key 139   MENU
-key 59    MENU
-key 127   SEARCH
-key 217   SEARCH
-key 228   POUND
-key 227   STAR
-key 231   CALL
-key 61    CALL
-key 232   DPAD_CENTER
-key 108   DPAD_DOWN
-key 103   DPAD_UP
-key 102   HOME
-key 105   DPAD_LEFT
-key 106   DPAD_RIGHT
-key 115   VOLUME_UP
-key 114   VOLUME_DOWN
-key 116   POWER
-key 212   CAMERA
-
-key 16    Q
-key 17    W
-key 18    E
-key 19    R
-key 20    T
-key 21    Y
-key 22    U
-key 23    I
-key 24    O
-key 25    P
-key 26    LEFT_BRACKET
-key 27    RIGHT_BRACKET
-key 43    BACKSLASH
-
-key 30    A
-key 31    S
-key 32    D
-key 33    F
-key 34    G
-key 35    H
-key 36    J
-key 37    K
-key 38    L
-key 39    SEMICOLON
-key 40    APOSTROPHE
-key 14    DEL
-
-key 44    Z
-key 45    X
-key 46    C
-key 47    V
-key 48    B
-key 49    N
-key 50    M
-key 51    COMMA
-key 52    PERIOD
-key 53    SLASH
-key 28    ENTER
-
-key 56    ALT_LEFT
-key 100   ALT_RIGHT
-key 42    SHIFT_LEFT
-key 54    SHIFT_RIGHT
-key 15    TAB
-key 57    SPACE
-key 150   EXPLORER
-key 155   ENVELOPE
-
-key 12    MINUS
-key 13    EQUALS
-key 215   AT
-
-# On an AT keyboard: ESC, F10
-key 1     BACK
-key 68    MENU
-
-# App switch = Overview key
-key 580   APP_SWITCH
-
-# Media control keys
-key 160   MEDIA_CLOSE
-key 161   MEDIA_EJECT
-key 163   MEDIA_NEXT
-key 164   MEDIA_PLAY_PAUSE
-key 165   MEDIA_PREVIOUS
-key 166   MEDIA_STOP
-key 167   MEDIA_RECORD
-key 168   MEDIA_REWIND
-
-key 142   SLEEP
-key 581   STEM_PRIMARY
-key 582   STEM_1
-key 583   STEM_2
-key 584   STEM_3
diff --git a/data/keyboards/qwerty2.idc b/data/keyboards/qwerty2.idc
deleted file mode 100644
index 369205e..0000000
--- a/data/keyboards/qwerty2.idc
+++ /dev/null
@@ -1,28 +0,0 @@
-# Copyright (C) 2010 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.
-
-#
-# Emulator keyboard configuration file #2.
-#
-
-touch.deviceType = touchScreen
-touch.orientationAware = 1
-
-keyboard.layout = qwerty
-keyboard.characterMap = qwerty2
-keyboard.orientationAware = 1
-keyboard.builtIn = 1
-
-cursor.mode = navigation
-cursor.orientationAware = 1
diff --git a/data/keyboards/qwerty2.kcm b/data/keyboards/qwerty2.kcm
deleted file mode 100644
index b981d83..0000000
--- a/data/keyboards/qwerty2.kcm
+++ /dev/null
@@ -1,505 +0,0 @@
-# Copyright (C) 2010 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.
-
-#
-# Emulator keyboard character map #2.
-#
-
-type ALPHA
-
-key A {
-    label:                              'A'
-    number:                             '2'
-    base:                               'a'
-    shift, capslock:                    'A'
-    alt:                                '\u00e1'
-    shift+alt, capslock+alt:            '\u00c1'
-}
-
-key B {
-    label:                              'B'
-    number:                             '2'
-    base:                               'b'
-    shift, capslock:                    'B'
-    alt:                                'b'
-    shift+alt, capslock+alt:            'B'
-}
-
-key C {
-    label:                              'C'
-    number:                             '2'
-    base:                               'c'
-    shift, capslock:                    'C'
-    alt:                                '\u00a9'
-    shift+alt, capslock+alt:            '\u00a2'
-}
-
-key D {
-    label:                              'D'
-    number:                             '3'
-    base:                               'd'
-    shift, capslock:                    'D'
-    alt:                                '\u00f0'
-    shift+alt, capslock+alt:            '\u00d0'
-}
-
-key E {
-    label:                              'E'
-    number:                             '3'
-    base:                               'e'
-    shift, capslock:                    'E'
-    alt:                                '\u00e9'
-    shift+alt, capslock+alt:            '\u00c9'
-}
-
-key F {
-    label:                              'F'
-    number:                             '3'
-    base:                               'f'
-    shift, capslock:                    'F'
-    alt:                                '['
-    shift+alt, capslock+alt:            '['
-}
-
-key G {
-    label:                              'G'
-    number:                             '4'
-    base:                               'g'
-    shift, capslock:                    'G'
-    alt:                                ']'
-    shift+alt, capslock+alt:            ']'
-}
-
-key H {
-    label:                              'H'
-    number:                             '4'
-    base:                               'h'
-    shift, capslock:                    'H'
-    alt:                                '<'
-    shift+alt, capslock+alt:            '<'
-}
-
-key I {
-    label:                              'I'
-    number:                             '4'
-    base:                               'i'
-    shift, capslock:                    'I'
-    alt:                                '\u00ed'
-    shift+alt, capslock+alt:            '\u00cd'
-}
-
-key J {
-    label:                              'J'
-    number:                             '5'
-    base:                               'j'
-    shift, capslock:                    'J'
-    alt:                                '>'
-    shift+alt, capslock+alt:            '>'
-}
-
-key K {
-    label:                              'K'
-    number:                             '5'
-    base:                               'k'
-    shift, capslock:                    'K'
-    alt:                                ';'
-    shift+alt, capslock+alt:            '~'
-}
-
-key L {
-    label:                              'L'
-    number:                             '5'
-    base:                               'l'
-    shift, capslock:                    'L'
-    alt:                                '\u00f8'
-    shift+alt, capslock+alt:            '\u00d8'
-}
-
-key M {
-    label:                              'M'
-    number:                             '6'
-    base:                               'm'
-    shift, capslock:                    'M'
-    alt:                                '\u00b5'
-    shift+alt, capslock+alt:            none
-}
-
-key N {
-    label:                              'N'
-    number:                             '6'
-    base:                               'n'
-    shift, capslock:                    'N'
-    alt:                                '\u00f1'
-    shift+alt, capslock+alt:            '\u00d1'
-}
-
-key O {
-    label:                              'O'
-    number:                             '6'
-    base:                               'o'
-    shift, capslock:                    'O'
-    alt:                                '\u00f3'
-    shift+alt, capslock+alt:            '\u00d3'
-}
-
-key P {
-    label:                              'P'
-    number:                             '7'
-    base:                               'p'
-    shift, capslock:                    'P'
-    alt:                                '\u00f6'
-    shift+alt, capslock+alt:            '\u00d6'
-}
-
-key Q {
-    label:                              'Q'
-    number:                             '7'
-    base:                               'q'
-    shift, capslock:                    'Q'
-    alt:                                '\u00e4'
-    shift+alt, capslock+alt:            '\u00c4'
-}
-
-key R {
-    label:                              'R'
-    number:                             '7'
-    base:                               'r'
-    shift, capslock:                    'R'
-    alt:                                '\u00ae'
-    shift+alt, capslock+alt:            'R'
-}
-
-key S {
-    label:                              'S'
-    number:                             '7'
-    base:                               's'
-    shift, capslock:                    'S'
-    alt:                                '\u00df'
-    shift+alt, capslock+alt:            '\u00a7'
-}
-
-key T {
-    label:                              'T'
-    number:                             '8'
-    base:                               't'
-    shift, capslock:                    'T'
-    alt:                                '\u00fe'
-    shift+alt, capslock+alt:            '\u00de'
-}
-
-key U {
-    label:                              'U'
-    number:                             '8'
-    base:                               'u'
-    shift, capslock:                    'U'
-    alt:                                '\u00fa'
-    shift+alt, capslock+alt:            '\u00da'
-}
-
-key V {
-    label:                              'V'
-    number:                             '8'
-    base:                               'v'
-    shift, capslock:                    'V'
-    alt:                                'v'
-    shift+alt, capslock+alt:            'V'
-}
-
-key W {
-    label:                              'W'
-    number:                             '9'
-    base:                               'w'
-    shift, capslock:                    'W'
-    alt:                                '\u00e5'
-    shift+alt, capslock+alt:            '\u00c5'
-}
-
-key X {
-    label:                              'X'
-    number:                             '9'
-    base:                               'x'
-    shift, capslock:                    'X'
-    alt:                                'x'
-    shift+alt, capslock+alt:            '\uef00'
-}
-
-key Y {
-    label:                              'Y'
-    number:                             '9'
-    base:                               'y'
-    shift, capslock:                    'Y'
-    alt:                                '\u00fc'
-    shift+alt, capslock+alt:            '\u00dc'
-}
-
-key Z {
-    label:                              'Z'
-    number:                             '9'
-    base:                               'z'
-    shift, capslock:                    'Z'
-    alt:                                '\u00e6'
-    shift+alt, capslock+alt:            '\u00c6'
-}
-
-key COMMA {
-    label:                              ','
-    number:                             ','
-    base:                               ','
-    shift:                              '<'
-    alt:                                '\u00e7'
-    shift+alt:                          '\u00c7'
-}
-
-key PERIOD {
-    label:                              '.'
-    number:                             '.'
-    base:                               '.'
-    shift:                              '>'
-    alt:                                '.'
-    shift+alt:                          '\u2026'
-}
-
-key AT {
-    label:                              '@'
-    number:                             '@'
-    base:                               '@'
-    shift:                              '@'
-    alt:                                '@'
-    shift+alt:                          '\u2022'
-}
-
-key SLASH {
-    label:                              '/'
-    number:                             '/'
-    base:                               '/'
-    shift:                              '?'
-    alt:                                '\u00bf'
-    shift+alt:                          '?'
-}
-
-key SPACE {
-    label:                              ' '
-    number:                             ' '
-    base:                               ' '
-    shift:                              ' '
-    alt:                                '\uef01'
-    shift+alt:                          '\uef01'
-}
-
-key ENTER {
-    label:                              '\n'
-    number:                             '\n'
-    base:                               '\n'
-    shift:                              '\n'
-    alt:                                '\n'
-    shift+alt:                          '\n'
-}
-
-key TAB {
-    label:                              '\t'
-    number:                             '\t'
-    base:                               '\t'
-    shift:                              '\t'
-    alt:                                '\t'
-    shift+alt:                          '\t'
-}
-
-key 0 {
-    label:                              '0'
-    number:                             '0'
-    base:                               '0'
-    shift:                              ')'
-    alt:                                '\u02bc'
-    shift+alt:                          ')'
-}
-
-key 1 {
-    label:                              '1'
-    number:                             '1'
-    base:                               '1'
-    shift:                              '!'
-    alt:                                '\u00a1'
-    shift+alt:                          '\u00b9'
-}
-
-key 2 {
-    label:                              '2'
-    number:                             '2'
-    base:                               '2'
-    shift:                              '@'
-    alt:                                '\u00b2'
-    shift+alt:                          '@'
-}
-
-key 3 {
-    label:                              '3'
-    number:                             '3'
-    base:                               '3'
-    shift:                              '#'
-    alt:                                '\u00b3'
-    shift+alt:                          '#'
-}
-
-key 4 {
-    label:                              '4'
-    number:                             '4'
-    base:                               '4'
-    shift:                              '$'
-    alt:                                '\u00a4'
-    shift+alt:                          '\u00a3'
-}
-
-key 5 {
-    label:                              '5'
-    number:                             '5'
-    base:                               '5'
-    shift:                              '%'
-    alt:                                '\u20ac'
-    shift+alt:                          '%'
-}
-
-key 6 {
-    label:                              '6'
-    number:                             '6'
-    base:                               '6'
-    shift:                              '^'
-    alt:                                '\u00bc'
-    shift+alt:                          '\u0302'
-}
-
-key 7 {
-    label:                              '7'
-    number:                             '7'
-    base:                               '7'
-    shift:                              '&'
-    alt:                                '\u00bd'
-    shift+alt:                          '&'
-}
-
-key 8 {
-    label:                              '8'
-    number:                             '8'
-    base:                               '8'
-    shift:                              '*'
-    alt:                                '\u00be'
-    shift+alt:                          '*'
-}
-
-key 9 {
-    label:                              '9'
-    number:                             '9'
-    base:                               '9'
-    shift:                              '('
-    alt:                                '\u02bb'
-    shift+alt:                          '('
-}
-
-key GRAVE {
-    label:                              '`'
-    number:                             '`'
-    base:                               '`'
-    shift:                              '~'
-    alt:                                '\u0300'
-    shift+alt:                          '\u0303'
-}
-
-key MINUS {
-    label:                              '-'
-    number:                             '-'
-    base:                               '-'
-    shift:                              '_'
-    alt:                                '\u00a5'
-    shift+alt:                          '_'
-}
-
-key EQUALS {
-    label:                              '='
-    number:                             '='
-    base:                               '='
-    shift:                              '+'
-    alt:                                '\u00d7'
-    shift+alt:                          '\u00f7'
-}
-
-key LEFT_BRACKET {
-    label:                              '['
-    number:                             '['
-    base:                               '['
-    shift:                              '{'
-    alt:                                '\u00ab'
-    shift+alt:                          '{'
-}
-
-key RIGHT_BRACKET {
-    label:                              ']'
-    number:                             ']'
-    base:                               ']'
-    shift:                              '}'
-    alt:                                '\u00bb'
-    shift+alt:                          '}'
-}
-
-key BACKSLASH {
-    label:                              '\\'
-    number:                             '\\'
-    base:                               '\\'
-    shift:                              '|'
-    alt:                                '\u00ac'
-    shift+alt:                          '\u00a6'
-}
-
-key SEMICOLON {
-    label:                              ';'
-    number:                             ';'
-    base:                               ';'
-    shift:                              ':'
-    alt:                                '\u00b6'
-    shift+alt:                          '\u00b0'
-}
-
-key APOSTROPHE {
-    label:                              '\''
-    number:                             '\''
-    base:                               '\''
-    shift:                              '"'
-    alt:                                '\u0301'
-    shift+alt:                          '\u0308'
-}
-
-key STAR {
-    label:                              '*'
-    number:                             '*'
-    base:                               '*'
-    shift:                              '*'
-    alt:                                '*'
-    shift+alt:                          '*'
-}
-
-key POUND {
-    label:                              '#'
-    number:                             '#'
-    base:                               '#'
-    shift:                              '#'
-    alt:                                '#'
-    shift+alt:                          '#'
-}
-
-key PLUS {
-    label:                              '+'
-    number:                             '+'
-    base:                               '+'
-    shift:                              '+'
-    alt:                                '+'
-    shift+alt:                          '+'
-}
diff --git a/drm/jni/android_drm_DrmManagerClient.cpp b/drm/jni/android_drm_DrmManagerClient.cpp
index e2bb6a6..14d5eaf 100644
--- a/drm/jni/android_drm_DrmManagerClient.cpp
+++ b/drm/jni/android_drm_DrmManagerClient.cpp
@@ -167,8 +167,8 @@
     jint uniqueId = event.getUniqueId();
     jint type = event.getType();
     JNIEnv *env = AndroidRuntime::getJNIEnv();
-    jstring message = env->NewStringUTF(event.getMessage().string());
-    ALOGV("JNIOnInfoListener::onInfo => %d | %d | %s", uniqueId, type, event.getMessage().string());
+    jstring message = env->NewStringUTF(event.getMessage().c_str());
+    ALOGV("JNIOnInfoListener::onInfo => %d | %d | %s", uniqueId, type, event.getMessage().c_str());
 
     env->CallStaticVoidMethod(
             mClass,
@@ -273,15 +273,15 @@
                 const char* value = pConstraints->getAsByteArray(&key);
                 if (NULL != value) {
                     ScopedLocalRef<jbyteArray> dataArray(env, env->NewByteArray(strlen(value)));
-                    ScopedLocalRef<jstring> keyString(env, env->NewStringUTF(key.string()));
+                    ScopedLocalRef<jstring> keyString(env, env->NewStringUTF(key.c_str()));
                     env->SetByteArrayRegion(dataArray.get(), 0, strlen(value), (jbyte*)value);
                     env->CallVoidMethod(constraints, ContentValues_putByteArray,
                                         keyString.get(), dataArray.get());
                 }
             } else {
                 String8 value = pConstraints->get(key);
-                ScopedLocalRef<jstring> keyString(env, env->NewStringUTF(key.string()));
-                ScopedLocalRef<jstring> valueString(env, env->NewStringUTF(value.string()));
+                ScopedLocalRef<jstring> keyString(env, env->NewStringUTF(key.c_str()));
+                ScopedLocalRef<jstring> valueString(env, env->NewStringUTF(value.c_str()));
                 env->CallVoidMethod(constraints, ContentValues_putString,
                                     keyString.get(), valueString.get());
             }
@@ -320,8 +320,8 @@
                     // insert the entry<constraintKey, constraintValue>
                     // to newly created java object
                     String8 value = pMetadata->get(key);
-                    ScopedLocalRef<jstring> keyString(env, env->NewStringUTF(key.string()));
-                    ScopedLocalRef<jstring> valueString(env, env->NewStringUTF(value.string()));
+                    ScopedLocalRef<jstring> keyString(env, env->NewStringUTF(key.c_str()));
+                    ScopedLocalRef<jstring> valueString(env, env->NewStringUTF(value.c_str()));
                     env->CallVoidMethod(metadata, ContentValues_putString,
                                         keyString.get(), valueString.get());
                 }
@@ -357,19 +357,19 @@
 
         env->CallVoidMethod(
             drmSupportInfo, env->GetMethodID(clazz, "setDescription", "(Ljava/lang/String;)V"),
-            env->NewStringUTF(info.getDescription().string()));
+            env->NewStringUTF(info.getDescription().c_str()));
 
         DrmSupportInfo::MimeTypeIterator iterator = info.getMimeTypeIterator();
         while (iterator.hasNext()) {
             String8  value = iterator.next();
-            env->CallVoidMethod(drmSupportInfo, addMimeTypeId, env->NewStringUTF(value.string()));
+            env->CallVoidMethod(drmSupportInfo, addMimeTypeId, env->NewStringUTF(value.c_str()));
         }
 
         DrmSupportInfo::FileSuffixIterator it = info.getFileSuffixIterator();
         while (it.hasNext()) {
             String8 value = it.next();
             env->CallVoidMethod(
-                drmSupportInfo, addFileSuffixId, env->NewStringUTF(value.string()));
+                drmSupportInfo, addFileSuffixId, env->NewStringUTF(value.c_str()));
         }
 
         env->SetObjectArrayElement(array, i, drmSupportInfo);
@@ -459,7 +459,7 @@
 
         String8 keyString = Utility::getStringValue(env, key.get());
         String8 valueString = Utility::getStringValue(env, valString.get());
-        ALOGV("Key: %s | Value: %s", keyString.string(), valueString.string());
+        ALOGV("Key: %s | Value: %s", keyString.c_str(), valueString.c_str());
 
         drmInfo.put(keyString, valueString);
     }
@@ -488,15 +488,15 @@
         jmethodID constructorId
             = env->GetMethodID(clazz, "<init>", "([BLjava/lang/String;Ljava/lang/String;)V");
         jobject processedData = env->NewObject(clazz, constructorId, dataArray,
-                    env->NewStringUTF((drmInfo.get(DrmInfoRequest::ACCOUNT_ID)).string()),
-                    env->NewStringUTF((drmInfo.get(DrmInfoRequest::SUBSCRIPTION_ID)).string()));
+                    env->NewStringUTF((drmInfo.get(DrmInfoRequest::ACCOUNT_ID)).c_str()),
+                    env->NewStringUTF((drmInfo.get(DrmInfoRequest::SUBSCRIPTION_ID)).c_str()));
 
         constructorId
             = env->GetMethodID(localRef,
                 "<init>", "(IILandroid/drm/ProcessedData;Ljava/lang/String;)V");
 
         drmInfoStatus = env->NewObject(localRef, constructorId, statusCode, infoType,
-                processedData, env->NewStringUTF(pDrmInfoStatus->mimeType.string()));
+                processedData, env->NewStringUTF(pDrmInfoStatus->mimeType.c_str()));
     }
 
     delete[] mData; mData = NULL;
@@ -533,7 +533,7 @@
 
         String8 keyString = Utility::getStringValue(env, key.get());
         String8 valueString = Utility::getStringValue(env, value.get());
-        ALOGV("Key: %s | Value: %s", keyString.string(), valueString.string());
+        ALOGV("Key: %s | Value: %s", keyString.c_str(), valueString.c_str());
 
         drmInfoReq.put(keyString, valueString);
     }
@@ -554,7 +554,7 @@
             drmInfoObject
                 = env->NewObject(localRef,
                     env->GetMethodID(localRef, "<init>", "(I[BLjava/lang/String;)V"),
-                    mInfoType, dataArray, env->NewStringUTF(pDrmInfo->getMimeType().string()));
+                    mInfoType, dataArray, env->NewStringUTF(pDrmInfo->getMimeType().c_str()));
 
             DrmInfo::KeyIterator it = pDrmInfo->keyIterator();
             jmethodID putMethodId
@@ -563,8 +563,8 @@
             while (it.hasNext()) {
                 String8 key = it.next();
                 String8 value = pDrmInfo->get(key);
-                ScopedLocalRef<jstring> keyString(env, env->NewStringUTF(key.string()));
-                ScopedLocalRef<jstring> valueString(env, env->NewStringUTF(value.string()));
+                ScopedLocalRef<jstring> keyString(env, env->NewStringUTF(key.c_str()));
+                ScopedLocalRef<jstring> valueString(env, env->NewStringUTF(value.c_str()));
                 env->CallVoidMethod(drmInfoObject, putMethodId,
                     keyString.get(), valueString.get());
             }
@@ -602,7 +602,7 @@
             ->getOriginalMimeType(uniqueId,
                                   Utility::getStringValue(env, path), fd);
     ALOGV("getOriginalMimeType Exit");
-    return env->NewStringUTF(mimeType.string());
+    return env->NewStringUTF(mimeType.c_str());
 }
 
 static jint android_drm_DrmManagerClient_checkRightsStatus(
diff --git a/graphics/java/android/graphics/fonts/SystemFonts.java b/graphics/java/android/graphics/fonts/SystemFonts.java
index 6278c0e..1c1723c 100644
--- a/graphics/java/android/graphics/fonts/SystemFonts.java
+++ b/graphics/java/android/graphics/fonts/SystemFonts.java
@@ -46,7 +46,7 @@
 public final class SystemFonts {
     private static final String TAG = "SystemFonts";
 
-    private static final String FONTS_XML = "/system/etc/fonts.xml";
+    private static final String FONTS_XML = "/system/etc/font_fallback.xml";
     /** @hide */
     public static final String SYSTEM_FONT_DIR = "/system/fonts/";
     private static final String OEM_XML = "/product/etc/fonts_customization.xml";
@@ -208,6 +208,19 @@
     }
 
     /**
+     * Get the updated FontConfig for testing purposes.
+     * @hide
+     */
+    public static @NonNull FontConfig getSystemFontConfigForTesting(
+            @NonNull String fontsXmlPath,
+            @Nullable Map<String, File> updatableFontMap,
+            long lastModifiedDate,
+            int configVersion) {
+        return getSystemFontConfigInternal(fontsXmlPath, SYSTEM_FONT_DIR, OEM_XML, OEM_FONT_DIR,
+                updatableFontMap, lastModifiedDate, configVersion);
+    }
+
+    /**
      * Get the updated FontConfig.
      *
      * @param updatableFontMap a font mapping of updated font files.
diff --git a/keystore/OWNERS b/keystore/OWNERS
index 7ab9d76..913f655 100644
--- a/keystore/OWNERS
+++ b/keystore/OWNERS
@@ -1,4 +1,4 @@
+# Bug component: 189335
 eranm@google.com
 jbires@google.com
-jdanis@google.com
 swillden@google.com
diff --git a/keystore/java/android/security/AndroidKeyStoreMaintenance.java b/keystore/java/android/security/AndroidKeyStoreMaintenance.java
index 919a93b..0f3488b 100644
--- a/keystore/java/android/security/AndroidKeyStoreMaintenance.java
+++ b/keystore/java/android/security/AndroidKeyStoreMaintenance.java
@@ -20,6 +20,7 @@
 import android.annotation.Nullable;
 import android.os.ServiceManager;
 import android.os.ServiceSpecificException;
+import android.os.StrictMode;
 import android.security.maintenance.IKeystoreMaintenance;
 import android.system.keystore2.Domain;
 import android.system.keystore2.KeyDescriptor;
@@ -51,6 +52,7 @@
      * @hide
      */
     public static int onUserAdded(@NonNull int userId) {
+        StrictMode.noteDiskWrite();
         try {
             getService().onUserAdded(userId);
             return 0;
@@ -71,6 +73,7 @@
      * @hide
      */
     public static int onUserRemoved(int userId) {
+        StrictMode.noteDiskWrite();
         try {
             getService().onUserRemoved(userId);
             return 0;
@@ -93,6 +96,7 @@
      * @hide
      */
     public static int onUserPasswordChanged(int userId, @Nullable byte[] password) {
+        StrictMode.noteDiskWrite();
         try {
             getService().onUserPasswordChanged(userId, password);
             return 0;
@@ -110,6 +114,7 @@
      * be cleared.
      */
     public static int clearNamespace(@Domain int domain, long namespace) {
+        StrictMode.noteDiskWrite();
         try {
             getService().clearNamespace(domain, namespace);
             return 0;
@@ -129,6 +134,7 @@
      * @return UserState enum variant as integer if successful or an error
      */
     public static int getState(int userId) {
+        StrictMode.noteDiskRead();
         try {
             return getService().getState(userId);
         } catch (ServiceSpecificException e) {
@@ -144,6 +150,7 @@
      * Informs Keystore 2.0 that an off body event was detected.
      */
     public static void onDeviceOffBody() {
+        StrictMode.noteDiskWrite();
         try {
             getService().onDeviceOffBody();
         } catch (Exception e) {
@@ -172,6 +179,7 @@
      *         * SYSTEM_ERROR if an unexpected error occurred.
      */
     public static int migrateKeyNamespace(KeyDescriptor source, KeyDescriptor destination) {
+        StrictMode.noteDiskWrite();
         try {
             getService().migrateKeyNamespace(source, destination);
             return 0;
diff --git a/keystore/java/android/security/Authorization.java b/keystore/java/android/security/Authorization.java
index 00219e7..2d2dd24 100644
--- a/keystore/java/android/security/Authorization.java
+++ b/keystore/java/android/security/Authorization.java
@@ -22,6 +22,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.ServiceSpecificException;
+import android.os.StrictMode;
 import android.security.authorization.IKeystoreAuthorization;
 import android.security.authorization.LockScreenEvent;
 import android.system.keystore2.ResponseCode;
@@ -48,6 +49,7 @@
      * @return 0 if successful or {@code ResponseCode.SYSTEM_ERROR}.
      */
     public static int addAuthToken(@NonNull HardwareAuthToken authToken) {
+        StrictMode.noteSlowCall("addAuthToken");
         try {
             getService().addAuthToken(authToken);
             return 0;
@@ -81,6 +83,7 @@
      */
     public static int onLockScreenEvent(@NonNull boolean locked, @NonNull int userId,
             @Nullable byte[] syntheticPassword, @Nullable long[] unlockingSids) {
+        StrictMode.noteDiskWrite();
         try {
             if (locked) {
                 getService().onLockScreenEvent(LockScreenEvent.LOCK, userId, null, unlockingSids);
diff --git a/keystore/java/android/security/KeyStore.java b/keystore/java/android/security/KeyStore.java
index 8811a7f..8045f55 100644
--- a/keystore/java/android/security/KeyStore.java
+++ b/keystore/java/android/security/KeyStore.java
@@ -18,6 +18,7 @@
 
 import android.compat.annotation.UnsupportedAppUsage;
 import android.os.Build;
+import android.os.StrictMode;
 import android.os.UserHandle;
 import android.security.maintenance.UserState;
 
@@ -126,6 +127,8 @@
      * a {@code KeymasterDefs.KM_ERROR_} value or {@code KeyStore} ResponseCode.
      */
     public int addAuthToken(byte[] authToken) {
+        StrictMode.noteDiskWrite();
+
         return Authorization.addAuthToken(authToken);
     }
 
diff --git a/keystore/java/android/security/KeyStore2.java b/keystore/java/android/security/KeyStore2.java
index 74597c5..2661b61 100644
--- a/keystore/java/android/security/KeyStore2.java
+++ b/keystore/java/android/security/KeyStore2.java
@@ -23,6 +23,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.ServiceSpecificException;
+import android.os.StrictMode;
 import android.security.keymaster.KeymasterDefs;
 import android.system.keystore2.Domain;
 import android.system.keystore2.IKeystoreService;
@@ -147,6 +148,8 @@
     }
 
     void delete(KeyDescriptor descriptor) throws KeyStoreException {
+        StrictMode.noteDiskWrite();
+
         handleRemoteExceptionWithRetry((service) -> {
             service.deleteKey(descriptor);
             return 0;
@@ -157,6 +160,8 @@
      * List all entries in the keystore for in the given namespace.
      */
     public KeyDescriptor[] list(int domain, long namespace) throws KeyStoreException {
+        StrictMode.noteDiskRead();
+
         return handleRemoteExceptionWithRetry((service) -> service.listEntries(domain, namespace));
     }
 
@@ -165,6 +170,8 @@
      */
     public KeyDescriptor[] listBatch(int domain, long namespace, String startPastAlias)
             throws KeyStoreException {
+        StrictMode.noteDiskRead();
+
         return handleRemoteExceptionWithRetry(
                 (service) -> service.listEntriesBatched(domain, namespace, startPastAlias));
     }
@@ -227,6 +234,8 @@
      */
     public KeyDescriptor grant(KeyDescriptor descriptor, int granteeUid, int accessVector)
             throws  KeyStoreException {
+        StrictMode.noteDiskWrite();
+
         return handleRemoteExceptionWithRetry(
                 (service) -> service.grant(descriptor, granteeUid, accessVector)
         );
@@ -242,6 +251,8 @@
      */
     public void ungrant(KeyDescriptor descriptor, int granteeUid)
             throws KeyStoreException {
+        StrictMode.noteDiskWrite();
+
         handleRemoteExceptionWithRetry((service) -> {
             service.ungrant(descriptor, granteeUid);
             return 0;
@@ -258,6 +269,8 @@
      */
     public KeyEntryResponse getKeyEntry(@NonNull KeyDescriptor descriptor)
             throws KeyStoreException {
+        StrictMode.noteDiskRead();
+
         return handleRemoteExceptionWithRetry((service) -> service.getKeyEntry(descriptor));
     }
 
@@ -289,6 +302,8 @@
      */
     public void updateSubcomponents(@NonNull KeyDescriptor key, byte[] publicCert,
             byte[] publicCertChain) throws KeyStoreException {
+        StrictMode.noteDiskWrite();
+
         handleRemoteExceptionWithRetry((service) -> {
             service.updateSubcomponent(key, publicCert, publicCertChain);
             return 0;
@@ -304,6 +319,8 @@
      */
     public void deleteKey(@NonNull KeyDescriptor descriptor)
             throws KeyStoreException {
+        StrictMode.noteDiskWrite();
+
         handleRemoteExceptionWithRetry((service) -> {
             service.deleteKey(descriptor);
             return 0;
@@ -314,6 +331,8 @@
      * Returns the number of Keystore entries for a given domain and namespace.
      */
     public int getNumberOfEntries(int domain, long namespace) throws KeyStoreException {
+        StrictMode.noteDiskRead();
+
         return handleRemoteExceptionWithRetry((service)
                 -> service.getNumberOfEntries(domain, namespace));
     }
diff --git a/keystore/java/android/security/KeyStoreOperation.java b/keystore/java/android/security/KeyStoreOperation.java
index 737ff2b..7c9b8eb 100644
--- a/keystore/java/android/security/KeyStoreOperation.java
+++ b/keystore/java/android/security/KeyStoreOperation.java
@@ -21,6 +21,7 @@
 import android.os.Binder;
 import android.os.RemoteException;
 import android.os.ServiceSpecificException;
+import android.os.StrictMode;
 import android.security.keymaster.KeymasterDefs;
 import android.system.keystore2.IKeystoreOperation;
 import android.system.keystore2.ResponseCode;
@@ -97,6 +98,7 @@
      * @throws KeyStoreException
      */
     public void updateAad(@NonNull byte[] input) throws KeyStoreException {
+        StrictMode.noteSlowCall("updateAad");
         handleExceptions(() -> {
             mOperation.updateAad(input);
             return 0;
@@ -112,6 +114,7 @@
      * @hide
      */
     public byte[] update(@NonNull byte[] input) throws KeyStoreException {
+        StrictMode.noteSlowCall("update");
         return handleExceptions(() -> mOperation.update(input));
     }
 
@@ -125,6 +128,7 @@
      * @hide
      */
     public byte[] finish(byte[] input, byte[] signature) throws KeyStoreException {
+        StrictMode.noteSlowCall("finish");
         return handleExceptions(() -> mOperation.finish(input, signature));
     }
 
@@ -135,6 +139,7 @@
      * @hide
      */
     public void abort() throws KeyStoreException {
+        StrictMode.noteSlowCall("abort");
         handleExceptions(() -> {
             mOperation.abort();
             return 0;
diff --git a/keystore/java/android/security/KeyStoreSecurityLevel.java b/keystore/java/android/security/KeyStoreSecurityLevel.java
index 9c0b46c..6ab148a 100644
--- a/keystore/java/android/security/KeyStoreSecurityLevel.java
+++ b/keystore/java/android/security/KeyStoreSecurityLevel.java
@@ -22,6 +22,7 @@
 import android.os.Binder;
 import android.os.RemoteException;
 import android.os.ServiceSpecificException;
+import android.os.StrictMode;
 import android.security.keystore.BackendBusyException;
 import android.security.keystore.KeyStoreConnectException;
 import android.system.keystore2.AuthenticatorSpec;
@@ -75,6 +76,7 @@
      */
     public KeyStoreOperation createOperation(@NonNull KeyDescriptor keyDescriptor,
             Collection<KeyParameter> args) throws KeyStoreException {
+        StrictMode.noteDiskWrite();
         while (true) {
             try {
                 CreateOperationResponse createOperationResponse =
@@ -142,6 +144,8 @@
     public KeyMetadata generateKey(@NonNull KeyDescriptor descriptor, KeyDescriptor attestationKey,
             Collection<KeyParameter> args, int flags, byte[] entropy)
             throws KeyStoreException {
+        StrictMode.noteDiskWrite();
+
         return handleExceptions(() -> mSecurityLevel.generateKey(
                 descriptor, attestationKey, args.toArray(new KeyParameter[args.size()]),
                 flags, entropy));
@@ -163,6 +167,8 @@
     public KeyMetadata importKey(KeyDescriptor descriptor, KeyDescriptor attestationKey,
             Collection<KeyParameter> args, int flags, byte[] keyData)
             throws KeyStoreException {
+        StrictMode.noteDiskWrite();
+
         return handleExceptions(() -> mSecurityLevel.importKey(descriptor, attestationKey,
                 args.toArray(new KeyParameter[args.size()]), flags, keyData));
     }
@@ -186,6 +192,7 @@
             @NonNull byte[] wrappedKey, byte[] maskingKey,
             Collection<KeyParameter> args, @NonNull AuthenticatorSpec[] authenticatorSpecs)
             throws KeyStoreException {
+        StrictMode.noteDiskWrite();
         KeyDescriptor keyDescriptor = new KeyDescriptor();
         keyDescriptor.alias = wrappedKeyDescriptor.alias;
         keyDescriptor.nspace = wrappedKeyDescriptor.nspace;
diff --git a/keystore/java/android/security/LegacyVpnProfileStore.java b/keystore/java/android/security/LegacyVpnProfileStore.java
index c85b6b1..0cc4dfa 100644
--- a/keystore/java/android/security/LegacyVpnProfileStore.java
+++ b/keystore/java/android/security/LegacyVpnProfileStore.java
@@ -19,6 +19,7 @@
 import android.annotation.NonNull;
 import android.os.ServiceManager;
 import android.os.ServiceSpecificException;
+import android.os.StrictMode;
 import android.security.legacykeystore.ILegacyKeystore;
 import android.util.Log;
 
@@ -51,6 +52,7 @@
      * @hide
      */
     public static boolean put(@NonNull String alias, @NonNull byte[] profile) {
+        StrictMode.noteDiskWrite();
         try {
             getService().put(alias, ILegacyKeystore.UID_SELF, profile);
             return true;
@@ -70,6 +72,7 @@
      * @hide
      */
     public static byte[] get(@NonNull String alias) {
+        StrictMode.noteDiskRead();
         try {
             return getService().get(alias, ILegacyKeystore.UID_SELF);
         } catch (ServiceSpecificException e) {
@@ -89,6 +92,7 @@
      * @hide
      */
     public static boolean remove(@NonNull String alias) {
+        StrictMode.noteDiskWrite();
         try {
             getService().remove(alias, ILegacyKeystore.UID_SELF);
             return true;
@@ -109,6 +113,7 @@
      * @hide
      */
     public static @NonNull String[] list(@NonNull String prefix) {
+        StrictMode.noteDiskRead();
         try {
             final String[] aliases = getService().list(prefix, ILegacyKeystore.UID_SELF);
             for (int i = 0; i < aliases.length; ++i) {
diff --git a/keystore/java/android/security/SystemKeyStore.java b/keystore/java/android/security/SystemKeyStore.java
index e07eaa2..d481a07 100644
--- a/keystore/java/android/security/SystemKeyStore.java
+++ b/keystore/java/android/security/SystemKeyStore.java
@@ -18,6 +18,9 @@
 
 import android.os.Environment;
 import android.os.FileUtils;
+import android.os.StrictMode;
+
+import libcore.io.IoUtils;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -28,8 +31,6 @@
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
 
-import libcore.io.IoUtils;
-
 /**
  *@hide
  */
@@ -69,6 +70,7 @@
 
     public byte[] generateNewKey(int numBits, String algName, String keyName)
             throws NoSuchAlgorithmException {
+        StrictMode.noteDiskWrite();
 
         // Check if key with similar name exists. If so, return null.
         File keyFile = getKeyFile(keyName);
@@ -103,6 +105,7 @@
     }
 
     private File getKeyFile(String keyName) {
+        StrictMode.noteDiskWrite();
         File sysKeystoreDir = new File(Environment.getDataDirectory(),
                 SYSTEM_KEYSTORE_DIRECTORY);
         File keyFile = new File(sysKeystoreDir, keyName + KEY_FILE_EXTENSION);
@@ -114,6 +117,7 @@
     }
 
     public byte[] retrieveKey(String keyName) throws IOException {
+        StrictMode.noteDiskRead();
         File keyFile = getKeyFile(keyName);
         if (!keyFile.exists()) {
             return null;
@@ -122,6 +126,7 @@
     }
 
     public void deleteKey(String keyName) {
+        StrictMode.noteDiskWrite();
 
         // Get the file first.
         File keyFile = getKeyFile(keyName);
diff --git a/keystore/java/android/security/keystore/KeyGenParameterSpec.java b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
index 7afb890..6db1832 100644
--- a/keystore/java/android/security/keystore/KeyGenParameterSpec.java
+++ b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
@@ -16,6 +16,7 @@
 
 package android.security.keystore;
 
+import android.annotation.FlaggedApi;
 import android.annotation.IntRange;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -34,7 +35,10 @@
 import java.security.Signature;
 import java.security.cert.Certificate;
 import java.security.spec.AlgorithmParameterSpec;
+import java.util.Collections;
 import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
 
 import javax.crypto.Cipher;
 import javax.crypto.KeyGenerator;
@@ -300,6 +304,7 @@
     private final Date mKeyValidityForConsumptionEnd;
     private final @KeyProperties.PurposeEnum int mPurposes;
     private final @KeyProperties.DigestEnum String[] mDigests;
+    private final @NonNull @KeyProperties.DigestEnum Set<String> mMgf1Digests;
     private final @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
     private final @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
     private final @KeyProperties.BlockModeEnum String[] mBlockModes;
@@ -343,6 +348,7 @@
             Date keyValidityForConsumptionEnd,
             @KeyProperties.PurposeEnum int purposes,
             @KeyProperties.DigestEnum String[] digests,
+            @KeyProperties.DigestEnum Set<String> mgf1Digests,
             @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings,
             @KeyProperties.SignaturePaddingEnum String[] signaturePaddings,
             @KeyProperties.BlockModeEnum String[] blockModes,
@@ -401,6 +407,9 @@
         mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd);
         mPurposes = purposes;
         mDigests = ArrayUtils.cloneIfNotEmpty(digests);
+        // No need to copy the input parameter because the Builder class passes in an immutable
+        // collection.
+        mMgf1Digests = mgf1Digests != null ? mgf1Digests : Collections.emptySet();
         mEncryptionPaddings =
                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(encryptionPaddings));
         mSignaturePaddings = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings));
@@ -562,7 +571,7 @@
 
     /**
      * Returns the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384} with which the
-     * key can be used or {@code null} if not specified.
+     * key can be used.
      *
      * <p>See {@link KeyProperties}.{@code DIGEST} constants.
      *
@@ -590,6 +599,40 @@
     }
 
     /**
+     * Returns the set of digests that can be used by the MGF1 mask generation function
+     * (e.g., {@code SHA-256}, {@code SHA-384}) with the key. Useful with the {@code RSA-OAEP}
+     * scheme.
+     * If not explicitly specified during key generation, the default {@code SHA-1} digest is
+     * used and may be specified when using the key.
+     *
+     * <p>See {@link KeyProperties}.{@code DIGEST} constants.
+     *
+     * @throws IllegalStateException if this set has not been specified.
+     *
+     * @see #isMgf1DigestsSpecified()
+     */
+    @NonNull
+    @FlaggedApi("MGF1_DIGEST_SETTER")
+    public @KeyProperties.DigestEnum Set<String> getMgf1Digests() {
+        if (mMgf1Digests.isEmpty()) {
+            throw new IllegalStateException("Mask generation function (MGF) not specified");
+        }
+        return new HashSet(mMgf1Digests);
+    }
+
+    /**
+     * Returns {@code true} if the set of digests for the MGF1 mask generation function,
+     * with which the key can be used, has been specified. Useful with the {@code RSA-OAEP} scheme.
+     *
+     * @see #getMgf1Digests()
+     */
+    @NonNull
+    @FlaggedApi("MGF1_DIGEST_SETTER")
+    public boolean isMgf1DigestsSpecified() {
+        return !mMgf1Digests.isEmpty();
+    }
+
+    /**
      * Returns the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OEAPPadding},
      * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when
      * encrypting/decrypting. Attempts to use the key with any other padding scheme will be
@@ -899,6 +942,8 @@
         private Date mKeyValidityForOriginationEnd;
         private Date mKeyValidityForConsumptionEnd;
         private @KeyProperties.DigestEnum String[] mDigests;
+        private @NonNull @KeyProperties.DigestEnum Set<String> mMgf1Digests =
+                Collections.emptySet();
         private @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
         private @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
         private @KeyProperties.BlockModeEnum String[] mBlockModes;
@@ -968,6 +1013,9 @@
             if (sourceSpec.isDigestsSpecified()) {
                 mDigests = sourceSpec.getDigests();
             }
+            if (sourceSpec.isMgf1DigestsSpecified()) {
+                mMgf1Digests = sourceSpec.getMgf1Digests();
+            }
             mEncryptionPaddings = sourceSpec.getEncryptionPaddings();
             mSignaturePaddings = sourceSpec.getSignaturePaddings();
             mBlockModes = sourceSpec.getBlockModes();
@@ -1214,6 +1262,30 @@
         }
 
         /**
+         * Sets the set of hash functions (e.g., {@code SHA-256}, {@code SHA-384}) which could be
+         * used by the mask generation function MGF1 (which is used for certain operations with
+         * the key). Attempts to use the key with any other digest for the mask generation
+         * function will be rejected.
+         *
+         * <p>This can only be specified for signing/verification keys and RSA encryption/decryption
+         * keys used with RSA OAEP padding scheme because these operations involve a mask generation
+         * function (MGF1) with a digest.
+         * The default digest for MGF1 is {@code SHA-1}, which will be specified during key creation
+         * time if no digests have been explicitly provided.
+         * When using the key, the caller may not specify any digests that were not provided during
+         * key creation time. The caller may specify the default digest, {@code SHA-1}, if no
+         * digests were explicitly provided during key creation (but it is not necessary to do so).
+         *
+         * <p>See {@link KeyProperties}.{@code DIGEST} constants.
+         */
+        @NonNull
+        @FlaggedApi("MGF1_DIGEST_SETTER")
+        public Builder setMgf1Digests(@Nullable @KeyProperties.DigestEnum String... mgf1Digests) {
+            mMgf1Digests = Set.of(mgf1Digests);
+            return this;
+        }
+
+        /**
          * Sets the set of padding schemes (e.g., {@code PKCS7Padding}, {@code OAEPPadding},
          * {@code PKCS1Padding}, {@code NoPadding}) with which the key can be used when
          * encrypting/decrypting. Attempts to use the key with any other padding scheme will be
@@ -1508,7 +1580,7 @@
          * key has purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}. If the key
          * does not have purpose {@link android.security.keystore.KeyProperties#PURPOSE_SIGN}, it is
          * not possible to use the key to sign a certificate, so the public key certificate will
-         * contain a dummy signature.
+         * contain a placeholder signature.
          *
          * <p>Symmetric keys, such as AES and HMAC keys, do not have public key certificates. If a
          * {@link #getAttestationChallenge()} returns non-null and the spec is used to generate a
@@ -1745,6 +1817,7 @@
                     mKeyValidityForConsumptionEnd,
                     mPurposes,
                     mDigests,
+                    mMgf1Digests,
                     mEncryptionPaddings,
                     mSignaturePaddings,
                     mBlockModes,
diff --git a/keystore/java/android/security/keystore/KeyProtection.java b/keystore/java/android/security/keystore/KeyProtection.java
index c14c3c5..1262a53 100644
--- a/keystore/java/android/security/keystore/KeyProtection.java
+++ b/keystore/java/android/security/keystore/KeyProtection.java
@@ -16,6 +16,7 @@
 
 package android.security.keystore;
 
+import android.annotation.FlaggedApi;
 import android.annotation.IntRange;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -30,7 +31,10 @@
 import java.security.KeyStore.ProtectionParameter;
 import java.security.Signature;
 import java.security.cert.Certificate;
+import java.util.Collections;
 import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
 
 import javax.crypto.Cipher;
 import javax.crypto.Mac;
@@ -223,6 +227,7 @@
     private final @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
     private final @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
     private final @KeyProperties.DigestEnum String[] mDigests;
+    private final @NonNull @KeyProperties.DigestEnum Set<String> mMgf1Digests;
     private final @KeyProperties.BlockModeEnum String[] mBlockModes;
     private final boolean mRandomizedEncryptionRequired;
     private final boolean mUserAuthenticationRequired;
@@ -246,6 +251,7 @@
             @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings,
             @KeyProperties.SignaturePaddingEnum String[] signaturePaddings,
             @KeyProperties.DigestEnum String[] digests,
+            @KeyProperties.DigestEnum Set<String> mgf1Digests,
             @KeyProperties.BlockModeEnum String[] blockModes,
             boolean randomizedEncryptionRequired,
             boolean userAuthenticationRequired,
@@ -269,6 +275,7 @@
         mSignaturePaddings =
                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings));
         mDigests = ArrayUtils.cloneIfNotEmpty(digests);
+        mMgf1Digests = mgf1Digests;
         mBlockModes = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(blockModes));
         mRandomizedEncryptionRequired = randomizedEncryptionRequired;
         mUserAuthenticationRequired = userAuthenticationRequired;
@@ -378,6 +385,40 @@
     }
 
     /**
+     * Returns the set of digests that can be used by the MGF1 mask generation function
+     * (e.g., {@code SHA-256}, {@code SHA-384}) with the key. Useful with the {@code RSA-OAEP}
+     * scheme.
+     * If not explicitly specified  during key generation, the default {@code SHA-1} digest is
+     * used and may be specified.
+     *
+     * <p>See {@link KeyProperties}.{@code DIGEST} constants.
+     *
+     * @throws IllegalStateException if this set has not been specified.
+     *
+     * @see #isMgf1DigestsSpecified()
+     */
+    @NonNull
+    @FlaggedApi("MGF1_DIGEST_SETTER")
+    public @KeyProperties.DigestEnum Set<String> getMgf1Digests() {
+        if (mMgf1Digests.isEmpty()) {
+            throw new IllegalStateException("Mask generation function (MGF) not specified");
+        }
+        return new HashSet(mMgf1Digests);
+    }
+
+    /**
+     * Returns {@code true} if the set of digests for the MGF1 mask generation function,
+     * with which the key can be used, has been specified. Useful with the {@code RSA-OAEP} scheme.
+     *
+     * @see #getMgf1Digests()
+     */
+    @NonNull
+    @FlaggedApi("MGF1_DIGEST_SETTER")
+    public boolean isMgf1DigestsSpecified() {
+        return !mMgf1Digests.isEmpty();
+    }
+
+    /**
      * Gets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be used
      * when encrypting/decrypting. Attempts to use the key with any other block modes will be
      * rejected.
@@ -574,6 +615,8 @@
         private @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
         private @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
         private @KeyProperties.DigestEnum String[] mDigests;
+        private @NonNull @KeyProperties.DigestEnum Set<String> mMgf1Digests =
+                Collections.emptySet();
         private @KeyProperties.BlockModeEnum String[] mBlockModes;
         private boolean mRandomizedEncryptionRequired = true;
         private boolean mUserAuthenticationRequired;
@@ -724,6 +767,30 @@
         }
 
         /**
+         * Sets the set of hash functions (e.g., {@code SHA-256}, {@code SHA-384}) which could be
+         * used by the mask generation function MGF1 (which is used for certain operations with
+         * the key). Attempts to use the key with any other digest for the mask generation
+         * function will be rejected.
+         *
+         * <p>This can only be specified for signing/verification keys and RSA encryption/decryption
+         * keys used with RSA OAEP padding scheme because these operations involve a mask generation
+         * function (MGF1) with a digest.
+         * The default digest for MGF1 is {@code SHA-1}, which will be specified during key import
+         * time if no digests have been explicitly provided.
+         * When using the key, the caller may not specify any digests that were not provided during
+         * key import time. The caller may specify the default digest, {@code SHA-1}, if no
+         * digests were explicitly provided during key import (but it is not necessary to do so).
+         *
+         * <p>See {@link KeyProperties}.{@code DIGEST} constants.
+         */
+        @NonNull
+        @FlaggedApi("MGF1_DIGEST_SETTER")
+        public Builder setMgf1Digests(@Nullable @KeyProperties.DigestEnum String... mgf1Digests) {
+            mMgf1Digests = Set.of(mgf1Digests);
+            return this;
+        }
+
+        /**
          * Sets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be
          * used when encrypting/decrypting. Attempts to use the key with any other block modes will
          * be rejected.
@@ -1111,6 +1178,7 @@
                     mEncryptionPaddings,
                     mSignaturePaddings,
                     mDigests,
+                    mMgf1Digests,
                     mBlockModes,
                     mRandomizedEncryptionRequired,
                     mUserAuthenticationRequired,
diff --git a/keystore/java/android/security/keystore/ParcelableKeyGenParameterSpec.java b/keystore/java/android/security/keystore/ParcelableKeyGenParameterSpec.java
index a6e3366..30b3b5c 100644
--- a/keystore/java/android/security/keystore/ParcelableKeyGenParameterSpec.java
+++ b/keystore/java/android/security/keystore/ParcelableKeyGenParameterSpec.java
@@ -23,7 +23,11 @@
 import java.security.spec.AlgorithmParameterSpec;
 import java.security.spec.ECGenParameterSpec;
 import java.security.spec.RSAKeyGenParameterSpec;
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.Date;
+import java.util.List;
+import java.util.Set;
 
 import javax.security.auth.x500.X500Principal;
 
@@ -91,6 +95,11 @@
         } else {
             out.writeStringArray(null);
         }
+        if (mSpec.isMgf1DigestsSpecified()) {
+            out.writeStringList(List.copyOf(mSpec.getMgf1Digests()));
+        } else {
+            out.writeStringList(null);
+        }
         out.writeStringArray(mSpec.getEncryptionPaddings());
         out.writeStringArray(mSpec.getSignaturePaddings());
         out.writeStringArray(mSpec.getBlockModes());
@@ -152,6 +161,7 @@
         final Date keyValidityForOriginationEnd = readDateOrNull(in);
         final Date keyValidityForConsumptionEnd = readDateOrNull(in);
         final String[] digests = in.createStringArray();
+        final ArrayList<String> mgf1Digests = in.createStringArrayList();
         final String[] encryptionPaddings = in.createStringArray();
         final String[] signaturePaddings = in.createStringArray();
         final String[] blockModes = in.createStringArray();
@@ -189,6 +199,7 @@
                 keyValidityForConsumptionEnd,
                 purposes,
                 digests,
+                mgf1Digests != null ? Set.copyOf(mgf1Digests) : Collections.emptySet(),
                 encryptionPaddings,
                 signaturePaddings,
                 blockModes,
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreCipherSpiBase.java b/keystore/java/android/security/keystore2/AndroidKeyStoreCipherSpiBase.java
index d129891..101a10e3 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreCipherSpiBase.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreCipherSpiBase.java
@@ -20,9 +20,11 @@
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.hardware.security.keymint.KeyParameter;
+import android.os.StrictMode;
 import android.security.KeyStoreException;
 import android.security.KeyStoreOperation;
 import android.security.keymaster.KeymasterDefs;
+import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyStoreCryptoOperation;
 import android.system.keystore2.Authorization;
 
@@ -70,7 +72,7 @@
  */
 abstract class AndroidKeyStoreCipherSpiBase extends CipherSpi implements KeyStoreCryptoOperation {
     private static final String TAG = "AndroidKeyStoreCipherSpiBase";
-    public static final String DEFAULT_MGF1_DIGEST = "SHA-1";
+    public static final String DEFAULT_MGF1_DIGEST = KeyProperties.DIGEST_SHA1;
 
     // Fields below are populated by Cipher.init and KeyStore.begin and should be preserved after
     // doFinal finishes.
@@ -137,6 +139,7 @@
         if (!(key instanceof AndroidKeyStorePrivateKey)
                 && (key instanceof PrivateKey || key instanceof PublicKey)) {
             try {
+                StrictMode.noteSlowCall("engineInit");
                 mCipher = Cipher.getInstance(getTransform());
                 String transform = getTransform();
 
@@ -203,6 +206,7 @@
         if (!(key instanceof AndroidKeyStorePrivateKey)
                 && (key instanceof PrivateKey || key instanceof PublicKey)) {
             try {
+                StrictMode.noteSlowCall("engineInit");
                 mCipher = Cipher.getInstance(getTransform());
                 mCipher.init(opmode, key, params, random);
                 return;
@@ -233,6 +237,7 @@
         if (!(key instanceof AndroidKeyStorePrivateKey)
                 && (key instanceof PrivateKey || key instanceof PublicKey)) {
             try {
+                StrictMode.noteSlowCall("engineInit");
                 mCipher = Cipher.getInstance(getTransform());
                 mCipher.init(opmode, key, params, random);
                 return;
@@ -346,6 +351,7 @@
         parameters.add(KeyStore2ParameterUtils.makeEnum(KeymasterDefs.KM_TAG_PURPOSE, purpose));
 
         try {
+            StrictMode.noteDiskRead();
             mOperation = mKey.getSecurityLevel().createOperation(
                     mKey.getKeyIdDescriptor(),
                     parameters
@@ -521,6 +527,7 @@
     @Override
     protected final void engineUpdateAAD(byte[] input, int inputOffset, int inputLen) {
         if (mCipher != null) {
+            StrictMode.noteSlowCall("engineUpdateAAD");
             mCipher.updateAAD(input, inputOffset, inputLen);
             return;
         }
@@ -562,6 +569,7 @@
     @Override
     protected final void engineUpdateAAD(ByteBuffer src) {
         if (mCipher != null) {
+            StrictMode.noteSlowCall("engineUpdateAAD");
             mCipher.updateAAD(src);
             return;
         }
@@ -715,6 +723,7 @@
             throw new NullPointerException("key == null");
         }
         byte[] encoded = null;
+        StrictMode.noteSlowCall("engineWrap");
         if (key instanceof SecretKey) {
             if ("RAW".equalsIgnoreCase(key.getFormat())) {
                 encoded = key.getEncoded();
@@ -807,6 +816,7 @@
             throw new InvalidKeyException("Failed to unwrap key", e);
         }
 
+        StrictMode.noteSlowCall("engineUnwrap");
         switch (wrappedKeyType) {
             case Cipher.SECRET_KEY:
             {
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java
index ace2053..9d3fca8 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreECDSASignatureSpi.java
@@ -195,7 +195,7 @@
     protected final void initKey(AndroidKeyStoreKey key) throws InvalidKeyException {
         if (!ACCEPTED_SIGNING_SCHEMES.contains(key.getAlgorithm().toLowerCase())) {
             throw new InvalidKeyException("Unsupported key algorithm: " + key.getAlgorithm()
-                    + ". Only" + Arrays.toString(ACCEPTED_SIGNING_SCHEMES.stream().toArray())
+                    + ". Only " + Arrays.toString(ACCEPTED_SIGNING_SCHEMES.stream().toArray())
                     + " supported");
         }
 
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyAgreementSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyAgreementSpi.java
index 7292cd3..66e9f71 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyAgreementSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyAgreementSpi.java
@@ -20,6 +20,7 @@
 import android.hardware.security.keymint.KeyParameter;
 import android.hardware.security.keymint.KeyPurpose;
 import android.hardware.security.keymint.Tag;
+import android.os.StrictMode;
 import android.security.KeyStoreException;
 import android.security.KeyStoreOperation;
 import android.security.keystore.KeyStoreCryptoOperation;
@@ -174,6 +175,7 @@
         }
         byte[] otherPartyKeyEncoded = mOtherPartyKey.getEncoded();
 
+        StrictMode.noteSlowCall("engineGenerateSecret");
         try {
             return mOperation.finish(otherPartyKeyEncoded, null);
         } catch (KeyStoreException e) {
@@ -245,6 +247,7 @@
                 Tag.PURPOSE, KeyPurpose.AGREE_KEY
         ));
 
+        StrictMode.noteDiskWrite();
         try {
             mOperation =
                     mKey.getSecurityLevel().createOperation(mKey.getKeyIdDescriptor(), parameters);
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyGeneratorSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyGeneratorSpi.java
index f1681ec..d283b05 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyGeneratorSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyGeneratorSpi.java
@@ -18,6 +18,7 @@
 
 import android.hardware.security.keymint.KeyParameter;
 import android.hardware.security.keymint.SecurityLevel;
+import android.os.StrictMode;
 import android.security.KeyStore2;
 import android.security.KeyStoreSecurityLevel;
 import android.security.keymaster.KeymasterDefs;
@@ -281,6 +282,7 @@
 
     @Override
     protected SecretKey engineGenerateKey() {
+        StrictMode.noteSlowCall("engineGenerateKey");
         KeyGenParameterSpec spec = mSpec;
         if (spec == null) {
             throw new IllegalStateException("Not initialized");
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java
index 474b7ea..ed4b485 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreKeyPairGeneratorSpi.java
@@ -27,6 +27,7 @@
 import android.hardware.security.keymint.SecurityLevel;
 import android.hardware.security.keymint.Tag;
 import android.os.Build;
+import android.os.StrictMode;
 import android.security.KeyPairGeneratorSpec;
 import android.security.KeyStore2;
 import android.security.KeyStoreException;
@@ -187,6 +188,7 @@
     private int[] mKeymasterEncryptionPaddings;
     private int[] mKeymasterSignaturePaddings;
     private int[] mKeymasterDigests;
+    private int[] mKeymasterMgf1Digests;
 
     private Long mRSAPublicExponent;
 
@@ -322,6 +324,21 @@
                 } else {
                     mKeymasterDigests = EmptyArray.INT;
                 }
+                if (spec.isMgf1DigestsSpecified()) {
+                    // User-specified digests: Add all of them and do _not_ add the SHA-1
+                    // digest by default (stick to what the user provided).
+                    Set<String> mgfDigests = spec.getMgf1Digests();
+                    mKeymasterMgf1Digests = new int[mgfDigests.size()];
+                    int offset = 0;
+                    for (String digest : mgfDigests) {
+                        mKeymasterMgf1Digests[offset] = KeyProperties.Digest.toKeymaster(digest);
+                        offset++;
+                    }
+                } else {
+                    // No user-specified digests: Add the SHA-1 default.
+                    mKeymasterMgf1Digests = new int[]{
+                            KeyProperties.Digest.toKeymaster(DEFAULT_MGF1_DIGEST)};
+                }
 
                 // Check that user authentication related parameters are acceptable. This method
                 // will throw an IllegalStateException if there are issues (e.g., secure lock screen
@@ -543,6 +560,7 @@
         mKeymasterEncryptionPaddings = null;
         mKeymasterSignaturePaddings = null;
         mKeymasterDigests = null;
+        mKeymasterMgf1Digests = null;
         mKeySizeBits = 0;
         mSpec = null;
         mRSAPublicExponent = null;
@@ -617,6 +635,7 @@
 
     @Override
     public KeyPair generateKeyPair() {
+        StrictMode.noteSlowCall("generateKeyPair");
         if (mKeyStore == null || mSpec == null) {
             throw new IllegalStateException("Not initialized");
         }
@@ -829,24 +848,11 @@
                     KeymasterDefs.KM_TAG_PADDING, padding
             ));
             if (padding == KeymasterDefs.KM_PAD_RSA_OAEP) {
-                final boolean[] hasDefaultMgf1DigestBeenAdded = {false};
-                ArrayUtils.forEach(mKeymasterDigests, (digest) -> {
+                ArrayUtils.forEach(mKeymasterMgf1Digests, (mgf1Digest) -> {
                     params.add(KeyStore2ParameterUtils.makeEnum(
-                            KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST, digest
+                            KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST, mgf1Digest
                     ));
-                    hasDefaultMgf1DigestBeenAdded[0] |=
-                            digest.equals(KeyProperties.Digest.toKeymaster(DEFAULT_MGF1_DIGEST));
                 });
-                /* Because of default MGF1 digest is SHA-1. It has to be added in Key
-                 * characteristics. Otherwise, crypto operations will fail with Incompatible
-                 * MGF1 digest.
-                 */
-                if (!hasDefaultMgf1DigestBeenAdded[0]) {
-                    params.add(KeyStore2ParameterUtils.makeEnum(
-                            KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST,
-                            KeyProperties.Digest.toKeymaster(DEFAULT_MGF1_DIGEST)
-                    ));
-                }
             }
         });
         ArrayUtils.forEach(mKeymasterSignaturePaddings, (padding) -> {
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreRSASignatureSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreRSASignatureSpi.java
index 931c2f8..d5fb49a 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreRSASignatureSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreRSASignatureSpi.java
@@ -189,7 +189,7 @@
     protected final void initKey(AndroidKeyStoreKey key) throws InvalidKeyException {
         if (!KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(key.getAlgorithm())) {
             throw new InvalidKeyException("Unsupported key algorithm: " + key.getAlgorithm()
-                    + ". Only" + KeyProperties.KEY_ALGORITHM_RSA + " supported");
+                    + ". Only " + KeyProperties.KEY_ALGORITHM_RSA + " supported");
         }
         super.initKey(key);
     }
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java b/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java
index 045e318..d3d9701 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreSpi.java
@@ -24,6 +24,7 @@
 import android.hardware.security.keymint.HardwareAuthenticatorType;
 import android.hardware.security.keymint.KeyParameter;
 import android.hardware.security.keymint.SecurityLevel;
+import android.os.StrictMode;
 import android.security.GateKeeper;
 import android.security.KeyStore2;
 import android.security.KeyStoreParameter;
@@ -36,6 +37,7 @@
 import android.security.keystore.SecureKeyImportUnavailableException;
 import android.security.keystore.WrappedKeyEntry;
 import android.system.keystore2.AuthenticatorSpec;
+import android.system.keystore2.Authorization;
 import android.system.keystore2.Domain;
 import android.system.keystore2.IKeystoreSecurityLevel;
 import android.system.keystore2.KeyDescriptor;
@@ -163,6 +165,7 @@
         KeyDescriptor descriptor = makeKeyDescriptor(alias);
 
         try {
+            StrictMode.noteDiskRead();
             return mKeyStore.getKeyEntry(descriptor);
         } catch (android.security.KeyStoreException e) {
             if (e.getErrorCode() != ResponseCode.KEY_NOT_FOUND) {
@@ -446,6 +449,7 @@
             assertCanReplace(alias, targetDomain, mNamespace, descriptor);
 
             try {
+                StrictMode.noteDiskWrite();
                 mKeyStore.updateSubcomponents(
                         ((AndroidKeyStorePrivateKey) key).getKeyIdDescriptor(),
                         userCertBytes, chainBytes);
@@ -522,25 +526,22 @@
                         padding
                 ));
                 if (padding == KeymasterDefs.KM_PAD_RSA_OAEP) {
-                    if (spec.isDigestsSpecified()) {
-                        boolean hasDefaultMgf1DigestBeenAdded = false;
-                        for (String digest : spec.getDigests()) {
+                    if (spec.isMgf1DigestsSpecified()) {
+                        for (String mgf1Digest : spec.getMgf1Digests()) {
                             importArgs.add(KeyStore2ParameterUtils.makeEnum(
                                     KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST,
-                                    KeyProperties.Digest.toKeymaster(digest)
+                                    KeyProperties.Digest.toKeymaster(mgf1Digest)
                             ));
-                            hasDefaultMgf1DigestBeenAdded |= digest.equals(DEFAULT_MGF1_DIGEST);
                         }
+                    } else {
                         /* Because of default MGF1 digest is SHA-1. It has to be added in Key
                          * characteristics. Otherwise, crypto operations will fail with Incompatible
                          * MGF1 digest.
                          */
-                        if (!hasDefaultMgf1DigestBeenAdded) {
-                            importArgs.add(KeyStore2ParameterUtils.makeEnum(
-                                    KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST,
-                                    KeyProperties.Digest.toKeymaster(DEFAULT_MGF1_DIGEST)
-                            ));
-                        }
+                        importArgs.add(KeyStore2ParameterUtils.makeEnum(
+                                KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST,
+                                KeyProperties.Digest.toKeymaster(DEFAULT_MGF1_DIGEST)
+                        ));
                     }
                 }
             }
@@ -596,6 +597,7 @@
                     importArgs, flags, pkcs8EncodedPrivateKeyBytes);
 
             try {
+                StrictMode.noteDiskWrite();
                 mKeyStore.updateSubcomponents(metadata.key, userCertBytes, chainBytes);
             } catch (android.security.KeyStoreException e) {
                 mKeyStore.deleteKey(metadata.key);
@@ -931,6 +933,7 @@
 
         KeyEntryResponse response = null;
         try {
+            StrictMode.noteDiskRead();
             response = mKeyStore.getKeyEntry(wrappingkey);
         } catch (android.security.KeyStoreException e) {
             throw new KeyStoreException("Failed to import wrapped key. Keystore error code: "
@@ -960,7 +963,34 @@
             authenticatorSpecs.add(authSpec);
         }
 
+        if (parts.length > 2) {
+            @KeyProperties.EncryptionPaddingEnum int padding =
+                    KeyProperties.EncryptionPadding.toKeymaster(parts[2]);
+            if (padding == KeymasterDefs.KM_PAD_RSA_OAEP
+                    && response.metadata != null
+                    && response.metadata.authorizations != null) {
+                Authorization[] keyCharacteristics = response.metadata.authorizations;
+
+                for (Authorization authorization : keyCharacteristics) {
+                    // Add default MGF1 digest SHA-1
+                    // when wrapping key has KM_TAG_RSA_OAEP_MGF_DIGEST tag
+                    if (authorization.keyParameter.tag
+                            == KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST) {
+                        // Default MGF1 digest is SHA-1
+                        // and KeyMint only supports default MGF1 digest crypto operations
+                        // for importWrappedKey.
+                        args.add(KeyStore2ParameterUtils.makeEnum(
+                                KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST,
+                                KeyProperties.Digest.toKeymaster(DEFAULT_MGF1_DIGEST)
+                        ));
+                        break;
+                    }
+                }
+            }
+        }
+
         try {
+            StrictMode.noteDiskWrite();
             securityLevel.importWrappedKey(
                     wrappedKey, wrappingkey,
                     entry.getWrappedKeyBytes(),
@@ -1021,6 +1051,7 @@
         }
 
         try {
+            StrictMode.noteDiskWrite();
             mKeyStore.updateSubcomponents(makeKeyDescriptor(alias),
                     null /* publicCert - unused when used as pure certificate store. */,
                     encoded);
@@ -1033,6 +1064,7 @@
     public void engineDeleteEntry(String alias) throws KeyStoreException {
         KeyDescriptor descriptor = makeKeyDescriptor(alias);
         try {
+            StrictMode.noteDiskWrite();
             mKeyStore.deleteKey(descriptor);
         } catch (android.security.KeyStoreException e) {
             if (e.getErrorCode() != ResponseCode.KEY_NOT_FOUND) {
@@ -1043,6 +1075,7 @@
 
     private KeyDescriptor[] getAliasesBatch(String startPastAlias) {
         try {
+            StrictMode.noteDiskRead();
             return mKeyStore.listBatch(
                     getTargetDomain(),
                     mNamespace,
@@ -1070,6 +1103,7 @@
     @Override
     public int engineSize() {
         try {
+            StrictMode.noteDiskRead();
             return mKeyStore.getNumberOfEntries(
                     getTargetDomain(),
                     mNamespace
@@ -1133,6 +1167,7 @@
 
         KeyDescriptor[] keyDescriptors = null;
         try {
+            StrictMode.noteDiskRead();
             keyDescriptors = mKeyStore.list(
                     getTargetDomain(),
                     mNamespace
diff --git a/keystore/java/android/security/keystore2/KeyStore2ParameterUtils.java b/keystore/java/android/security/keystore2/KeyStore2ParameterUtils.java
index 54955c6..1394bd44 100644
--- a/keystore/java/android/security/keystore2/KeyStore2ParameterUtils.java
+++ b/keystore/java/android/security/keystore2/KeyStore2ParameterUtils.java
@@ -325,32 +325,25 @@
             args.add(KeyStore2ParameterUtils.makeBool(
                     KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED));
         } else {
-            if (spec.getUserAuthenticationValidityDurationSeconds() == 0) {
-                // Every use of this key needs to be authorized by the user.
-                addSids(args, spec);
-                args.add(KeyStore2ParameterUtils.makeEnum(
-                        KeymasterDefs.KM_TAG_USER_AUTH_TYPE, spec.getUserAuthenticationType()
-                ));
-
-                if (spec.isUserAuthenticationValidWhileOnBody()) {
-                    throw new ProviderException(
-                            "Key validity extension while device is on-body is not "
-                                    + "supported for keys requiring fingerprint authentication");
-                }
-            } else {
-                addSids(args, spec);
-                args.add(KeyStore2ParameterUtils.makeEnum(
-                        KeymasterDefs.KM_TAG_USER_AUTH_TYPE, spec.getUserAuthenticationType()
-                ));
+            addSids(args, spec);
+            args.add(KeyStore2ParameterUtils.makeEnum(
+                    KeymasterDefs.KM_TAG_USER_AUTH_TYPE, spec.getUserAuthenticationType()
+            ));
+            if (spec.getUserAuthenticationValidityDurationSeconds() != 0) {
                 args.add(KeyStore2ParameterUtils.makeInt(
                         KeymasterDefs.KM_TAG_AUTH_TIMEOUT,
                         spec.getUserAuthenticationValidityDurationSeconds()
                 ));
-                if (spec.isUserAuthenticationValidWhileOnBody()) {
-                    args.add(KeyStore2ParameterUtils.makeBool(
-                            KeymasterDefs.KM_TAG_ALLOW_WHILE_ON_BODY
-                    ));
+            }
+            if (spec.isUserAuthenticationValidWhileOnBody()) {
+                if (spec.getUserAuthenticationValidityDurationSeconds() == 0) {
+                    throw new ProviderException(
+                            "Key validity extension while device is on-body is not "
+                                    + "supported for keys requiring fingerprint authentication");
                 }
+                args.add(KeyStore2ParameterUtils.makeBool(
+                        KeymasterDefs.KM_TAG_ALLOW_WHILE_ON_BODY
+                ));
             }
         }
     }
diff --git a/keystore/tests/src/android/security/ParcelableKeyGenParameterSpecTest.java b/keystore/tests/src/android/security/ParcelableKeyGenParameterSpecTest.java
index 2ae61ab..d4e2dbc 100644
--- a/keystore/tests/src/android/security/ParcelableKeyGenParameterSpecTest.java
+++ b/keystore/tests/src/android/security/ParcelableKeyGenParameterSpecTest.java
@@ -17,6 +17,7 @@
 package android.security;
 
 import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertThat;
 
@@ -101,6 +102,7 @@
         assertThat(spec.getKeyValidityForOriginationEnd(), is(KEY_VALIDITY_FOR_ORIG_END));
         assertThat(spec.getKeyValidityForConsumptionEnd(), is(KEY_VALIDITY_FOR_CONSUMPTION_END));
         assertThat(spec.getDigests(), is(new String[] {DIGEST}));
+        assertThat(spec.isMgf1DigestsSpecified(), is(false));
         assertThat(spec.getEncryptionPaddings(), is(new String[] {ENCRYPTION_PADDING}));
         assertThat(spec.getSignaturePaddings(), is(new String[] {SIGNATURE_PADDING}));
         assertThat(spec.getBlockModes(), is(new String[] {BLOCK_MODE}));
@@ -189,4 +191,19 @@
         ECGenParameterSpec parcelSpec = (ECGenParameterSpec) fromParcel.getAlgorithmParameterSpec();
         assertEquals(parcelSpec.getName(), ecSpec.getName());
     }
+
+    @Test
+    public void testParcelingMgf1Digests() {
+        String[] mgf1Digests =
+                new String[] {KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256};
+
+        ParcelableKeyGenParameterSpec spec = new ParcelableKeyGenParameterSpec(
+                new KeyGenParameterSpec.Builder(ALIAS, KEY_PURPOSES)
+                        .setMgf1Digests(mgf1Digests)
+                        .build());
+        Parcel parcel = parcelForReading(spec);
+        KeyGenParameterSpec fromParcel =
+                ParcelableKeyGenParameterSpec.CREATOR.createFromParcel(parcel).getSpec();
+        assertArrayEquals(fromParcel.getMgf1Digests().toArray(), mgf1Digests);
+    }
 }
diff --git a/keystore/tests/src/android/security/keystore/KeyGenParameterSpecTest.java b/keystore/tests/src/android/security/keystore/KeyGenParameterSpecTest.java
index ddbb1d8..da5e8bf 100644
--- a/keystore/tests/src/android/security/keystore/KeyGenParameterSpecTest.java
+++ b/keystore/tests/src/android/security/keystore/KeyGenParameterSpecTest.java
@@ -16,9 +16,12 @@
 
 package android.security.keystore;
 
+import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertThrows;
 
 import android.security.ParcelableKeyGenParameterSpecTest;
 
@@ -61,4 +64,54 @@
 
         assertEquals(copiedSpec.getAttestationChallenge(), null);
     }
+
+    @Test
+    public void testMgf1DigestsNotSpecifiedByDefault() {
+        KeyGenParameterSpec spec = ParcelableKeyGenParameterSpecTest.configureDefaultSpec();
+        assertThat(spec.isMgf1DigestsSpecified(), is(false));
+        assertThrows(IllegalStateException.class, () -> {
+            spec.getMgf1Digests();
+        });
+    }
+
+    @Test
+    public void testMgf1DigestsCanBeSpecified() {
+        String[] mgf1Digests =
+                new String[] {KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256};
+        KeyGenParameterSpec spec =  new KeyGenParameterSpec.Builder(ALIAS, KEY_PURPOSES)
+                .setMgf1Digests(mgf1Digests)
+                .build();
+        assertThat(spec.isMgf1DigestsSpecified(), is(true));
+        assertThat(spec.getMgf1Digests(), containsInAnyOrder(mgf1Digests));
+
+        KeyGenParameterSpec copiedSpec = new KeyGenParameterSpec.Builder(spec).build();
+        assertThat(copiedSpec.isMgf1DigestsSpecified(), is(true));
+        assertThat(copiedSpec.getMgf1Digests(), containsInAnyOrder(mgf1Digests));
+    }
+
+    @Test
+    public void testMgf1DigestsAreNotModified() {
+        String[] mgf1Digests =
+                new String[] {KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256};
+        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(ALIAS, KEY_PURPOSES)
+                .setMgf1Digests(mgf1Digests);
+
+        KeyGenParameterSpec firstSpec =  builder.build();
+        assertArrayEquals(mgf1Digests, firstSpec.getMgf1Digests().toArray());
+
+        String[] otherDigests = new String[] {KeyProperties.DIGEST_SHA224};
+        KeyGenParameterSpec secondSpec =  builder.setMgf1Digests(otherDigests).build();
+        assertThat(secondSpec.getMgf1Digests(), containsInAnyOrder(otherDigests));
+
+        // Now check that the first spec created hasn't changed.
+        assertThat(firstSpec.getMgf1Digests(), containsInAnyOrder(mgf1Digests));
+    }
+
+    @Test
+    public void testEmptyMgf1DigestsCanBeSet() {
+        KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(ALIAS, KEY_PURPOSES)
+                .setMgf1Digests(new String[] {}).build();
+
+        assertThat(spec.isMgf1DigestsSpecified(), is(false));
+    }
 }
diff --git a/libs/WindowManager/Shell/Android.bp b/libs/WindowManager/Shell/Android.bp
index b3108fe..c00a749 100644
--- a/libs/WindowManager/Shell/Android.bp
+++ b/libs/WindowManager/Shell/Android.bp
@@ -110,8 +110,7 @@
     name: "protolog.json.gz",
     srcs: [":generate-wm_shell_protolog.json"],
     out: ["wmshell.protolog.json.gz"],
-    cmd: "$(location minigzip) -c < $(in) > $(out)",
-    tools: ["minigzip"],
+    cmd: "gzip -c < $(in) > $(out)",
 }
 
 prebuilt_etc {
@@ -162,7 +161,7 @@
         // *.kt sources are inside a filegroup.
         "kotlin-annotations",
     ],
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
     manifest: "AndroidManifest.xml",
     plugins: ["dagger2-compiler"],
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
index 541c0f0..2b3ee76 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/BubbleController.java
@@ -307,16 +307,20 @@
                 new OneHandedTransitionCallback() {
                     @Override
                     public void onStartFinished(Rect bounds) {
-                        if (mStackView != null) {
-                            mStackView.onVerticalOffsetChanged(bounds.top);
-                        }
+                        mMainExecutor.execute(() -> {
+                            if (mStackView != null) {
+                                mStackView.onVerticalOffsetChanged(bounds.top);
+                            }
+                        });
                     }
 
                     @Override
                     public void onStopFinished(Rect bounds) {
-                        if (mStackView != null) {
-                            mStackView.onVerticalOffsetChanged(bounds.top);
-                        }
+                        mMainExecutor.execute(() -> {
+                            if (mStackView != null) {
+                                mStackView.onVerticalOffsetChanged(bounds.top);
+                            }
+                        });
                     }
                 });
     }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/FloatingContentCoordinator.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/common/FloatingContentCoordinator.kt
index d5d072a..122dcbb 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/FloatingContentCoordinator.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/FloatingContentCoordinator.kt
@@ -94,7 +94,6 @@
          * non-overlapping.
          * @return The new bounds for this content.
          */
-        @JvmDefault
         fun calculateNewBoundsOnOverlap(
             overlappingContentBounds: Rect,
             otherContentBounds: List<Rect>
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitDecorManager.java b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitDecorManager.java
index bdf0ac2..4c2e0da 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitDecorManager.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/common/split/SplitDecorManager.java
@@ -164,6 +164,10 @@
             t.remove(mGapBackgroundLeash);
             mGapBackgroundLeash = null;
         }
+        if (mScreenshot != null) {
+            t.remove(mScreenshot);
+            mScreenshot = null;
+        }
         mHostLeash = null;
         mIcon = null;
         mResizingIconView = null;
@@ -323,6 +327,8 @@
         if (!mShown && mIsResizing && !mOldBounds.equals(mResizingBounds)) {
             if (mScreenshotAnimator != null && mScreenshotAnimator.isRunning()) {
                 mScreenshotAnimator.cancel();
+            } else if (mScreenshot != null) {
+                t.remove(mScreenshot);
             }
 
             mTempRect.set(mOldBounds);
@@ -339,6 +345,8 @@
         if (!mShown && mIsResizing && !mOldBounds.equals(mResizingBounds)) {
             if (mScreenshotAnimator != null && mScreenshotAnimator.isRunning()) {
                 mScreenshotAnimator.cancel();
+            } else if (mScreenshot != null) {
+                t.remove(mScreenshot);
             }
 
             mScreenshot = screenshot;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeTaskRepository.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeTaskRepository.kt
index 47342c9..935a588 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeTaskRepository.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeTaskRepository.kt
@@ -173,7 +173,6 @@
         /**
          * Called when the active tasks change in desktop mode.
          */
-        @JvmDefault
         fun onActiveTasksChanged() {}
     }
 
@@ -184,7 +183,6 @@
         /**
          * Called when the desktop starts or stops showing freeform tasks.
          */
-        @JvmDefault
         fun onVisibilityChanged(hasVisibleFreeformTasks: Boolean) {}
     }
 }
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
index c4b5470..7da7502 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTaskOrganizer.java
@@ -73,7 +73,6 @@
 import android.window.TaskSnapshot;
 import android.window.WindowContainerToken;
 import android.window.WindowContainerTransaction;
-import android.window.WindowContainerTransactionCallback;
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.protolog.common.ProtoLog;
@@ -145,23 +144,6 @@
     protected final ShellTaskOrganizer mTaskOrganizer;
     protected final ShellExecutor mMainExecutor;
 
-    // the runnable to execute after WindowContainerTransactions is applied to finish resizing pip
-    private Runnable mPipFinishResizeWCTRunnable;
-
-    private final WindowContainerTransactionCallback mPipFinishResizeWCTCallback =
-            new WindowContainerTransactionCallback() {
-        @Override
-        public void onTransactionReady(int id, SurfaceControl.Transaction t) {
-            t.apply();
-
-            // execute the runnable if non-null after WCT is applied to finish resizing pip
-            if (mPipFinishResizeWCTRunnable != null) {
-                mPipFinishResizeWCTRunnable.run();
-                mPipFinishResizeWCTRunnable = null;
-            }
-        }
-    };
-
     // These callbacks are called on the update thread
     private final PipAnimationController.PipAnimationCallback mPipAnimationCallback =
             new PipAnimationController.PipAnimationCallback() {
@@ -1278,23 +1260,8 @@
     /**
      * Animates resizing of the pinned stack given the duration and start bounds.
      * This is used when the starting bounds is not the current PiP bounds.
-     *
-     * @param pipFinishResizeWCTRunnable callback to run after window updates are complete
      */
     public void scheduleAnimateResizePip(Rect fromBounds, Rect toBounds, int duration,
-            float startingAngle, Consumer<Rect> updateBoundsCallback,
-            Runnable pipFinishResizeWCTRunnable) {
-        mPipFinishResizeWCTRunnable = pipFinishResizeWCTRunnable;
-        if (mPipFinishResizeWCTRunnable != null) {
-            ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
-                    "mPipFinishResizeWCTRunnable is set to be called once window updates");
-        }
-
-        scheduleAnimateResizePip(fromBounds, toBounds, duration, startingAngle,
-                updateBoundsCallback);
-    }
-
-    private void scheduleAnimateResizePip(Rect fromBounds, Rect toBounds, int duration,
             float startingAngle, Consumer<Rect> updateBoundsCallback) {
         if (mWaitForFixedRotation) {
             ProtoLog.d(ShellProtoLogGroup.WM_SHELL_PICTURE_IN_PICTURE,
@@ -1599,7 +1566,7 @@
             mSplitScreenOptional.ifPresent(splitScreenController ->
                     splitScreenController.enterSplitScreen(mTaskInfo.taskId, wasPipTopLeft, wct));
         } else {
-            mTaskOrganizer.applySyncTransaction(wct, mPipFinishResizeWCTCallback);
+            mTaskOrganizer.applyTransaction(wct);
         }
     }
 
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipResizeGestureHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipResizeGestureHandler.java
index 3e83c5f..41ff0b3 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipResizeGestureHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipResizeGestureHandler.java
@@ -580,16 +580,8 @@
                 final float snapFraction = mPipBoundsAlgorithm.getSnapFraction(
                         mLastResizeBounds, movementBounds);
                 mPipBoundsAlgorithm.applySnapFraction(mLastResizeBounds, snapFraction);
-
-                // disable the pinch resizing until the final bounds are updated
-                final boolean prevEnablePinchResize = mEnablePinchResize;
-                mEnablePinchResize = false;
-
                 mPipTaskOrganizer.scheduleAnimateResizePip(startBounds, mLastResizeBounds,
-                        PINCH_RESIZE_SNAP_DURATION, mAngle, mUpdateResizeBoundsCallback, () -> {
-                            // reset the pinch resizing to its default state
-                            mEnablePinchResize = prevEnablePinchResize;
-                        });
+                        PINCH_RESIZE_SNAP_DURATION, mAngle, mUpdateResizeBoundsCallback);
             } else {
                 mPipTaskOrganizer.scheduleFinishResizePip(mLastResizeBounds,
                         PipAnimationController.TRANSITION_DIRECTION_USER_RESIZE,
diff --git a/libs/WindowManager/Shell/tests/unittest/Android.bp b/libs/WindowManager/Shell/tests/unittest/Android.bp
index 2ac1dc0..64bb481 100644
--- a/libs/WindowManager/Shell/tests/unittest/Android.bp
+++ b/libs/WindowManager/Shell/tests/unittest/Android.bp
@@ -61,7 +61,7 @@
         "libstaticjvmtiagent",
     ],
 
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
 
     plugins: ["dagger2-compiler"],
 
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java
index 5f356c9..c7b9eb3 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/pip/phone/PipResizeGestureHandlerTest.java
@@ -155,7 +155,7 @@
         mPipResizeGestureHandler.onPinchResize(upEvent);
 
         verify(mPipTaskOrganizer, times(1))
-                .scheduleAnimateResizePip(any(), any(), anyInt(), anyFloat(), any(), any());
+                .scheduleAnimateResizePip(any(), any(), anyInt(), anyFloat(), any());
 
         assertTrue("The new size should be bigger than the original PiP size.",
                 mPipResizeGestureHandler.getLastResizeBounds().width()
@@ -194,7 +194,7 @@
         mPipResizeGestureHandler.onPinchResize(upEvent);
 
         verify(mPipTaskOrganizer, times(1))
-                .scheduleAnimateResizePip(any(), any(), anyInt(), anyFloat(), any(), any());
+                .scheduleAnimateResizePip(any(), any(), anyInt(), anyFloat(), any());
 
         assertTrue("The new size should be smaller than the original PiP size.",
                 mPipResizeGestureHandler.getLastResizeBounds().width()
diff --git a/libs/androidfw/Android.bp b/libs/androidfw/Android.bp
index c80fb18..86e1fe3d 100644
--- a/libs/androidfw/Android.bp
+++ b/libs/androidfw/Android.bp
@@ -80,7 +80,10 @@
     export_include_dirs: ["include"],
     export_shared_lib_headers: ["libz"],
     static_libs: ["libincfs-utils"],
-    whole_static_libs: ["libincfs-utils"],
+    whole_static_libs: [
+        "libandroidfw_pathutils",
+        "libincfs-utils",
+    ],
     export_static_lib_headers: ["libincfs-utils"],
     target: {
         android: {
@@ -132,6 +135,28 @@
     },
 }
 
+cc_library_static {
+    name: "libandroidfw_pathutils",
+    defaults: ["libandroidfw_defaults"],
+    host_supported: true,
+    export_include_dirs: ["include_pathutils"],
+    srcs: [
+        "PathUtils.cpp",
+    ],
+    shared_libs: [
+        "libutils",
+    ],
+    target: {
+        windows: {
+            enabled: true,
+        },
+    },
+    visibility: [
+        ":__subpackages__",
+        "//frameworks/base/tools/aapt",
+    ],
+}
+
 common_test_libs = [
     "libandroidfw",
     "libbase",
diff --git a/libs/androidfw/AssetManager.cpp b/libs/androidfw/AssetManager.cpp
index fb2b571..68befff 100644
--- a/libs/androidfw/AssetManager.cpp
+++ b/libs/androidfw/AssetManager.cpp
@@ -26,6 +26,7 @@
 #include <androidfw/AssetDir.h>
 #include <androidfw/AssetManager.h>
 #include <androidfw/misc.h>
+#include <androidfw/PathUtils.h>
 #include <androidfw/ResourceTypes.h>
 #include <androidfw/ZipFileRO.h>
 #include <cutils/atomic.h>
@@ -88,10 +89,10 @@
     const char* root = getenv("ANDROID_DATA");
     LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_DATA not set");
     String8 path(root);
-    path.appendPath(kResourceCache);
+    appendPath(path, kResourceCache);
 
     char buf[256]; // 256 chars should be enough for anyone...
-    strncpy(buf, pkgPath.string(), 255);
+    strncpy(buf, pkgPath.c_str(), 255);
     buf[255] = '\0';
     char* filename = buf;
     while (*filename && *filename == '/') {
@@ -104,7 +105,7 @@
         }
         ++p;
     }
-    path.appendPath(filename);
+    appendPath(path, filename);
     path.append("@idmap");
 
     return path;
@@ -181,17 +182,17 @@
 
     String8 realPath(path);
     if (kAppZipName) {
-        realPath.appendPath(kAppZipName);
+        appendPath(realPath, kAppZipName);
     }
-    ap.type = ::getFileType(realPath.string());
+    ap.type = ::getFileType(realPath.c_str());
     if (ap.type == kFileTypeRegular) {
         ap.path = realPath;
     } else {
         ap.path = path;
-        ap.type = ::getFileType(path.string());
+        ap.type = ::getFileType(path.c_str());
         if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
             ALOGW("Asset path %s is neither a directory nor file (type=%d).",
-                 path.string(), (int)ap.type);
+                 path.c_str(), (int)ap.type);
             return false;
         }
     }
@@ -207,7 +208,7 @@
     }
 
     ALOGV("In %p Asset %s path: %s", this,
-         ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
+         ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.c_str());
 
     ap.isSystemAsset = isSystemAsset;
     ssize_t apPos = mAssetPaths.add(ap);
@@ -248,7 +249,7 @@
 
     Asset* idmap = NULL;
     if ((idmap = openAssetFromFileLocked(idmapPath, Asset::ACCESS_BUFFER)) == NULL) {
-        ALOGW("failed to open idmap file %s\n", idmapPath.string());
+        ALOGW("failed to open idmap file %s\n", idmapPath.c_str());
         return false;
     }
 
@@ -256,7 +257,7 @@
     String8 overlayPath;
     if (!ResTable::getIdmapInfo(idmap->getBuffer(false), idmap->getLength(),
                 NULL, NULL, NULL, &targetPath, &overlayPath)) {
-        ALOGW("failed to read idmap file %s\n", idmapPath.string());
+        ALOGW("failed to read idmap file %s\n", idmapPath.c_str());
         delete idmap;
         return false;
     }
@@ -264,29 +265,29 @@
 
     if (overlayPath != packagePath) {
         ALOGW("idmap file %s inconcistent: expected path %s does not match actual path %s\n",
-                idmapPath.string(), packagePath.string(), overlayPath.string());
+                idmapPath.c_str(), packagePath.c_str(), overlayPath.c_str());
         return false;
     }
-    if (access(targetPath.string(), R_OK) != 0) {
-        ALOGW("failed to access file %s: %s\n", targetPath.string(), strerror(errno));
+    if (access(targetPath.c_str(), R_OK) != 0) {
+        ALOGW("failed to access file %s: %s\n", targetPath.c_str(), strerror(errno));
         return false;
     }
-    if (access(idmapPath.string(), R_OK) != 0) {
-        ALOGW("failed to access file %s: %s\n", idmapPath.string(), strerror(errno));
+    if (access(idmapPath.c_str(), R_OK) != 0) {
+        ALOGW("failed to access file %s: %s\n", idmapPath.c_str(), strerror(errno));
         return false;
     }
-    if (access(overlayPath.string(), R_OK) != 0) {
-        ALOGW("failed to access file %s: %s\n", overlayPath.string(), strerror(errno));
+    if (access(overlayPath.c_str(), R_OK) != 0) {
+        ALOGW("failed to access file %s: %s\n", overlayPath.c_str(), strerror(errno));
         return false;
     }
 
     asset_path oap;
     oap.path = overlayPath;
-    oap.type = ::getFileType(overlayPath.string());
+    oap.type = ::getFileType(overlayPath.c_str());
     oap.idmap = idmapPath;
 #if 0
     ALOGD("Overlay added: targetPath=%s overlayPath=%s idmapPath=%s\n",
-            targetPath.string(), overlayPath.string(), idmapPath.string());
+            targetPath.c_str(), overlayPath.c_str(), idmapPath.c_str());
 #endif
     mAssetPaths.add(oap);
     *cookie = static_cast<int32_t>(mAssetPaths.size());
@@ -310,7 +311,7 @@
     ap.type = kFileTypeRegular;
     ap.assumeOwnership = assume_ownership;
 
-    ALOGV("In %p Asset fd %d name: %s", this, fd, ap.path.string());
+    ALOGV("In %p Asset fd %d name: %s", this, fd, ap.path.c_str());
 
     ssize_t apPos = mAssetPaths.add(ap);
 
@@ -343,11 +344,11 @@
             assets[i] = openNonAssetInPathLocked("resources.arsc",
                     Asset::ACCESS_BUFFER, ap);
             if (assets[i] == NULL) {
-                ALOGW("failed to find resources.arsc in %s\n", ap.path.string());
+                ALOGW("failed to find resources.arsc in %s\n", ap.path.c_str());
                 goto exit;
             }
             if (tables[i].add(assets[i]) != NO_ERROR) {
-                ALOGW("failed to add %s to resource table", paths[i].string());
+                ALOGW("failed to add %s to resource table", paths[i].c_str());
                 goto exit;
             }
         }
@@ -367,7 +368,7 @@
     LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
 
     String8 path(root);
-    path.appendPath(kSystemAssets);
+    appendPath(path, kSystemAssets);
 
     return addAssetPath(path, NULL, false /* appAsLib */, true /* isSystemAsset */);
 }
@@ -439,7 +440,7 @@
     LOG_FATAL_IF(mAssetPaths.size() == 0, "No assets added to AssetManager");
 
     String8 assetName(kAssetsRoot);
-    assetName.appendPath(fileName);
+    appendPath(assetName, fileName);
 
     /*
      * For each top-level asset path, search for the asset.
@@ -449,8 +450,8 @@
     while (i > 0) {
         i--;
         ALOGV("Looking for asset '%s' in '%s'\n",
-                assetName.string(), mAssetPaths.itemAt(i).path.string());
-        Asset* pAsset = openNonAssetInPathLocked(assetName.string(), mode,
+                assetName.c_str(), mAssetPaths.itemAt(i).path.c_str());
+        Asset* pAsset = openNonAssetInPathLocked(assetName.c_str(), mode,
                 mAssetPaths.editItemAt(i));
         if (pAsset != NULL) {
             return pAsset != kExcludedAsset ? pAsset : NULL;
@@ -478,7 +479,7 @@
     size_t i = mAssetPaths.size();
     while (i > 0) {
         i--;
-        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.string());
+        ALOGV("Looking for non-asset '%s' in '%s'\n", fileName, mAssetPaths.itemAt(i).path.c_str());
         Asset* pAsset = openNonAssetInPathLocked(
             fileName, mode, mAssetPaths.editItemAt(i));
         if (pAsset != NULL) {
@@ -500,7 +501,7 @@
 
     if (which < mAssetPaths.size()) {
         ALOGV("Looking for non-asset '%s' in '%s'\n", fileName,
-                mAssetPaths.itemAt(which).path.string());
+                mAssetPaths.itemAt(which).path.c_str());
         Asset* pAsset = openNonAssetInPathLocked(
             fileName, mode, mAssetPaths.editItemAt(which));
         if (pAsset != NULL) {
@@ -546,10 +547,10 @@
     ResTable* sharedRes = NULL;
     bool shared = true;
     bool onlyEmptyResources = true;
-    ATRACE_NAME(ap.path.string());
+    ATRACE_NAME(ap.path.c_str());
     Asset* idmap = openIdmapLocked(ap);
     size_t nextEntryIdx = mResources->getTableCount();
-    ALOGV("Looking for resource asset in '%s'\n", ap.path.string());
+    ALOGV("Looking for resource asset in '%s'\n", ap.path.c_str());
     if (ap.type != kFileTypeDirectory && ap.rawFd < 0) {
         if (nextEntryIdx == 0) {
             // The first item is typically the framework resources,
@@ -565,7 +566,7 @@
             ass = const_cast<AssetManager*>(this)->
                 mZipSet.getZipResourceTableAsset(ap.path);
             if (ass == NULL) {
-                ALOGV("loading resource table %s\n", ap.path.string());
+                ALOGV("loading resource table %s\n", ap.path.c_str());
                 ass = const_cast<AssetManager*>(this)->
                     openNonAssetInPathLocked("resources.arsc",
                                              Asset::ACCESS_BUFFER,
@@ -580,23 +581,23 @@
                 // If this is the first resource table in the asset
                 // manager, then we are going to cache it so that we
                 // can quickly copy it out for others.
-                ALOGV("Creating shared resources for %s", ap.path.string());
+                ALOGV("Creating shared resources for %s", ap.path.c_str());
                 sharedRes = new ResTable();
                 sharedRes->add(ass, idmap, nextEntryIdx + 1, false);
 #ifdef __ANDROID__
                 const char* data = getenv("ANDROID_DATA");
                 LOG_ALWAYS_FATAL_IF(data == NULL, "ANDROID_DATA not set");
                 String8 overlaysListPath(data);
-                overlaysListPath.appendPath(kResourceCache);
-                overlaysListPath.appendPath("overlays.list");
-                addSystemOverlays(overlaysListPath.string(), ap.path, sharedRes, nextEntryIdx);
+                appendPath(overlaysListPath, kResourceCache);
+                appendPath(overlaysListPath, "overlays.list");
+                addSystemOverlays(overlaysListPath.c_str(), ap.path, sharedRes, nextEntryIdx);
 #endif
                 sharedRes = const_cast<AssetManager*>(this)->
                     mZipSet.setZipResourceTable(ap.path, sharedRes);
             }
         }
     } else {
-        ALOGV("loading resource table %s\n", ap.path.string());
+        ALOGV("loading resource table %s\n", ap.path.c_str());
         ass = const_cast<AssetManager*>(this)->
             openNonAssetInPathLocked("resources.arsc",
                                      Asset::ACCESS_BUFFER,
@@ -607,10 +608,10 @@
     if ((ass != NULL || sharedRes != NULL) && ass != kExcludedAsset) {
         ALOGV("Installing resource asset %p in to table %p\n", ass, mResources);
         if (sharedRes != NULL) {
-            ALOGV("Copying existing resources for %s", ap.path.string());
+            ALOGV("Copying existing resources for %s", ap.path.c_str());
             mResources->add(sharedRes, ap.isSystemAsset);
         } else {
-            ALOGV("Parsing resources for %s", ap.path.string());
+            ALOGV("Parsing resources for %s", ap.path.c_str());
             mResources->add(ass, idmap, nextEntryIdx + 1, !shared, appAsLib, ap.isSystemAsset);
         }
         onlyEmptyResources = false;
@@ -692,9 +693,9 @@
         ass = const_cast<AssetManager*>(this)->
             openAssetFromFileLocked(ap.idmap, Asset::ACCESS_BUFFER);
         if (ass) {
-            ALOGV("loading idmap %s\n", ap.idmap.string());
+            ALOGV("loading idmap %s\n", ap.idmap.c_str());
         } else {
-            ALOGW("failed to load idmap %s\n", ap.idmap.string());
+            ALOGW("failed to load idmap %s\n", ap.idmap.c_str());
         }
     }
     return ass;
@@ -789,7 +790,7 @@
     /* look at the filesystem on disk */
     if (ap.type == kFileTypeDirectory) {
         String8 path(ap.path);
-        path.appendPath(fileName);
+        appendPath(path, fileName);
 
         pAsset = openAssetFromFileLocked(path, mode);
 
@@ -811,10 +812,10 @@
         /* check the appropriate Zip file */
         ZipFileRO* pZip = getZipFileLocked(ap);
         if (pZip != NULL) {
-            ALOGV("GOT zip, checking NA '%s'", (const char*) path);
-            ZipEntryRO entry = pZip->findEntryByName(path.string());
+            ALOGV("GOT zip, checking NA '%s'", path.c_str());
+            ZipEntryRO entry = pZip->findEntryByName(path.c_str());
             if (entry != NULL) {
-                ALOGV("FOUND NA in Zip file for %s", (const char*) path);
+                ALOGV("FOUND NA in Zip file for %s", path.c_str());
                 pAsset = openAssetFromZipLocked(pZip, entry, mode, path);
                 pZip->releaseEntry(entry);
             }
@@ -823,7 +824,7 @@
         if (pAsset != NULL) {
             /* create a "source" name, for debug/display */
             pAsset->setAssetSource(
-                    createZipSourceNameLocked(ZipSet::getPathName(ap.path.string()), String8(""),
+                    createZipSourceNameLocked(ZipSet::getPathName(ap.path.c_str()), String8(""),
                                                 String8(fileName)));
         }
     }
@@ -841,9 +842,9 @@
     sourceName.append(zipFileName);
     sourceName.append(":");
     if (dirName.length() > 0) {
-        sourceName.appendPath(dirName);
+        appendPath(sourceName, dirName);
     }
-    sourceName.appendPath(fileName);
+    appendPath(sourceName, fileName);
     return sourceName;
 }
 
@@ -853,7 +854,7 @@
 String8 AssetManager::createPathNameLocked(const asset_path& ap, const char* rootDir)
 {
     String8 path(ap.path);
-    if (rootDir != NULL) path.appendPath(rootDir);
+    if (rootDir != NULL) appendPath(path, rootDir);
     return path;
 }
 
@@ -870,7 +871,7 @@
     }
 
     if (ap.rawFd < 0) {
-        ALOGV("getZipFileLocked: Creating new zip from path %s", ap.path.string());
+        ALOGV("getZipFileLocked: Creating new zip from path %s", ap.path.c_str());
         ap.zip = mZipSet.getSharedZip(ap.path);
     } else {
         ALOGV("getZipFileLocked: Creating new zip from fd %d", ap.rawFd);
@@ -897,12 +898,12 @@
 {
     Asset* pAsset = NULL;
 
-    if (strcasecmp(pathName.getPathExtension().string(), ".gz") == 0) {
+    if (strcasecmp(getPathExtension(pathName).c_str(), ".gz") == 0) {
         //printf("TRYING '%s'\n", (const char*) pathName);
-        pAsset = Asset::createFromCompressedFile(pathName.string(), mode);
+        pAsset = Asset::createFromCompressedFile(pathName.c_str(), mode);
     } else {
         //printf("TRYING '%s'\n", (const char*) pathName);
-        pAsset = Asset::createFromFile(pathName.string(), mode);
+        pAsset = Asset::createFromFile(pathName.c_str(), mode);
     }
 
     return pAsset;
@@ -940,12 +941,12 @@
 
     if (method == ZipFileRO::kCompressStored) {
         pAsset = Asset::createFromUncompressedMap(std::move(*dataMap), mode);
-        ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.string(),
+        ALOGV("Opened uncompressed entry %s in zip %s mode %d: %p", entryName.c_str(),
                 dataMap->file_name(), mode, pAsset.get());
     } else {
         pAsset = Asset::createFromCompressedMap(std::move(*dataMap),
             static_cast<size_t>(uncompressedLen), mode);
-        ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.string(),
+        ALOGV("Opened compressed entry %s in zip %s mode %d: %p", entryName.c_str(),
                 dataMap->file_name(), mode, pAsset.get());
     }
     if (pAsset == NULL) {
@@ -993,10 +994,10 @@
         i--;
         const asset_path& ap = mAssetPaths.itemAt(i);
         if (ap.type == kFileTypeRegular) {
-            ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
+            ALOGV("Adding directory %s from zip %s", dirName, ap.path.c_str());
             scanAndMergeZipLocked(pMergedInfo, ap, kAssetsRoot, dirName);
         } else {
-            ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
+            ALOGV("Adding directory %s from dir %s", dirName, ap.path.c_str());
             scanAndMergeDirLocked(pMergedInfo, ap, kAssetsRoot, dirName);
         }
     }
@@ -1042,10 +1043,10 @@
     if (which < mAssetPaths.size()) {
         const asset_path& ap = mAssetPaths.itemAt(which);
         if (ap.type == kFileTypeRegular) {
-            ALOGV("Adding directory %s from zip %s", dirName, ap.path.string());
+            ALOGV("Adding directory %s from zip %s", dirName, ap.path.c_str());
             scanAndMergeZipLocked(pMergedInfo, ap, NULL, dirName);
         } else {
-            ALOGV("Adding directory %s from dir %s", dirName, ap.path.string());
+            ALOGV("Adding directory %s from dir %s", dirName, ap.path.c_str());
             scanAndMergeDirLocked(pMergedInfo, ap, NULL, dirName);
         }
     }
@@ -1075,11 +1076,10 @@
 {
     assert(pMergedInfo != NULL);
 
-    //printf("scanAndMergeDir: %s %s %s\n", ap.path.string(), rootDir, dirName);
+    //printf("scanAndMergeDir: %s %s %s\n", ap.path.c_str(), rootDir, dirName);
 
     String8 path = createPathNameLocked(ap, rootDir);
-    if (dirName[0] != '\0')
-        path.appendPath(dirName);
+    if (dirName[0] != '\0') appendPath(path, dirName);
 
     SortedVector<AssetDir::FileInfo>* pContents = scanDirLocked(path);
     if (pContents == NULL)
@@ -1100,7 +1100,7 @@
         const char* name;
         int nameLen;
 
-        name = pContents->itemAt(i).getFileName().string();
+        name = pContents->itemAt(i).getFileName().c_str();
         nameLen = strlen(name);
         if (nameLen > exclExtLen &&
             strcmp(name + (nameLen - exclExtLen), kExcludeExtension) == 0)
@@ -1111,8 +1111,8 @@
             matchIdx = AssetDir::FileInfo::findEntry(pMergedInfo, match);
             if (matchIdx > 0) {
                 ALOGV("Excluding '%s' [%s]\n",
-                    pMergedInfo->itemAt(matchIdx).getFileName().string(),
-                    pMergedInfo->itemAt(matchIdx).getSourceName().string());
+                    pMergedInfo->itemAt(matchIdx).getFileName().c_str(),
+                    pMergedInfo->itemAt(matchIdx).getSourceName().c_str());
                 pMergedInfo->removeAt(matchIdx);
             } else {
                 //printf("+++ no match on '%s'\n", (const char*) match);
@@ -1150,9 +1150,9 @@
     struct dirent* entry;
     FileType fileType;
 
-    ALOGV("Scanning dir '%s'\n", path.string());
+    ALOGV("Scanning dir '%s'\n", path.c_str());
 
-    dir = opendir(path.string());
+    dir = opendir(path.c_str());
     if (dir == NULL)
         return NULL;
 
@@ -1176,7 +1176,7 @@
             fileType = kFileTypeUnknown;
 #else
         // stat the file
-        fileType = ::getFileType(path.appendPathCopy(entry->d_name).string());
+        fileType = ::getFileType(appendPathCopy(path, entry->d_name).c_str());
 #endif
 
         if (fileType != kFileTypeRegular && fileType != kFileTypeDirectory)
@@ -1184,9 +1184,9 @@
 
         AssetDir::FileInfo info;
         info.set(String8(entry->d_name), fileType);
-        if (strcasecmp(info.getFileName().getPathExtension().string(), ".gz") == 0)
-            info.setFileName(info.getFileName().getBasePath());
-        info.setSourceName(path.appendPathCopy(info.getFileName()));
+        if (strcasecmp(getPathExtension(info.getFileName()).c_str(), ".gz") == 0)
+            info.setFileName(getBasePath(info.getFileName()));
+        info.setSourceName(appendPathCopy(path, info.getFileName()));
         pContents->add(info);
     }
 
@@ -1212,15 +1212,15 @@
 
     pZip = mZipSet.getZip(ap.path);
     if (pZip == NULL) {
-        ALOGW("Failure opening zip %s\n", ap.path.string());
+        ALOGW("Failure opening zip %s\n", ap.path.c_str());
         return false;
     }
 
-    zipName = ZipSet::getPathName(ap.path.string());
+    zipName = ZipSet::getPathName(ap.path.c_str());
 
     /* convert "sounds" to "rootDir/sounds" */
     if (rootDir != NULL) dirName = rootDir;
-    dirName.appendPath(baseDirName);
+    appendPath(dirName, baseDirName);
 
     /*
      * Scan through the list of files, looking for a match.  The files in
@@ -1240,7 +1240,7 @@
      */
     int dirNameLen = dirName.length();
     void *iterationCookie;
-    if (!pZip->startIteration(&iterationCookie, dirName.string(), NULL)) {
+    if (!pZip->startIteration(&iterationCookie, dirName.c_str(), NULL)) {
         ALOGW("ZipFileRO::startIteration returned false");
         return false;
     }
@@ -1254,7 +1254,7 @@
             ALOGE("ARGH: name too long?\n");
             continue;
         }
-        //printf("Comparing %s in %s?\n", nameBuf, dirName.string());
+        //printf("Comparing %s in %s?\n", nameBuf, dirName.c_str());
         if (dirNameLen == 0 || nameBuf[dirNameLen] == '/')
         {
             const char* cp;
@@ -1269,13 +1269,13 @@
             if (nextSlash == NULL) {
                 /* this is a file in the requested directory */
 
-                info.set(String8(nameBuf).getPathLeaf(), kFileTypeRegular);
+                info.set(getPathLeaf(String8(nameBuf)), kFileTypeRegular);
 
                 info.setSourceName(
                     createZipSourceNameLocked(zipName, dirName, info.getFileName()));
 
                 contents.add(info);
-                //printf("FOUND: file '%s'\n", info.getFileName().string());
+                //printf("FOUND: file '%s'\n", info.getFileName().c_str());
             } else {
                 /* this is a subdir; add it if we don't already have it*/
                 String8 subdirName(cp, nextSlash - cp);
@@ -1291,7 +1291,7 @@
                     dirs.add(subdirName);
                 }
 
-                //printf("FOUND: dir '%s'\n", subdirName.string());
+                //printf("FOUND: dir '%s'\n", subdirName.c_str());
             }
         }
     }
@@ -1425,12 +1425,12 @@
       mResourceTableAsset(NULL), mResourceTable(NULL)
 {
     if (kIsDebug) {
-        ALOGI("Creating SharedZip %p %s\n", this, (const char*)mPath);
+        ALOGI("Creating SharedZip %p %s\n", this, mPath.c_str());
     }
-    ALOGV("+++ opening zip '%s'\n", mPath.string());
-    mZipFile = ZipFileRO::open(mPath.string());
+    ALOGV("+++ opening zip '%s'\n", mPath.c_str());
+    mZipFile = ZipFileRO::open(mPath.c_str());
     if (mZipFile == NULL) {
-        ALOGD("failed to open Zip archive '%s'\n", mPath.string());
+        ALOGD("failed to open Zip archive '%s'\n", mPath.c_str());
     }
 }
 
@@ -1439,13 +1439,13 @@
       mResourceTableAsset(NULL), mResourceTable(NULL)
 {
     if (kIsDebug) {
-        ALOGI("Creating SharedZip %p fd=%d %s\n", this, fd, (const char*)mPath);
+        ALOGI("Creating SharedZip %p fd=%d %s\n", this, fd, mPath.c_str());
     }
-    ALOGV("+++ opening zip fd=%d '%s'\n", fd, mPath.string());
-    mZipFile = ZipFileRO::openFd(fd, mPath.string());
+    ALOGV("+++ opening zip fd=%d '%s'\n", fd, mPath.c_str());
+    mZipFile = ZipFileRO::openFd(fd, mPath.c_str());
     if (mZipFile == NULL) {
         ::close(fd);
-        ALOGD("failed to open Zip archive fd=%d '%s'\n", fd, mPath.string());
+        ALOGD("failed to open Zip archive fd=%d '%s'\n", fd, mPath.c_str());
     }
 }
 
@@ -1453,7 +1453,7 @@
         bool createIfNotPresent)
 {
     AutoMutex _l(gLock);
-    time_t modWhen = getFileModDate(path);
+    time_t modWhen = getFileModDate(path.c_str());
     sp<SharedZip> zip = gOpen.valueFor(path).promote();
     if (zip != NULL && zip->mModWhen == modWhen) {
         return zip;
@@ -1520,7 +1520,7 @@
 
 bool AssetManager::SharedZip::isUpToDate()
 {
-    time_t modWhen = getFileModDate(mPath.string());
+    time_t modWhen = getFileModDate(mPath.c_str());
     return mModWhen == modWhen;
 }
 
@@ -1541,7 +1541,7 @@
 AssetManager::SharedZip::~SharedZip()
 {
     if (kIsDebug) {
-        ALOGI("Destroying SharedZip %p %s\n", this, (const char*)mPath);
+        ALOGI("Destroying SharedZip %p %s\n", this, mPath.c_str());
     }
     if (mResourceTable != NULL) {
         delete mResourceTable;
@@ -1551,7 +1551,7 @@
     }
     if (mZipFile != NULL) {
         delete mZipFile;
-        ALOGV("Closed '%s'\n", mPath.string());
+        ALOGV("Closed '%s'\n", mPath.c_str());
     }
 }
 
diff --git a/libs/androidfw/AssetManager2.cpp b/libs/androidfw/AssetManager2.cpp
index 400829e..daed277 100644
--- a/libs/androidfw/AssetManager2.cpp
+++ b/libs/androidfw/AssetManager2.cpp
@@ -99,6 +99,13 @@
   StringPoolRef entry_string_ref;
 };
 
+struct Theme::Entry {
+  uint32_t attr_res_id;
+  ApkAssetsCookie cookie;
+  uint32_t type_spec_flags;
+  Res_value value;
+};
+
 AssetManager2::AssetManager2() {
   memset(&configuration_, 0, sizeof(configuration_));
 }
@@ -890,14 +897,14 @@
     }
 
     log_stream << "\n\t" << prefix->second << ": " << apk_assets_[step.cookie]->GetDebugName();
-    if (!step.config_name.isEmpty()) {
+    if (!step.config_name.empty()) {
       log_stream << " - " << step.config_name;
     }
   }
 
   log_stream << "\nBest matching is from "
-             << (last_resolution_.best_config_name.isEmpty() ? "default"
-                                                   : last_resolution_.best_config_name)
+             << (last_resolution_.best_config_name.empty() ? "default"
+                    : last_resolution_.best_config_name.c_str())
              << " configuration of " << last_resolution_.best_package_name;
   return log_stream.str();
 }
@@ -1411,13 +1418,6 @@
 
 Theme::~Theme() = default;
 
-struct Theme::Entry {
-  uint32_t attr_res_id;
-  ApkAssetsCookie cookie;
-  uint32_t type_spec_flags;
-  Res_value value;
-};
-
 namespace {
 struct ThemeEntryKeyComparer {
   bool operator() (const Theme::Entry& entry, uint32_t attr_res_id) const noexcept {
diff --git a/libs/androidfw/BackupData.cpp b/libs/androidfw/BackupData.cpp
index 76a430e..fec0e77 100644
--- a/libs/androidfw/BackupData.cpp
+++ b/libs/androidfw/BackupData.cpp
@@ -106,8 +106,8 @@
         k = key;
     }
     if (kIsDebug) {
-        ALOGD("Writing header: prefix='%s' key='%s' dataSize=%zu", m_keyPrefix.string(),
-                key.string(), dataSize);
+        ALOGD("Writing header: prefix='%s' key='%s' dataSize=%zu", m_keyPrefix.c_str(),
+                key.c_str(), dataSize);
     }
 
     entity_header_v1 header;
@@ -128,7 +128,7 @@
     m_pos += amt;
 
     if (kIsDebug) ALOGI("writing entity header key, %zd bytes", keyLen+1);
-    amt = write(m_fd, k.string(), keyLen+1);
+    amt = write(m_fd, k.c_str(), keyLen+1);
     if (amt != keyLen+1) {
         m_status = errno;
         return m_status;
diff --git a/libs/androidfw/BackupHelpers.cpp b/libs/androidfw/BackupHelpers.cpp
index e80e948..1a6a952 100644
--- a/libs/androidfw/BackupHelpers.cpp
+++ b/libs/androidfw/BackupHelpers.cpp
@@ -30,6 +30,7 @@
 #include <utime.h>
 #include <zlib.h>
 
+#include <androidfw/PathUtils.h>
 #include <log/log.h>
 #include <utils/ByteOrder.h>
 #include <utils/KeyedVector.h>
@@ -179,7 +180,7 @@
             }
 
             // filename is not NULL terminated, but it is padded
-            amt = write(fd, name.string(), nameLen);
+            amt = write(fd, name.c_str(), nameLen);
             if (amt != nameLen) {
                 ALOGW("write_snapshot_file error writing filename %s", strerror(errno));
                 return 1;
@@ -203,7 +204,7 @@
 static int
 write_delete_file(BackupDataWriter* dataStream, const String8& key)
 {
-    LOGP("write_delete_file %s\n", key.string());
+    LOGP("write_delete_file %s\n", key.c_str());
     return dataStream->WriteEntityHeader(key, -1);
 }
 
@@ -211,7 +212,7 @@
 write_update_file(BackupDataWriter* dataStream, int fd, int mode, const String8& key,
         char const* realFilename)
 {
-    LOGP("write_update_file %s (%s) : mode 0%o\n", realFilename, key.string(), mode);
+    LOGP("write_update_file %s (%s) : mode 0%o\n", realFilename, key.c_str(), mode);
 
     const int bufsize = 4*1024;
     int err;
@@ -365,7 +366,7 @@
             r.s.size = st.st_size;
 
             if (newSnapshot.indexOfKey(key) >= 0) {
-                LOGP("back_up_files key already in use '%s'", key.string());
+                LOGP("back_up_files key already in use '%s'", key.c_str());
                 return -1;
             }
 
@@ -390,30 +391,30 @@
         int cmp = p.compare(q);
         if (cmp < 0) {
             // file present in oldSnapshot, but not present in newSnapshot
-            LOGP("file removed: %s", p.string());
+            LOGP("file removed: %s", p.c_str());
             write_delete_file(dataStream, p);
             n++;
         } else if (cmp > 0) {
             // file added
-            LOGP("file added: %s crc=0x%08x", g.file.string(), g.s.crc32);
-            write_update_file(dataStream, q, g.file.string());
+            LOGP("file added: %s crc=0x%08x", g.file.c_str(), g.s.crc32);
+            write_update_file(dataStream, q, g.file.c_str());
             m++;
         } else {
             // same file exists in both old and new; check whether to update
             const FileState& f = oldSnapshot.valueAt(n);
 
-            LOGP("%s", q.string());
+            LOGP("%s", q.c_str());
             LOGP("  old: modTime=%d,%d mode=%04o size=%-3d crc32=0x%08x",
                     f.modTime_sec, f.modTime_nsec, f.mode, f.size, f.crc32);
             LOGP("  new: modTime=%d,%d mode=%04o size=%-3d crc32=0x%08x",
                     g.s.modTime_sec, g.s.modTime_nsec, g.s.mode, g.s.size, g.s.crc32);
             if (f.modTime_sec != g.s.modTime_sec || f.modTime_nsec != g.s.modTime_nsec
                     || f.mode != g.s.mode || f.size != g.s.size || f.crc32 != g.s.crc32) {
-                int fd = open(g.file.string(), O_RDONLY);
+                int fd = open(g.file.c_str(), O_RDONLY);
                 if (fd < 0) {
-                    ALOGE("Unable to read file for backup: %s", g.file.string());
+                    ALOGE("Unable to read file for backup: %s", g.file.c_str());
                 } else {
-                    write_update_file(dataStream, fd, g.s.mode, p, g.file.string());
+                    write_update_file(dataStream, fd, g.s.mode, p, g.file.c_str());
                     close(fd);
                 }
             }
@@ -432,7 +433,7 @@
     while (m<M) {
         const String8& q = newSnapshot.keyAt(m);
         FileRec& g = newSnapshot.editValueAt(m);
-        write_update_file(dataStream, q, g.file.string());
+        write_update_file(dataStream, q, g.file.c_str());
         m++;
     }
 
@@ -483,7 +484,7 @@
         BackupDataWriter* writer)
 {
     // In the output stream everything is stored relative to the root
-    const char* relstart = filepath.string() + rootpath.length();
+    const char* relstart = filepath.c_str() + rootpath.length();
     if (*relstart == '/') relstart++;     // won't be true when path == rootpath
     String8 relpath(relstart);
 
@@ -514,9 +515,9 @@
 
     int err = 0;
     struct stat64 s;
-    if (lstat64(filepath.string(), &s) != 0) {
+    if (lstat64(filepath.c_str(), &s) != 0) {
         err = errno;
-        ALOGE("Error %d (%s) from lstat64(%s)", err, strerror(err), filepath.string());
+        ALOGE("Error %d (%s) from lstat64(%s)", err, strerror(err), filepath.c_str());
         return err;
     }
 
@@ -541,10 +542,10 @@
 
     // !!! TODO: use mmap when possible to avoid churning the buffer cache
     // !!! TODO: this will break with symlinks; need to use readlink(2)
-    int fd = open(filepath.string(), O_RDONLY);
+    int fd = open(filepath.c_str(), O_RDONLY);
     if (fd < 0) {
         err = errno;
-        ALOGE("Error %d (%s) from open(%s)", err, strerror(err), filepath.string());
+        ALOGE("Error %d (%s) from open(%s)", err, strerror(err), filepath.c_str());
         return err;
     }
 
@@ -592,7 +593,7 @@
     } else if (S_ISREG(s.st_mode)) {
         type = '0';     // tar magic: '0' == normal file
     } else {
-        ALOGW("Error: unknown file mode 0%o [%s]", s.st_mode, filepath.string());
+        ALOGW("Error: unknown file mode 0%o [%s]", s.st_mode, filepath.c_str());
         goto cleanup;
     }
     buf[156] = type;
@@ -606,30 +607,30 @@
             prefix += packageName;
         }
         if (domain.length() > 0) {
-            prefix.appendPath(domain);
+            appendPath(prefix, domain);
         }
 
         // pax extended means we don't put in a prefix field, and put a different
         // string in the basic name field.  We can also construct the full path name
         // out of the substrings we've now built.
         fullname = prefix;
-        fullname.appendPath(relpath);
+        appendPath(fullname, relpath);
 
         // ustar:
         //    [   0 : 100 ]; file name/path
         //    [ 345 : 155 ] filename path prefix
         // We only use the prefix area if fullname won't fit in the path
         if (fullname.length() > 100) {
-            strncpy(buf, relpath.string(), 100);
-            strncpy(buf + 345, prefix.string(), 155);
+            strncpy(buf, relpath.c_str(), 100);
+            strncpy(buf + 345, prefix.c_str(), 155);
         } else {
-            strncpy(buf, fullname.string(), 100);
+            strncpy(buf, fullname.c_str(), 100);
         }
     }
 
     // [ 329 : 8 ] and [ 337 : 8 ] devmajor/devminor, not used
 
-    ALOGI("   Name: %s", fullname.string());
+    ALOGI("   Name: %s", fullname.c_str());
 
     // If we're using a pax extended header, build & write that here; lengths are
     // already preflighted
@@ -647,18 +648,18 @@
 
         // fullname was generated above with the ustar paths
         paxLen += write_pax_header_entry(paxData + paxLen, PAXDATA_SIZE - paxLen,
-                "path", fullname.string());
+                "path", fullname.c_str());
 
         // Now we know how big the pax data is
 
         // Now build the pax *header* templated on the ustar header
         memcpy(paxHeader, buf, 512);
 
-        String8 leaf = fullname.getPathLeaf();
+        String8 leaf = getPathLeaf(fullname);
         memset(paxHeader, 0, 100);                  // rewrite the name area
-        snprintf(paxHeader, 100, "PaxHeader/%s", leaf.string());
+        snprintf(paxHeader, 100, "PaxHeader/%s", leaf.c_str());
         memset(paxHeader + 345, 0, 155);            // rewrite the prefix area
-        strncpy(paxHeader + 345, prefix.string(), 155);
+        strncpy(paxHeader + 345, prefix.c_str(), 155);
 
         paxHeader[156] = 'x';                       // mark it as a pax extended header
 
@@ -691,12 +692,12 @@
             ssize_t nRead = read(fd, buf, toRead);
             if (nRead < 0) {
                 err = errno;
-                ALOGE("Unable to read file [%s], err=%d (%s)", filepath.string(),
+                ALOGE("Unable to read file [%s], err=%d (%s)", filepath.c_str(),
                         err, strerror(err));
                 break;
             } else if (nRead == 0) {
                 ALOGE("EOF but expect %lld more bytes in [%s]", (long long) toWrite,
-                        filepath.string());
+                        filepath.c_str());
                 err = EIO;
                 break;
             }
@@ -762,7 +763,7 @@
     file_metadata_v1 metadata;
     amt = in->ReadEntityData(&metadata, sizeof(metadata));
     if (amt != sizeof(metadata)) {
-        ALOGW("Could not read metadata for %s -- %ld / %s", filename.string(),
+        ALOGW("Could not read metadata for %s -- %ld / %s", filename.c_str(),
                 (long)amt, strerror(errno));
         return EIO;
     }
@@ -779,9 +780,9 @@
 
     // Write the file and compute the crc
     crc = crc32(0L, Z_NULL, 0);
-    fd = open(filename.string(), O_CREAT|O_RDWR|O_TRUNC, mode);
+    fd = open(filename.c_str(), O_CREAT|O_RDWR|O_TRUNC, mode);
     if (fd == -1) {
-        ALOGW("Could not open file %s -- %s", filename.string(), strerror(errno));
+        ALOGW("Could not open file %s -- %s", filename.c_str(), strerror(errno));
         return errno;
     }
 
@@ -789,7 +790,7 @@
         err = write(fd, buf, amt);
         if (err != amt) {
             close(fd);
-            ALOGW("Error '%s' writing '%s'", strerror(errno), filename.string());
+            ALOGW("Error '%s' writing '%s'", strerror(errno), filename.c_str());
             return errno;
         }
         crc = crc32(crc, (Bytef*)buf, amt);
@@ -798,9 +799,9 @@
     close(fd);
 
     // Record for the snapshot
-    err = stat(filename.string(), &st);
+    err = stat(filename.c_str(), &st);
     if (err != 0) {
-        ALOGW("Error stating file that we just created %s", filename.string());
+        ALOGW("Error stating file that we just created %s", filename.c_str());
         return errno;
     }
 
@@ -1104,9 +1105,9 @@
             fprintf(stderr, "state %zu expected={%d/%d, %04o, 0x%08x, 0x%08x, %3zu} '%s'\n"
                             "          actual={%d/%d, %04o, 0x%08x, 0x%08x, %3d} '%s'\n", i,
                     states[i].modTime_sec, states[i].modTime_nsec, states[i].mode, states[i].size,
-                    states[i].crc32, name.length(), filenames[i].string(),
+                    states[i].crc32, name.length(), filenames[i].c_str(),
                     state.modTime_sec, state.modTime_nsec, state.mode, state.size, state.crc32,
-                    state.nameLen, name.string());
+                    state.nameLen, name.c_str());
             matched = false;
         }
     }
@@ -1152,9 +1153,9 @@
         return err;
     }
 
-    err = writer.WriteEntityData(text.string(), text.length()+1);
+    err = writer.WriteEntityData(text.c_str(), text.length()+1);
     if (err != 0) {
-        fprintf(stderr, "write failed for data '%s'\n", text.string());
+        fprintf(stderr, "write failed for data '%s'\n", text.c_str());
         return errno;
     }
 
@@ -1230,7 +1231,7 @@
         goto finished;
     }
     if (string != str) {
-        fprintf(stderr, "ReadEntityHeader expected key '%s' got '%s'\n", str, string.string());
+        fprintf(stderr, "ReadEntityHeader expected key '%s' got '%s'\n", str, string.c_str());
         err = EINVAL;
         goto finished;
     }
diff --git a/libs/androidfw/ConfigDescription.cpp b/libs/androidfw/ConfigDescription.cpp
index 19ead95..952101b 100644
--- a/libs/androidfw/ConfigDescription.cpp
+++ b/libs/androidfw/ConfigDescription.cpp
@@ -878,7 +878,7 @@
 
 std::string ConfigDescription::to_string() const {
   const String8 str = toString();
-  return std::string(str.string(), str.size());
+  return std::string(str.c_str(), str.size());
 }
 
 bool ConfigDescription::Dominates(const ConfigDescription& o) const {
diff --git a/libs/androidfw/CursorWindow.cpp b/libs/androidfw/CursorWindow.cpp
index 3527eee..5aa8e70 100644
--- a/libs/androidfw/CursorWindow.cpp
+++ b/libs/androidfw/CursorWindow.cpp
@@ -84,7 +84,7 @@
     String8 ashmemName("CursorWindow: ");
     ashmemName.append(mName);
 
-    ashmemFd = ashmem_create_region(ashmemName.string(), mInflatedSize);
+    ashmemFd = ashmem_create_region(ashmemName.c_str(), mInflatedSize);
     if (ashmemFd < 0) {
         PLOG(ERROR) << "Failed ashmem_create_region";
         goto fail_silent;
diff --git a/libs/androidfw/OWNERS b/libs/androidfw/OWNERS
index 17f5164..ef4cc46 100644
--- a/libs/androidfw/OWNERS
+++ b/libs/androidfw/OWNERS
@@ -1,7 +1,6 @@
 set noparent
-toddke@google.com
 zyy@google.com
 patb@google.com
 
 per-file CursorWindow.cpp=omakoto@google.com
-per-file LocaleDataTables.cpp=vichang@google.com,ngeoffray@google.com,nikitai@google.com
+per-file LocaleDataTables.cpp=vichang@google.com,ngeoffray@google.com
diff --git a/libs/androidfw/ObbFile.cpp b/libs/androidfw/ObbFile.cpp
index 95332a3..c6a9632 100644
--- a/libs/androidfw/ObbFile.cpp
+++ b/libs/androidfw/ObbFile.cpp
@@ -217,7 +217,7 @@
     free(scanBuf);
 
 #ifdef DEBUG
-    ALOGI("Obb scan succeeded: packageName=%s, version=%d\n", mPackageName.string(), mVersion);
+    ALOGI("Obb scan succeeded: packageName=%s, version=%d\n", mPackageName.c_str(), mVersion);
 #endif
 
     return true;
@@ -288,7 +288,7 @@
         return false;
     }
 
-    if (write(fd, mPackageName.string(), packageNameLen) != (ssize_t)packageNameLen) {
+    if (write(fd, mPackageName.c_str(), packageNameLen) != (ssize_t)packageNameLen) {
         ALOGW("couldn't write package name: %s\n", strerror(errno));
         return false;
     }
diff --git a/libs/androidfw/PathUtils.cpp b/libs/androidfw/PathUtils.cpp
new file mode 100644
index 0000000..df7a9f0
--- /dev/null
+++ b/libs/androidfw/PathUtils.cpp
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2023 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 <androidfw/PathUtils.h>
+
+#include <utils/Compat.h>
+
+namespace android {
+
+String8 getPathLeaf(const String8& str) {
+    const char* cp;
+    const char*const buf = str.c_str();
+
+    cp = strrchr(buf, OS_PATH_SEPARATOR);
+    if (cp == nullptr)
+        return str;
+    else
+        return String8(cp+1);
+}
+
+String8 getPathDir(const String8& str8) {
+    const char* cp;
+    const char*const str = str8.c_str();
+
+    cp = strrchr(str, OS_PATH_SEPARATOR);
+    if (cp == nullptr)
+        return String8();
+    else
+        return String8(str, cp - str);
+}
+
+static char* findExtension(const String8& str8) {
+    const char* lastSlash;
+    const char* lastDot;
+    const char* const str = str8.c_str();
+
+    // only look at the filename
+    lastSlash = strrchr(str, OS_PATH_SEPARATOR);
+    if (lastSlash == nullptr)
+        lastSlash = str;
+    else
+        lastSlash++;
+
+    // find the last dot
+    lastDot = strrchr(lastSlash, '.');
+    if (lastDot == nullptr)
+        return nullptr;
+
+    // looks good, ship it
+    return const_cast<char*>(lastDot);
+}
+
+String8 getPathExtension(const String8& str) {
+    char* ext;
+
+    ext = findExtension(str);
+    if (ext != nullptr)
+        return String8(ext);
+    else
+        return String8();
+}
+
+String8 getBasePath(const String8& str8) {
+    char* ext;
+    const char* const str = str8.c_str();
+
+    ext = findExtension(str8);
+    if (ext == nullptr)
+        return str8;
+    else
+        return String8(str, ext - str);
+}
+
+static void setPathName(String8& s, const char* name) {
+    size_t len = strlen(name);
+    char* buf = s.lockBuffer(len);
+
+    memcpy(buf, name, len);
+
+    // remove trailing path separator, if present
+    if (len > 0 && buf[len - 1] == OS_PATH_SEPARATOR) len--;
+    buf[len] = '\0';
+
+    s.unlockBuffer(len);
+}
+
+String8& appendPath(String8& str, const char* name) {
+    // TODO: The test below will fail for Win32 paths. Fix later or ignore.
+    if (name[0] != OS_PATH_SEPARATOR) {
+        if (*name == '\0') {
+            // nothing to do
+            return str;
+        }
+
+        size_t len = str.length();
+        if (len == 0) {
+            // no existing filename, just use the new one
+            setPathName(str, name);
+            return str;
+        }
+
+        // make room for oldPath + '/' + newPath
+        int newlen = strlen(name);
+
+        char* buf = str.lockBuffer(len+1+newlen);
+
+        // insert a '/' if needed
+        if (buf[len-1] != OS_PATH_SEPARATOR)
+            buf[len++] = OS_PATH_SEPARATOR;
+
+        memcpy(buf+len, name, newlen+1);
+        len += newlen;
+
+        str.unlockBuffer(len);
+        return str;
+    } else {
+        setPathName(str, name);
+        return str;
+    }
+}
+
+} // namespace android
diff --git a/libs/androidfw/ResourceTypes.cpp b/libs/androidfw/ResourceTypes.cpp
index 5e8a623..11d153e 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -1029,7 +1029,7 @@
 
     if ((mHeader->flags&ResStringPool_header::UTF8_FLAG) != 0) {
         if (kDebugStringPoolNoisy) {
-            ALOGI("indexOfString UTF-8: %s", String8(str, strLen).string());
+            ALOGI("indexOfString UTF-8: %s", String8(str, strLen).c_str());
         }
 
         // The string pool contains UTF 8 strings; we don't want to cause
@@ -1090,7 +1090,7 @@
                         ALOGI("Looking at %s, i=%d\n", s->data(), i);
                     }
                     if (str8Len == s->size()
-                            && memcmp(s->data(), str8.string(), str8Len) == 0) {
+                            && memcmp(s->data(), str8.c_str(), str8Len) == 0) {
                         if (kDebugStringPoolNoisy) {
                             ALOGI("MATCH!");
                         }
@@ -1102,7 +1102,7 @@
 
     } else {
         if (kDebugStringPoolNoisy) {
-            ALOGI("indexOfString UTF-16: %s", String8(str, strLen).string());
+            ALOGI("indexOfString UTF-16: %s", String8(str, strLen).c_str());
         }
 
         if (mHeader->flags&ResStringPool_header::SORTED_FLAG) {
@@ -1120,7 +1120,7 @@
                 int c = s.has_value() ? strzcmp16(s->data(), s->size(), str, strLen) : -1;
                 if (kDebugStringPoolNoisy) {
                     ALOGI("Looking at %s, cmp=%d, l/mid/h=%d/%d/%d\n",
-                          String8(s->data(), s->size()).string(), c, (int)l, (int)mid, (int)h);
+                          String8(s->data(), s->size()).c_str(), c, (int)l, (int)mid, (int)h);
                 }
                 if (c == 0) {
                     if (kDebugStringPoolNoisy) {
@@ -1144,7 +1144,7 @@
                     return base::unexpected(s.error());
                 }
                 if (kDebugStringPoolNoisy) {
-                    ALOGI("Looking at %s, i=%d\n", String8(s->data(), s->size()).string(), i);
+                    ALOGI("Looking at %s, i=%d\n", String8(s->data(), s->size()).c_str(), i);
                 }
                 if (s.has_value() && strLen == s->size() &&
                         strzcmp16(s->data(), s->size(), str, strLen) == 0) {
@@ -1512,8 +1512,8 @@
 {
     String16 nsStr(ns != NULL ? ns : "");
     String16 attrStr(attr);
-    return indexOfAttribute(ns ? nsStr.string() : NULL, ns ? nsStr.size() : 0,
-                            attrStr.string(), attrStr.size());
+    return indexOfAttribute(ns ? nsStr.c_str() : NULL, ns ? nsStr.size() : 0,
+                            attrStr.c_str(), attrStr.size());
 }
 
 ssize_t ResXMLParser::indexOfAttribute(const char16_t* ns, size_t nsLen,
@@ -1531,8 +1531,8 @@
             }
             attr8 = String8(attr, attrLen);
             if (kDebugStringPoolNoisy) {
-                ALOGI("indexOfAttribute UTF8 %s (%zu) / %s (%zu)", ns8.string(), nsLen,
-                        attr8.string(), attrLen);
+                ALOGI("indexOfAttribute UTF8 %s (%zu) / %s (%zu)", ns8.c_str(), nsLen,
+                        attr8.c_str(), attrLen);
             }
             for (size_t i=0; i<N; i++) {
                 size_t curNsLen = 0, curAttrLen = 0;
@@ -1542,7 +1542,7 @@
                     ALOGI("  curNs=%s (%zu), curAttr=%s (%zu)", curNs, curNsLen, curAttr, curAttrLen);
                 }
                 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
-                        && memcmp(attr8.string(), curAttr, attrLen) == 0) {
+                        && memcmp(attr8.c_str(), curAttr, attrLen) == 0) {
                     if (ns == NULL) {
                         if (curNs == NULL) {
                             if (kDebugStringPoolNoisy) {
@@ -1552,8 +1552,8 @@
                         }
                     } else if (curNs != NULL) {
                         //printf(" --> ns=%s, curNs=%s\n",
-                        //       String8(ns).string(), String8(curNs).string());
-                        if (memcmp(ns8.string(), curNs, nsLen) == 0) {
+                        //       String8(ns).c_str(), String8(curNs).c_str());
+                        if (memcmp(ns8.c_str(), curNs, nsLen) == 0) {
                             if (kDebugStringPoolNoisy) {
                                 ALOGI("  FOUND!");
                             }
@@ -1565,8 +1565,8 @@
         } else {
             if (kDebugStringPoolNoisy) {
                 ALOGI("indexOfAttribute UTF16 %s (%zu) / %s (%zu)",
-                        String8(ns, nsLen).string(), nsLen,
-                        String8(attr, attrLen).string(), attrLen);
+                        String8(ns, nsLen).c_str(), nsLen,
+                        String8(attr, attrLen).c_str(), attrLen);
             }
             for (size_t i=0; i<N; i++) {
                 size_t curNsLen = 0, curAttrLen = 0;
@@ -1574,8 +1574,8 @@
                 const char16_t* curAttr = getAttributeName(i, &curAttrLen);
                 if (kDebugStringPoolNoisy) {
                     ALOGI("  curNs=%s (%zu), curAttr=%s (%zu)",
-                            String8(curNs, curNsLen).string(), curNsLen,
-                            String8(curAttr, curAttrLen).string(), curAttrLen);
+                            String8(curNs, curNsLen).c_str(), curNsLen,
+                            String8(curAttr, curAttrLen).c_str(), curAttrLen);
                 }
                 if (curAttr != NULL && curNsLen == nsLen && curAttrLen == attrLen
                         && (memcmp(attr, curAttr, attrLen*sizeof(char16_t)) == 0)) {
@@ -1588,7 +1588,7 @@
                         }
                     } else if (curNs != NULL) {
                         //printf(" --> ns=%s, curNs=%s\n",
-                        //       String8(ns).string(), String8(curNs).string());
+                        //       String8(ns).c_str(), String8(curNs).c_str());
                         if (memcmp(ns, curNs, nsLen*sizeof(char16_t)) == 0) {
                             if (kDebugStringPoolNoisy) {
                                 ALOGI("  FOUND!");
@@ -4412,7 +4412,7 @@
         return false;
     }
 
-    outName->package = grp->name.string();
+    outName->package = grp->name.c_str();
     outName->packageLen = grp->name.size();
     if (allowUtf8) {
         outName->type8 = UnpackOptionalString(entry.typeStr.string8(), &outName->typeLen);
@@ -4518,7 +4518,7 @@
                 outValue->dataType,
                 outValue->dataType == Res_value::TYPE_STRING ?
                     String8(UnpackOptionalString(
-                        entry.package->header->values.stringAt(outValue->data), &len)).string() :
+                        entry.package->header->values.stringAt(outValue->data), &len)).c_str() :
                     "",
                 outValue->data);
     }
@@ -4888,7 +4888,7 @@
     AutoMutex _lock2(mFilteredConfigLock);
 
     if (kDebugTableGetEntry) {
-        ALOGI("Setting parameters: %s\n", params->toString().string());
+        ALOGI("Setting parameters: %s\n", params->toString().c_str());
     }
     mParams = *params;
     for (size_t p = 0; p < mPackageGroups.size(); p++) {
@@ -4999,7 +4999,7 @@
             if (name[1] == 'i' && name[2] == 'n'
                 && name[3] == 'd' && name[4] == 'e' && name[5] == 'x'
                 && name[6] == '_') {
-                int index = atoi(String8(name + 7, nameLen - 7).string());
+                int index = atoi(String8(name + 7, nameLen - 7).c_str());
                 if (Res_CHECKID(index)) {
                     ALOGW("Array resource index: %d is too large.",
                          index);
@@ -5065,9 +5065,9 @@
 
     if (kDebugTableNoisy) {
         printf("Looking for identifier: type=%s, name=%s, package=%s\n",
-                String8(type, typeLen).string(),
-                String8(name, nameLen).string(),
-                String8(package, packageLen).string());
+                String8(type, typeLen).c_str(),
+                String8(name, nameLen).c_str(),
+                String8(package, packageLen).c_str());
     }
 
     const String16 attr("attr");
@@ -5078,9 +5078,9 @@
         const PackageGroup* group = mPackageGroups[ig];
 
         if (strzcmp16(package, packageLen,
-                      group->name.string(), group->name.size())) {
+                      group->name.c_str(), group->name.size())) {
             if (kDebugTableNoisy) {
-                printf("Skipping package group: %s\n", String8(group->name).string());
+                printf("Skipping package group: %s\n", String8(group->name).c_str());
             }
             continue;
         }
@@ -5105,8 +5105,8 @@
                     }
                     return identifier;
                 }
-            } while (strzcmp16(attr.string(), attr.size(), targetType, targetTypeLen) == 0
-                    && (targetType = attrPrivate.string())
+            } while (strzcmp16(attr.c_str(), attr.size(), targetType, targetTypeLen) == 0
+                    && (targetType = attrPrivate.c_str())
                     && (targetTypeLen = attrPrivate.size())
             );
         }
@@ -5214,19 +5214,19 @@
         *outType = *defType;
     }
     *outName = String16(p, end-p);
-    if(**outPackage == 0) {
+    if(outPackage->empty()) {
         if(outErrorMsg) {
             *outErrorMsg = "Resource package cannot be an empty string";
         }
         return false;
     }
-    if(**outType == 0) {
+    if(outType->empty()) {
         if(outErrorMsg) {
             *outErrorMsg = "Resource type cannot be an empty string";
         }
         return false;
     }
-    if(**outName == 0) {
+    if(outName->empty()) {
         if(outErrorMsg) {
             *outErrorMsg = "Resource id cannot be an empty string";
         }
@@ -5525,7 +5525,7 @@
         }
     }
 
-    //printf("Value for: %s\n", String8(s, len).string());
+    //printf("Value for: %s\n", String8(s, len).c_str());
 
     uint32_t l10nReq = ResTable_map::L10N_NOT_REQUIRED;
     uint32_t attrMin = 0x80000000, attrMax = 0x7fffffff;
@@ -5580,7 +5580,7 @@
         // be to any other type; we just need to count on the client making
         // sure the referenced type is correct.
 
-        //printf("Looking up ref: %s\n", String8(s, len).string());
+        //printf("Looking up ref: %s\n", String8(s, len).c_str());
 
         // It's a reference!
         if (len == 5 && s[1]=='n' && s[2]=='u' && s[3]=='l' && s[4]=='l') {
@@ -5620,8 +5620,8 @@
             }
 
             uint32_t specFlags = 0;
-            uint32_t rid = identifierForName(name.string(), name.size(), type.string(),
-                    type.size(), package.string(), package.size(), &specFlags);
+            uint32_t rid = identifierForName(name.c_str(), name.size(), type.c_str(),
+                    type.size(), package.c_str(), package.size(), &specFlags);
             if (rid != 0) {
                 if (enforcePrivate) {
                     if (accessor == NULL || accessor->getAssetsPackage() != package) {
@@ -5640,8 +5640,8 @@
                         Res_GETTYPE(rid), Res_GETENTRY(rid));
                     if (kDebugTableNoisy) {
                         ALOGI("Incl %s:%s/%s: 0x%08x\n",
-                                String8(package).string(), String8(type).string(),
-                                String8(name).string(), rid);
+                                String8(package).c_str(), String8(type).c_str(),
+                                String8(name).c_str(), rid);
                     }
                 }
 
@@ -5659,8 +5659,8 @@
                 if (rid != 0) {
                     if (kDebugTableNoisy) {
                         ALOGI("Pckg %s:%s/%s: 0x%08x\n",
-                                String8(package).string(), String8(type).string(),
-                                String8(name).string(), rid);
+                                String8(package).c_str(), String8(type).c_str(),
+                                String8(name).c_str(), rid);
                     }
                     uint32_t packageId = Res_GETPACKAGE(rid) + 1;
                     if (packageId == 0x00) {
@@ -5749,7 +5749,7 @@
                 }
             } else {
                 outValue->data = color;
-                //printf("Color input=%s, output=0x%x\n", String8(s, len).string(), color);
+                //printf("Color input=%s, output=0x%x\n", String8(s, len).c_str(), color);
                 return true;
             }
         } else {
@@ -5761,8 +5761,8 @@
                 #if 0
                 fprintf(stderr, "%s: Color ID %s value %s is not valid\n",
                         "Resource File", //(const char*)in->getPrintableSource(),
-                        String8(*curTag).string(),
-                        String8(s, len).string());
+                        String8(*curTag).c_str(),
+                        String8(s, len).c_str());
                 #endif
                 return false;
             }
@@ -5776,7 +5776,7 @@
         // be to any other type; we just need to count on the client making
         // sure the referenced type is correct.
 
-        //printf("Looking up attr: %s\n", String8(s, len).string());
+        //printf("Looking up attr: %s\n", String8(s, len).c_str());
 
         static const String16 attr16("attr");
         String16 package, type, name;
@@ -5789,13 +5789,13 @@
         }
 
         //printf("Pkg: %s, Type: %s, Name: %s\n",
-        //       String8(package).string(), String8(type).string(),
-        //       String8(name).string());
+        //       String8(package).c_str(), String8(type).c_str(),
+        //       String8(name).c_str());
         uint32_t specFlags = 0;
         uint32_t rid =
-            identifierForName(name.string(), name.size(),
-                              type.string(), type.size(),
-                              package.string(), package.size(), &specFlags);
+            identifierForName(name.c_str(), name.size(),
+                              type.c_str(), type.size(),
+                              package.c_str(), package.size(), &specFlags);
         if (rid != 0) {
             if (enforcePrivate) {
                 if ((specFlags&ResTable_typeSpec::SPEC_PUBLIC) == 0) {
@@ -5953,8 +5953,8 @@
                     if (getResourceName(bag->map.name.ident, false, &rname)) {
                         #if 0
                         printf("Matching %s against %s (0x%08x)\n",
-                               String8(s, len).string(),
-                               String8(rname.name, rname.nameLen).string(),
+                               String8(s, len).c_str(),
+                               String8(rname.name, rname.nameLen).c_str(),
                                bag->map.name.ident);
                         #endif
                         if (strzcmp16(s, len, rname.name, rname.nameLen) == 0) {
@@ -5997,7 +5997,7 @@
                 while (pos < end && *pos != '|') {
                     pos++;
                 }
-                //printf("Looking for: %s\n", String8(start, pos-start).string());
+                //printf("Looking for: %s\n", String8(start, pos-start).c_str());
                 const bag_entry* bagi = bag;
                 ssize_t i;
                 for (i=0; i<cnt; i++, bagi++) {
@@ -6006,8 +6006,8 @@
                         if (getResourceName(bagi->map.name.ident, false, &rname)) {
                             #if 0
                             printf("Matching %s against %s (0x%08x)\n",
-                                   String8(start,pos-start).string(),
-                                   String8(rname.name, rname.nameLen).string(),
+                                   String8(start,pos-start).c_str(),
+                                   String8(rname.name, rname.nameLen).c_str(),
                                    bagi->map.name.ident);
                             #endif
                             if (strzcmp16(start, pos-start, rname.name, rname.nameLen) == 0) {
@@ -6190,13 +6190,13 @@
         if (append) {
             outString->append(tmp);
         } else {
-            outString->setTo(tmp);
+            *outString = tmp;
         }
     } else {
         if (append) {
             outString->append(String16(s, len));
         } else {
-            outString->setTo(s, len);
+            *outString = String16(s, len);
         }
     }
 
@@ -6334,7 +6334,7 @@
 }
 
 static bool compareString8AndCString(const String8& str, const char* cStr) {
-    return strcmp(str.string(), cStr) < 0;
+    return strcmp(str.c_str(), cStr) < 0;
 }
 
 void ResTable::getLocales(Vector<String8>* locales, bool includeSystemLocales,
@@ -6348,7 +6348,7 @@
         const auto endIter = locales->end();
 
         auto iter = std::lower_bound(beginIter, endIter, locale, compareString8AndCString);
-        if (iter == endIter || strcmp(iter->string(), locale) != 0) {
+        if (iter == endIter || strcmp(iter->c_str(), locale) != 0) {
             locales->insertAt(String8(locale), std::distance(beginIter, iter));
         }
     });
@@ -6940,7 +6940,7 @@
                         ResTable_config thisConfig;
                         thisConfig.copyFromDtoH(type->config);
                         ALOGI("Adding config to type %d: %s\n", type->id,
-                                thisConfig.toString().string());
+                                thisConfig.toString().c_str());
                     }
                 }
             } else {
@@ -7018,7 +7018,7 @@
         char16_t tmpName[sizeof(entry->packageName) / sizeof(char16_t)];
         strcpy16_dtoh(tmpName, entry->packageName, sizeof(entry->packageName) / sizeof(char16_t));
         if (kDebugLibNoisy) {
-            ALOGV("Found lib entry %s with id %d\n", String8(tmpName).string(),
+            ALOGV("Found lib entry %s with id %d\n", String8(tmpName).c_str(),
                     dtohl(entry->packageId));
         }
         if (packageId >= 256) {
@@ -7300,7 +7300,7 @@
                     current_res.nameLen,
                     current_res.type,
                     current_res.typeLen,
-                    targetPackageName.string(),
+                    targetPackageName.c_str(),
                     targetPackageName.size(),
                     &typeSpecFlags);
 
@@ -7398,16 +7398,16 @@
         *pOverlayCrc = dtohl(map[3]);
     }
     if (pTargetPath) {
-        pTargetPath->setTo(reinterpret_cast<const char*>(map + 4));
+        *pTargetPath = reinterpret_cast<const char*>(map + 4);
     }
     if (pOverlayPath) {
-        pOverlayPath->setTo(reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t)));
+        *pOverlayPath = reinterpret_cast<const char*>(map + 4 + 256 / sizeof(uint32_t));
     }
     return true;
 }
 
 
-#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).string())
+#define CHAR16_TO_CSTR(c16, len) (String8(String16(c16,len)).c_str())
 
 #define CHAR16_ARRAY_EQ(constant, var, len) \
         (((len) == (sizeof(constant)/sizeof((constant)[0]))) && (0 == memcmp((var), (constant), (len))))
@@ -7502,13 +7502,13 @@
         const char* str8 = UnpackOptionalString(pkg->header->values.string8At(
                 value.data), &len);
         if (str8 != NULL) {
-            printf("(string8) \"%s\"\n", normalizeForOutput(str8).string());
+            printf("(string8) \"%s\"\n", normalizeForOutput(str8).c_str());
         } else {
             const char16_t* str16 = UnpackOptionalString(pkg->header->values.stringAt(
                     value.data), &len);
             if (str16 != NULL) {
                 printf("(string16) \"%s\"\n",
-                    normalizeForOutput(String8(str16, len).string()).string());
+                    normalizeForOutput(String8(str16, len).c_str()).c_str());
             } else {
                 printf("(string) null\n");
             }
@@ -7549,7 +7549,7 @@
         const PackageGroup* pg = mPackageGroups[pgIndex];
         printf("Package Group %d id=0x%02x packageCount=%d name=%s\n",
                 (int)pgIndex, pg->id, (int)pg->packages.size(),
-                String8(pg->name).string());
+                String8(pg->name).c_str());
 
         const KeyedVector<String16, uint8_t>& refEntries = pg->dynamicRefTable.entries();
         const size_t refEntryCount = refEntries.size();
@@ -7558,7 +7558,7 @@
             for (size_t refIndex = 0; refIndex < refEntryCount; refIndex++) {
                 printf("    0x%02x -> %s\n",
                         refEntries.valueAt(refIndex),
-                        String8(refEntries.keyAt(refIndex)).string());
+                        String8(refEntries.keyAt(refIndex)).c_str());
             }
             printf("\n");
         }
@@ -7584,7 +7584,7 @@
                 strcpy16_dtoh(tmpName, pkg->package->name,
                               sizeof(pkg->package->name)/sizeof(pkg->package->name[0]));
                 printf("  Package %d id=0x%02x name=%s\n", (int)pkgIndex,
-                        pkg->package->id, String8(tmpName).string());
+                        pkg->package->id, String8(tmpName).c_str());
             }
 
             for (size_t typeIndex = 0; typeIndex < pg->types.size(); typeIndex++) {
@@ -7626,7 +7626,7 @@
                             printf("      spec resource 0x%08x %s:%s/%s: flags=0x%08x\n",
                                 resID,
                                 CHAR16_TO_CSTR(resName.package, resName.packageLen),
-                                type8.string(), name8.string(),
+                                type8.c_str(), name8.c_str(),
                                 dtohl(typeConfigs->typeSpecFlags[entryIndex]));
                         } else {
                             printf("      INVALID TYPE CONFIG FOR RESOURCE 0x%08x\n", resID);
@@ -7647,7 +7647,7 @@
 
                     String8 configStr = thisConfig.toString();
                     printf("      config %s", configStr.size() > 0
-                            ? configStr.string() : "(default)");
+                            ? configStr.c_str() : "(default)");
                     if (type->flags != 0u) {
                         printf(" flags=0x%02x", type->flags);
                         if (type->flags & ResTable_type::FLAG_SPARSE) {
@@ -7712,7 +7712,7 @@
                             }
                             printf("        resource 0x%08x %s:%s/%s: ", resID,
                                     CHAR16_TO_CSTR(resName.package, resName.packageLen),
-                                    type8.string(), name8.string());
+                                    type8.c_str(), name8.c_str());
                         } else {
                             printf("        INVALID RESOURCE 0x%08x: ", resID);
                         }
diff --git a/libs/androidfw/include/androidfw/Asset.h b/libs/androidfw/include/androidfw/Asset.h
index 19febcd..f3776b5 100644
--- a/libs/androidfw/include/androidfw/Asset.h
+++ b/libs/androidfw/include/androidfw/Asset.h
@@ -135,7 +135,7 @@
      * This is NOT intended to be used for anything except debug output.
      * DO NOT try to parse this or use it to open a file.
      */
-    const char* getAssetSource(void) const { return mAssetSource.string(); }
+    const char* getAssetSource(void) const { return mAssetSource.c_str(); }
 
     /*
      * Create the asset from a file descriptor.
diff --git a/libs/androidfw/include/androidfw/ConfigDescription.h b/libs/androidfw/include/androidfw/ConfigDescription.h
index 61d10cd..1701f1b 100644
--- a/libs/androidfw/include/androidfw/ConfigDescription.h
+++ b/libs/androidfw/include/androidfw/ConfigDescription.h
@@ -207,7 +207,7 @@
 
 inline ::std::ostream& operator<<(::std::ostream& out,
                                   const ConfigDescription& o) {
-  return out << o.toString().string();
+  return out << o.toString().c_str();
 }
 
 }  // namespace android
diff --git a/libs/androidfw/include_pathutils/androidfw/PathUtils.h b/libs/androidfw/include_pathutils/androidfw/PathUtils.h
new file mode 100644
index 0000000..4debe8d
--- /dev/null
+++ b/libs/androidfw/include_pathutils/androidfw/PathUtils.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2023 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.
+ */
+
+#pragma once
+
+#include <utils/String8.h>
+
+/* This library contains path manipulation functions that are used only by androidfw and aapt.
+ * When it's possible, migrate all uses to std::filesystem::path.
+ */
+
+namespace android {
+
+/**
+ * Get just the filename component.
+ *
+ * DEPRECATED: use std::filesystem::path::filename
+ *
+ * "/tmp/foo/bar.c" --> "bar.c"
+ */
+String8 getPathLeaf(const String8& str);
+
+/**
+ * Remove the last (file name) component, leaving just the directory
+ * name.
+ *
+ * DEPRECATED: use std::filesystem::path::parent_path
+ *
+ * "/tmp/foo/bar.c" --> "/tmp/foo"
+ * "/tmp" --> "" // ????? shouldn't this be "/" ???? XXX
+ * "bar.c" --> ""
+ */
+String8 getPathDir(const String8& str);
+
+/**
+ * Return the filename extension.  This is the last '.' and any number
+ * of characters that follow it.  The '.' is included in case we
+ * decide to expand our definition of what constitutes an extension.
+ *
+ * DEPRECATED: use std::filesystem::path::extension
+ *
+ * "/tmp/foo/bar.c" --> ".c"
+ * "/tmp" --> ""
+ * "/tmp/foo.bar/baz" --> ""
+ * "foo.jpeg" --> ".jpeg"
+ * "foo." --> ""
+ */
+String8 getPathExtension(const String8& str);
+
+/**
+ * Return the path without the extension.  Rules for what constitutes
+ * an extension are described in the comment for getPathExtension().
+ *
+ * DEPRECATED: use std::filesystem::path::stem and std::filesystem::path::parent_path
+ *
+ * "/tmp/foo/bar.c" --> "/tmp/foo/bar"
+ */
+String8 getBasePath(const String8& str);
+
+/**
+ * Add a component to the pathname.  We guarantee that there is
+ * exactly one path separator between the old path and the new.
+ * If there is no existing name, we just copy the new name in.
+ *
+ * DEPRECATED: use std::filesystem::path::operator/=
+ *
+ * If leaf is a fully qualified path (i.e. starts with '/', it
+ * replaces whatever was there before.
+ */
+String8& appendPath(String8& str, const char* leaf);
+inline String8& appendPath(String8& str, const String8& leaf) {
+    return appendPath(str, leaf.c_str());
+}
+
+/**
+ * Like appendPath(), but does not affect this string.  Returns a new one instead.
+ *
+ * DEPRECATED: use std::filesystem::operator/
+ */
+inline String8 appendPathCopy(String8 str, const char* leaf) { return appendPath(str, leaf); }
+inline String8 appendPathCopy(String8 str, const String8& leaf) {
+    return appendPath(str, leaf.c_str());
+}
+
+} // namespace android
diff --git a/libs/androidfw/tests/BackupData_test.cpp b/libs/androidfw/tests/BackupData_test.cpp
index e25b616..7d3a341 100644
--- a/libs/androidfw/tests/BackupData_test.cpp
+++ b/libs/androidfw/tests/BackupData_test.cpp
@@ -56,10 +56,10 @@
         mFilename.append(m_external_storage);
         mFilename.append(TEST_FILENAME);
 
-        ::unlink(mFilename.string());
-        int fd = ::open(mFilename.string(), O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
+        ::unlink(mFilename.c_str());
+        int fd = ::open(mFilename.c_str(), O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
         if (fd < 0) {
-            FAIL() << "Couldn't create " << mFilename.string() << " for writing";
+            FAIL() << "Couldn't create " << mFilename.c_str() << " for writing";
         }
         mKey1 = String8(KEY1);
         mKey2 = String8(KEY2);
@@ -72,7 +72,7 @@
 };
 
 TEST_F(BackupDataTest, WriteAndReadSingle) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
 
   EXPECT_EQ(NO_ERROR, writer->WriteEntityHeader(mKey1, sizeof(DATA1)))
@@ -81,7 +81,7 @@
           << "WriteEntityData returned an error";
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
   EXPECT_EQ(NO_ERROR, reader->Status())
           << "Reader ctor failed";
@@ -114,7 +114,7 @@
 }
 
 TEST_F(BackupDataTest, WriteAndReadMultiple) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, sizeof(DATA1));
   writer->WriteEntityData(DATA1, sizeof(DATA1));
@@ -122,7 +122,7 @@
   writer->WriteEntityData(DATA2, sizeof(DATA2));
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -162,7 +162,7 @@
 }
 
 TEST_F(BackupDataTest, SkipEntity) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, sizeof(DATA1));
   writer->WriteEntityData(DATA1, sizeof(DATA1));
@@ -172,7 +172,7 @@
   writer->WriteEntityData(DATA3, sizeof(DATA3));
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -217,14 +217,14 @@
 }
 
 TEST_F(BackupDataTest, DeleteEntity) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, sizeof(DATA1));
   writer->WriteEntityData(DATA1, sizeof(DATA1));
   writer->WriteEntityHeader(mKey2, -1);
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -256,7 +256,7 @@
 }
 
 TEST_F(BackupDataTest, EneityAfterDelete) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, sizeof(DATA1));
   writer->WriteEntityData(DATA1, sizeof(DATA1));
@@ -265,7 +265,7 @@
   writer->WriteEntityData(DATA3, sizeof(DATA3));
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -317,7 +317,7 @@
 }
 
 TEST_F(BackupDataTest, OnlyDeleteEntities) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, -1);
   writer->WriteEntityHeader(mKey2, -1);
@@ -325,7 +325,7 @@
   writer->WriteEntityHeader(mKey4, -1);
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
@@ -385,13 +385,13 @@
 }
 
 TEST_F(BackupDataTest, ReadDeletedEntityData) {
-  int fd = ::open(mFilename.string(), O_WRONLY);
+  int fd = ::open(mFilename.c_str(), O_WRONLY);
   BackupDataWriter* writer = new BackupDataWriter(fd);
   writer->WriteEntityHeader(mKey1, -1);
   writer->WriteEntityHeader(mKey2, -1);
 
   ::close(fd);
-  fd = ::open(mFilename.string(), O_RDONLY);
+  fd = ::open(mFilename.c_str(), O_RDONLY);
   BackupDataReader* reader = new BackupDataReader(fd);
 
   bool done;
diff --git a/libs/androidfw/tests/CommonHelpers.cpp b/libs/androidfw/tests/CommonHelpers.cpp
index 3396729..10138de 100644
--- a/libs/androidfw/tests/CommonHelpers.cpp
+++ b/libs/androidfw/tests/CommonHelpers.cpp
@@ -60,7 +60,7 @@
 std::string GetStringFromPool(const ResStringPool* pool, uint32_t idx) {
   auto str = pool->string8ObjectAt(idx);
   CHECK(str.has_value()) << "failed to find string entry";
-  return std::string(str->string(), str->length());
+  return std::string(str->c_str(), str->length());
 }
 
 }  // namespace android
diff --git a/libs/androidfw/tests/ConfigDescription_test.cpp b/libs/androidfw/tests/ConfigDescription_test.cpp
index ce7f805..7270357 100644
--- a/libs/androidfw/tests/ConfigDescription_test.cpp
+++ b/libs/androidfw/tests/ConfigDescription_test.cpp
@@ -50,10 +50,10 @@
 TEST(ConfigDescriptionTest, ParseBasicQualifiers) {
   ConfigDescription config;
   EXPECT_TRUE(TestParse("", &config));
-  EXPECT_EQ(std::string(""), config.toString().string());
+  EXPECT_EQ(std::string(""), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("fr-land", &config));
-  EXPECT_EQ(std::string("fr-land"), config.toString().string());
+  EXPECT_EQ(std::string("fr-land"), config.toString().c_str());
 
   EXPECT_TRUE(
       TestParse("mcc310-pl-sw720dp-normal-long-port-night-"
@@ -61,22 +61,22 @@
                 &config));
   EXPECT_EQ(std::string("mcc310-pl-sw720dp-normal-long-port-night-"
                         "xhdpi-keyssoft-qwerty-navexposed-nonav-v13"),
-            config.toString().string());
+            config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, ParseLocales) {
   ConfigDescription config;
   EXPECT_TRUE(TestParse("en-rUS", &config));
-  EXPECT_EQ(std::string("en-rUS"), config.toString().string());
+  EXPECT_EQ(std::string("en-rUS"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, ParseQualifierAddedInApi13) {
   ConfigDescription config;
   EXPECT_TRUE(TestParse("sw600dp", &config));
-  EXPECT_EQ(std::string("sw600dp-v13"), config.toString().string());
+  EXPECT_EQ(std::string("sw600dp-v13"), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("sw600dp-v8", &config));
-  EXPECT_EQ(std::string("sw600dp-v13"), config.toString().string());
+  EXPECT_EQ(std::string("sw600dp-v13"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, ParseCarAttribute) {
@@ -91,13 +91,13 @@
   EXPECT_EQ(android::ResTable_config::SCREENROUND_YES,
             config.screenLayout2 & android::ResTable_config::MASK_SCREENROUND);
   EXPECT_EQ(SDK_MARSHMALLOW, config.sdkVersion);
-  EXPECT_EQ(std::string("round-v23"), config.toString().string());
+  EXPECT_EQ(std::string("round-v23"), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("notround", &config));
   EXPECT_EQ(android::ResTable_config::SCREENROUND_NO,
             config.screenLayout2 & android::ResTable_config::MASK_SCREENROUND);
   EXPECT_EQ(SDK_MARSHMALLOW, config.sdkVersion);
-  EXPECT_EQ(std::string("notround-v23"), config.toString().string());
+  EXPECT_EQ(std::string("notround-v23"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, TestWideColorGamutQualifier) {
@@ -106,13 +106,13 @@
   EXPECT_EQ(android::ResTable_config::WIDE_COLOR_GAMUT_YES,
             config.colorMode & android::ResTable_config::MASK_WIDE_COLOR_GAMUT);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("widecg-v26"), config.toString().string());
+  EXPECT_EQ(std::string("widecg-v26"), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("nowidecg", &config));
   EXPECT_EQ(android::ResTable_config::WIDE_COLOR_GAMUT_NO,
             config.colorMode & android::ResTable_config::MASK_WIDE_COLOR_GAMUT);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("nowidecg-v26"), config.toString().string());
+  EXPECT_EQ(std::string("nowidecg-v26"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, TestHdrQualifier) {
@@ -121,13 +121,13 @@
   EXPECT_EQ(android::ResTable_config::HDR_YES,
             config.colorMode & android::ResTable_config::MASK_HDR);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("highdr-v26"), config.toString().string());
+  EXPECT_EQ(std::string("highdr-v26"), config.toString().c_str());
 
   EXPECT_TRUE(TestParse("lowdr", &config));
   EXPECT_EQ(android::ResTable_config::HDR_NO,
             config.colorMode & android::ResTable_config::MASK_HDR);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("lowdr-v26"), config.toString().string());
+  EXPECT_EQ(std::string("lowdr-v26"), config.toString().c_str());
 }
 
 TEST(ConfigDescriptionTest, ParseVrAttribute) {
@@ -135,7 +135,7 @@
   EXPECT_TRUE(TestParse("vrheadset", &config));
   EXPECT_EQ(android::ResTable_config::UI_MODE_TYPE_VR_HEADSET, config.uiMode);
   EXPECT_EQ(SDK_O, config.sdkVersion);
-  EXPECT_EQ(std::string("vrheadset-v26"), config.toString().string());
+  EXPECT_EQ(std::string("vrheadset-v26"), config.toString().c_str());
 }
 
 static inline ConfigDescription ParseConfigOrDie(const android::StringPiece& str) {
diff --git a/libs/androidfw/tests/ObbFile_test.cpp b/libs/androidfw/tests/ObbFile_test.cpp
index 1151121..ba818c4 100644
--- a/libs/androidfw/tests/ObbFile_test.cpp
+++ b/libs/androidfw/tests/ObbFile_test.cpp
@@ -43,9 +43,9 @@
         mFileName.append(externalStorage);
         mFileName.append(TEST_FILENAME);
 
-        int fd = ::open(mFileName.string(), O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
+        int fd = ::open(mFileName.c_str(), O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
         if (fd < 0) {
-            FAIL() << "Couldn't create " << mFileName.string() << " for tests";
+            FAIL() << "Couldn't create " << mFileName.c_str() << " for tests";
         }
     }
 
@@ -69,17 +69,17 @@
     EXPECT_TRUE(mObbFile->setSalt(salt, SALT_SIZE))
             << "Salt should be successfully set";
 
-    EXPECT_TRUE(mObbFile->writeTo(mFileName.string()))
+    EXPECT_TRUE(mObbFile->writeTo(mFileName.c_str()))
             << "couldn't write to fake .obb file";
 
     mObbFile = new ObbFile();
 
-    EXPECT_TRUE(mObbFile->readFrom(mFileName.string()))
+    EXPECT_TRUE(mObbFile->readFrom(mFileName.c_str()))
             << "couldn't read from fake .obb file";
 
     EXPECT_EQ(versionNum, mObbFile->getVersion())
             << "version didn't come out the same as it went in";
-    const char* currentPackageName = mObbFile->getPackageName().string();
+    const char* currentPackageName = mObbFile->getPackageName().c_str();
     EXPECT_STREQ(packageName, currentPackageName)
             << "package name didn't come out the same as it went in";
 
diff --git a/libs/androidfw/tests/ResTable_test.cpp b/libs/androidfw/tests/ResTable_test.cpp
index 9aeb00c..dc6dea9 100644
--- a/libs/androidfw/tests/ResTable_test.cpp
+++ b/libs/androidfw/tests/ResTable_test.cpp
@@ -57,7 +57,7 @@
   String16 name(u"com.android.sparse:integer/foo_9");
   uint32_t flags;
   uint32_t resid =
-      table.identifierForName(name.string(), name.size(), nullptr, 0, nullptr, 0, &flags);
+      table.identifierForName(name.c_str(), name.size(), nullptr, 0, nullptr, 0, &flags);
   ASSERT_NE(0u, resid);
 
   Res_value val;
@@ -91,8 +91,8 @@
   String16 defPackage("com.android.basic");
   String16 testName("@string/test1");
   uint32_t resID =
-      table.identifierForName(testName.string(), testName.size(), 0, 0,
-                              defPackage.string(), defPackage.size());
+      table.identifierForName(testName.c_str(), testName.size(), 0, 0,
+                              defPackage.c_str(), defPackage.size());
   ASSERT_NE(uint32_t(0x00000000), resID);
   ASSERT_EQ(basic::R::string::test1, resID);
 }
diff --git a/libs/androidfw/tests/Split_test.cpp b/libs/androidfw/tests/Split_test.cpp
index 2c242db..3d88577 100644
--- a/libs/androidfw/tests/Split_test.cpp
+++ b/libs/androidfw/tests/Split_test.cpp
@@ -261,8 +261,8 @@
   const String16 package("com.android.basic");
   ASSERT_EQ(
       R::string::test3,
-      table.identifierForName(name.string(), name.size(), type.string(),
-                              type.size(), package.string(), package.size()));
+      table.identifierForName(name.c_str(), name.size(), type.c_str(),
+                              type.size(), package.c_str(), package.size()));
 }
 
 }  // namespace
diff --git a/libs/androidfw/tests/TestHelpers.cpp b/libs/androidfw/tests/TestHelpers.cpp
index 10c0a4f..c6f657c 100644
--- a/libs/androidfw/tests/TestHelpers.cpp
+++ b/libs/androidfw/tests/TestHelpers.cpp
@@ -79,9 +79,9 @@
   }
 
   if (String8(expected_str) != *actual_str) {
-    return AssertionFailure() << actual_str->string();
+    return AssertionFailure() << actual_str->c_str();
   }
-  return AssertionSuccess() << actual_str->string();
+  return AssertionSuccess() << actual_str->c_str();
 }
 
 }  // namespace android
diff --git a/libs/hwui/OWNERS b/libs/hwui/OWNERS
index bb93e66..6ca991d 100644
--- a/libs/hwui/OWNERS
+++ b/libs/hwui/OWNERS
@@ -1,3 +1,5 @@
+# Bug component: 1075005
+
 alecmouri@google.com
 djsollen@google.com
 jreck@google.com
diff --git a/libs/hwui/RenderNode.h b/libs/hwui/RenderNode.h
index da04762..208dc3e 100644
--- a/libs/hwui/RenderNode.h
+++ b/libs/hwui/RenderNode.h
@@ -115,15 +115,15 @@
         return mDisplayList.containsProjectionReceiver();
     }
 
-    const char* getName() const { return mName.string(); }
+    const char* getName() const { return mName.c_str(); }
 
     void setName(const char* name) {
         if (name) {
             const char* lastPeriod = strrchr(name, '.');
             if (lastPeriod) {
-                mName.setTo(lastPeriod + 1);
+                mName = (lastPeriod + 1);
             } else {
-                mName.setTo(name);
+                mName = name;
             }
         }
     }
diff --git a/libs/hwui/pipeline/skia/SkiaPipeline.cpp b/libs/hwui/pipeline/skia/SkiaPipeline.cpp
index bc386fe..c9bb73e 100644
--- a/libs/hwui/pipeline/skia/SkiaPipeline.cpp
+++ b/libs/hwui/pipeline/skia/SkiaPipeline.cpp
@@ -189,7 +189,7 @@
             String8 cachesOutput;
             mRenderThread.cacheManager().dumpMemoryUsage(cachesOutput,
                                                          &mRenderThread.renderState());
-            ALOGE("%s", cachesOutput.string());
+            ALOGE("%s", cachesOutput.c_str());
             if (errorHandler) {
                 std::ostringstream err;
                 err << "Unable to create layer for " << node->getName();
diff --git a/libs/hwui/renderthread/RenderThread.cpp b/libs/hwui/renderthread/RenderThread.cpp
index 01b956c..7952e70 100644
--- a/libs/hwui/renderthread/RenderThread.cpp
+++ b/libs/hwui/renderthread/RenderThread.cpp
@@ -345,7 +345,7 @@
 
     String8 cachesOutput;
     mCacheManager->dumpMemoryUsage(cachesOutput, mRenderState);
-    dprintf(fd, "\nPipeline=%s\n%s\n", pipelineToString(), cachesOutput.string());
+    dprintf(fd, "\nPipeline=%s\n%s\n", pipelineToString(), cachesOutput.c_str());
 }
 
 void RenderThread::getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage) {
diff --git a/libs/hwui/utils/LinearAllocator.cpp b/libs/hwui/utils/LinearAllocator.cpp
index 8baa4b77..eab888e 100644
--- a/libs/hwui/utils/LinearAllocator.cpp
+++ b/libs/hwui/utils/LinearAllocator.cpp
@@ -31,15 +31,11 @@
 #include <utils/Log.h>
 #include <utils/Macros.h>
 
-// The ideal size of a page allocation (these need to be multiples of 8)
-#define INITIAL_PAGE_SIZE ((size_t)512)  // 512b
-#define MAX_PAGE_SIZE ((size_t)131072)   // 128kb
-
 // The maximum amount of wasted space we can have per page
 // Allocations exceeding this will have their own dedicated page
 // If this is too low, we will malloc too much
 // Too high, and we may waste too much space
-// Must be smaller than INITIAL_PAGE_SIZE
+// Must be smaller than kInitialPageSize
 #define MAX_WASTE_RATIO (0.5f)
 
 #if LOG_NDEBUG
@@ -75,6 +71,10 @@
 namespace android {
 namespace uirenderer {
 
+// The ideal size of a page allocation (these need to be multiples of 8)
+static constexpr size_t kInitialPageSize = 512;  // 512b
+static constexpr size_t kMaxPageSize = 131072;   // 128kb
+
 class LinearAllocator::Page {
 public:
     Page* next() { return mNextPage; }
@@ -94,8 +94,8 @@
 };
 
 LinearAllocator::LinearAllocator()
-        : mPageSize(INITIAL_PAGE_SIZE)
-        , mMaxAllocSize(INITIAL_PAGE_SIZE * MAX_WASTE_RATIO)
+        : mPageSize(kInitialPageSize)
+        , mMaxAllocSize(kInitialPageSize * MAX_WASTE_RATIO)
         , mNext(0)
         , mCurrentPage(0)
         , mPages(0)
@@ -135,8 +135,8 @@
 void LinearAllocator::ensureNext(size_t size) {
     if (fitsInCurrentPage(size)) return;
 
-    if (mCurrentPage && mPageSize < MAX_PAGE_SIZE) {
-        mPageSize = min(MAX_PAGE_SIZE, mPageSize * 2);
+    if (mCurrentPage && mPageSize < kMaxPageSize) {
+        mPageSize = min(kMaxPageSize, mPageSize * 2);
         mMaxAllocSize = mPageSize * MAX_WASTE_RATIO;
         mPageSize = ALIGN(mPageSize);
     }
diff --git a/libs/incident/src/IncidentReportArgs.cpp b/libs/incident/src/IncidentReportArgs.cpp
index d344a981..858813f 100644
--- a/libs/incident/src/IncidentReportArgs.cpp
+++ b/libs/incident/src/IncidentReportArgs.cpp
@@ -152,8 +152,8 @@
     }
     mPrivacyPolicy = privacyPolicy;
 
-    mReceiverPkg = String8(in->readString16()).string();
-    mReceiverCls = String8(in->readString16()).string();
+    mReceiverPkg = String8(in->readString16()).c_str();
+    mReceiverCls = String8(in->readString16()).c_str();
 
     int32_t gzip;
     err = in->readInt32(&gzip);
diff --git a/libs/protoutil/Android.bp b/libs/protoutil/Android.bp
index 128be3c..28856c8 100644
--- a/libs/protoutil/Android.bp
+++ b/libs/protoutil/Android.bp
@@ -80,6 +80,10 @@
         "libgmock",
     ],
 
+    test_suites: [
+        "general-tests",
+    ],
+
     proto: {
         type: "full",
     },
diff --git a/libs/protoutil/AndroidTest.xml b/libs/protoutil/AndroidTest.xml
deleted file mode 100644
index 46d418e..0000000
--- a/libs/protoutil/AndroidTest.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 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.
--->
-<configuration description="Config for libprotoutil_test">
-    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
-        <option name="cleanup" value="true" />
-        <option name="push" value="libprotoutil_test->/data/nativetest/libprotoutil_test" />
-    </target_preparer>
-    <option name="test-suite-tag" value="apct" />
-    <test class="com.android.tradefed.testtype.GTest" >
-        <option name="native-test-device-path" value="/data/nativetest" />
-        <option name="module-name" value="libprotoutil_test" />
-    </test>
-</configuration>
diff --git a/libs/protoutil/TEST_MAPPING b/libs/protoutil/TEST_MAPPING
new file mode 100644
index 0000000..b10dd9b
--- /dev/null
+++ b/libs/protoutil/TEST_MAPPING
@@ -0,0 +1,12 @@
+{
+  "presubmit": [
+    {
+      "name": "libprotoutil_test"
+    }
+  ],
+  "hwasan-postsubmit": [
+    {
+      "name": "libprotoutil_test"
+    }
+  ]
+}
diff --git a/libs/protoutil/include/android/util/ProtoOutputStream.h b/libs/protoutil/include/android/util/ProtoOutputStream.h
index f4a358d..1bfb874 100644
--- a/libs/protoutil/include/android/util/ProtoOutputStream.h
+++ b/libs/protoutil/include/android/util/ProtoOutputStream.h
@@ -102,7 +102,7 @@
     bool write(uint64_t fieldId, long val);
     bool write(uint64_t fieldId, long long val);
     bool write(uint64_t fieldId, bool val);
-    bool write(uint64_t fieldId, std::string val);
+    bool write(uint64_t fieldId, std::string_view val);
     bool write(uint64_t fieldId, const char* val, size_t size);
 
     /**
diff --git a/libs/protoutil/src/EncodedBuffer.cpp b/libs/protoutil/src/EncodedBuffer.cpp
index 96b54c6..afb54a6 100644
--- a/libs/protoutil/src/EncodedBuffer.cpp
+++ b/libs/protoutil/src/EncodedBuffer.cpp
@@ -17,6 +17,7 @@
 
 #include <stdlib.h>
 #include <sys/mman.h>
+#include <unistd.h>
 
 #include <android/util/EncodedBuffer.h>
 #include <android/util/protobuf.h>
@@ -25,7 +26,8 @@
 namespace android {
 namespace util {
 
-const size_t BUFFER_SIZE = 8 * 1024; // 8 KB
+constexpr size_t BUFFER_SIZE = 8 * 1024; // 8 KB
+const size_t kPageSize = getpagesize();
 
 EncodedBuffer::Pointer::Pointer() : Pointer(BUFFER_SIZE)
 {
@@ -92,7 +94,7 @@
 {
     // Align chunkSize to memory page size
     chunkSize = chunkSize == 0 ? BUFFER_SIZE : chunkSize;
-    mChunkSize = (chunkSize / PAGE_SIZE + ((chunkSize % PAGE_SIZE == 0) ? 0 : 1)) * PAGE_SIZE;
+    mChunkSize = (chunkSize + (kPageSize - 1)) & ~(kPageSize - 1);
     mWp = Pointer(mChunkSize);
     mEp = Pointer(mChunkSize);
 }
diff --git a/libs/protoutil/src/ProtoOutputStream.cpp b/libs/protoutil/src/ProtoOutputStream.cpp
index fcf82ee..a44a1b2 100644
--- a/libs/protoutil/src/ProtoOutputStream.cpp
+++ b/libs/protoutil/src/ProtoOutputStream.cpp
@@ -170,13 +170,13 @@
 }
 
 bool
-ProtoOutputStream::write(uint64_t fieldId, std::string val)
+ProtoOutputStream::write(uint64_t fieldId, std::string_view val)
 {
     if (mCompact) return false;
     const uint32_t id = (uint32_t)fieldId;
     switch (fieldId & FIELD_TYPE_MASK) {
         case FIELD_TYPE_STRING:
-            writeUtf8StringImpl(id, val.c_str(), val.size());
+            writeUtf8StringImpl(id, val.data(), val.size());
             return true;
         default:
             ALOGW("Field type %" PRIu64 " is not supported when writing string val.",
diff --git a/libs/protoutil/tests/EncodedBuffer_test.cpp b/libs/protoutil/tests/EncodedBuffer_test.cpp
index f895154..a0955854 100644
--- a/libs/protoutil/tests/EncodedBuffer_test.cpp
+++ b/libs/protoutil/tests/EncodedBuffer_test.cpp
@@ -15,12 +15,16 @@
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
 
+#include <unistd.h>
+
 using namespace android::util;
 using android::sp;
 
-constexpr size_t TEST_CHUNK_SIZE = 16UL;
-constexpr size_t TEST_CHUNK_HALF_SIZE = TEST_CHUNK_SIZE / 2;
-constexpr size_t TEST_CHUNK_3X_SIZE = 3 * TEST_CHUNK_SIZE;
+constexpr size_t __TEST_CHUNK_SIZE = 16UL;
+const size_t kPageSize = getpagesize();
+const size_t TEST_CHUNK_SIZE = (__TEST_CHUNK_SIZE + (kPageSize - 1)) & ~(kPageSize - 1);
+const size_t TEST_CHUNK_HALF_SIZE = TEST_CHUNK_SIZE / 2;
+const size_t TEST_CHUNK_3X_SIZE = 3 * TEST_CHUNK_SIZE;
 
 static void expectPointer(EncodedBuffer::Pointer* p, size_t pos) {
     EXPECT_EQ(p->pos(), pos);
@@ -34,13 +38,13 @@
     expectPointer(buffer->wp(), 0);
     EXPECT_EQ(buffer->currentToWrite(), TEST_CHUNK_SIZE);
     for (size_t i = 0; i < TEST_CHUNK_HALF_SIZE; i++) {
-        buffer->writeRawByte(50 + i);
+        buffer->writeRawByte(static_cast<uint8_t>(50 + i));
     }
     EXPECT_EQ(buffer->size(), TEST_CHUNK_HALF_SIZE);
     expectPointer(buffer->wp(), TEST_CHUNK_HALF_SIZE);
     EXPECT_EQ(buffer->currentToWrite(), TEST_CHUNK_HALF_SIZE);
     for (size_t i = 0; i < TEST_CHUNK_SIZE; i++) {
-        buffer->writeRawByte(80 + i);
+        buffer->writeRawByte(static_cast<uint8_t>(80 + i));
     }
     EXPECT_EQ(buffer->size(), TEST_CHUNK_SIZE + TEST_CHUNK_HALF_SIZE);
     expectPointer(buffer->wp(), TEST_CHUNK_SIZE + TEST_CHUNK_HALF_SIZE);
@@ -49,10 +53,10 @@
     // verifies the buffer's data
     expectPointer(buffer->ep(), 0);
     for (size_t i = 0; i < TEST_CHUNK_HALF_SIZE; i++) {
-        EXPECT_EQ(buffer->readRawByte(), 50 + i);
+        EXPECT_EQ(buffer->readRawByte(), static_cast<uint8_t>(50 + i));
     }
     for (size_t i = 0; i < TEST_CHUNK_SIZE; i++) {
-        EXPECT_EQ(buffer->readRawByte(), 80 + i);
+        EXPECT_EQ(buffer->readRawByte(), static_cast<uint8_t>(80 + i));
     }
 
     // clears the buffer
diff --git a/libs/services/src/os/DropBoxManager.cpp b/libs/services/src/os/DropBoxManager.cpp
index 3716e01..60bb00a 100644
--- a/libs/services/src/os/DropBoxManager.cpp
+++ b/libs/services/src/os/DropBoxManager.cpp
@@ -196,7 +196,7 @@
     vector<uint8_t> dataArg;
     dataArg.assign(data, data + size);
     Status status = service->addData(tag, dataArg, flags);
-    ALOGD("service->add returned %s", status.toString8().string());
+    ALOGD("service->add returned %s", status.toString8().c_str());
     return status;
 }
 
@@ -230,7 +230,7 @@
     android::base::unique_fd uniqueFd(fd);
     android::os::ParcelFileDescriptor parcelFd(std::move(uniqueFd));
     Status status = service->addFile(tag, parcelFd, flags);
-    ALOGD("service->add returned %s", status.toString8().string());
+    ALOGD("service->add returned %s", status.toString8().c_str());
     return status;
 }
 
diff --git a/location/Android.bp b/location/Android.bp
new file mode 100644
index 0000000..ead46e9
--- /dev/null
+++ b/location/Android.bp
@@ -0,0 +1,24 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_base_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_base_license"],
+}
+
+//location sources that will populate the new module
+filegroup {
+    name: "framework-location-nonupdatable-sources",
+    srcs: [
+        "placeholder_java/android/location/Placeholder.java",
+    ],
+}
+
+java_library {
+    name: "framework-location.stubs.module_lib",
+    srcs: [
+        ":framework-location-nonupdatable-sources",
+    ],
+    sdk_version: "core_platform",
+}
diff --git a/location/java/android/location/GnssRequest.java b/location/java/android/location/GnssRequest.java
index 9c9766f..f3a40cc 100644
--- a/location/java/android/location/GnssRequest.java
+++ b/location/java/android/location/GnssRequest.java
@@ -41,7 +41,7 @@
      *
      * <p>If true, GNSS chipset switches off duty cycling. In such a mode, no clock
      * discontinuities are expected, and when supported, carrier phase should be continuous in
-     * good signal conditions. All non-blacklisted, healthy constellations, satellites and
+     * good signal conditions. All non-denylisted, healthy constellations, satellites and
      * frequency bands that the chipset supports must be reported in this mode. The GNSS chipset
      * is allowed to consume more power in this mode. If false, GNSS chipset optimizes power via
      * duty cycling, constellations and frequency limits, etc.
@@ -138,7 +138,7 @@
          *
          * <p>If true, GNSS chipset switches off duty cycling. In such a mode, no clock
          * discontinuities are expected, and when supported, carrier phase should be continuous in
-         * good signal conditions. All non-blacklisted, healthy constellations, satellites and
+         * good signal conditions. All non-denylisted, healthy constellations, satellites and
          * frequency bands that the chipset supports must be reported in this mode. The GNSS chipset
          * is allowed to consume more power in this mode. If false, GNSS chipset optimizes power via
          * duty cycling, constellations and frequency limits, etc.
diff --git a/location/placeholder_java/android/location/Placeholder.java b/location/placeholder_java/android/location/Placeholder.java
new file mode 100644
index 0000000..f0dbce8
--- /dev/null
+++ b/location/placeholder_java/android/location/Placeholder.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2023 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.location;
+
+/**
+ * Placeholder class so new frameworks-location module isn't empty, will be removed once module is
+ * populated.
+ *
+ * @hide
+ *
+ */
+public class Placeholder {
+}
diff --git a/media/java/android/media/AudioFormat.java b/media/java/android/media/AudioFormat.java
index b8090c4..1100c54 100644
--- a/media/java/android/media/AudioFormat.java
+++ b/media/java/android/media/AudioFormat.java
@@ -1240,7 +1240,8 @@
          *    {@link AudioFormat#CHANNEL_OUT_SIDE_RIGHT}.
          *    <p> For a valid {@link AudioTrack} channel position mask,
          *    the following conditions apply:
-         *    <br> (1) at most eight channel positions may be used;
+         *    <br> (1) at most {@link AudioSystem#OUT_CHANNEL_COUNT_MAX} channel positions may be
+         *    used;
          *    <br> (2) right/left pairs should be matched.
          *    <p> For input or {@link AudioRecord}, the mask should be
          *    {@link AudioFormat#CHANNEL_IN_MONO} or
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index 1583a1b..fb712bb 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -4580,7 +4580,9 @@
             synchronized (this) {
                 while (!mQuit) {
                     final long timeToWait = timeOutTime - java.lang.System.currentTimeMillis();
-                    if (timeToWait < 0) { break; }
+                    if (timeToWait <= 0) {
+                        break;
+                    }
                     this.wait(timeToWait);
                 }
             }
diff --git a/media/java/android/media/Cea708CaptionRenderer.java b/media/java/android/media/Cea708CaptionRenderer.java
index 88912fe..efaf3d2 100644
--- a/media/java/android/media/Cea708CaptionRenderer.java
+++ b/media/java/android/media/Cea708CaptionRenderer.java
@@ -194,7 +194,7 @@
     private final StringBuffer mBuffer = new StringBuffer();
     private int mCommand = 0;
 
-    // Assign a dummy listener in order to avoid null checks.
+    // Assign a placeholder listener in order to avoid null checks.
     private DisplayListener mListener = new DisplayListener() {
         @Override
         public void emitEvent(CaptionEvent event) {
diff --git a/media/java/android/media/MediaMetadataRetriever.java b/media/java/android/media/MediaMetadataRetriever.java
index ea26185..1de0881 100644
--- a/media/java/android/media/MediaMetadataRetriever.java
+++ b/media/java/android/media/MediaMetadataRetriever.java
@@ -1155,7 +1155,7 @@
     public static final int OPTION_CLOSEST          = 0x03;
 
     /** @hide */
-    @IntDef(flag = true, prefix = { "OPTION_" }, value = {
+    @IntDef(flag = false, prefix = { "OPTION_" }, value = {
             OPTION_PREVIOUS_SYNC,
             OPTION_NEXT_SYNC,
             OPTION_CLOSEST_SYNC,
diff --git a/media/java/android/media/OWNERS b/media/java/android/media/OWNERS
index 6d6a9f8..bbe5e06 100644
--- a/media/java/android/media/OWNERS
+++ b/media/java/android/media/OWNERS
@@ -10,5 +10,8 @@
 
 per-file *Image* = file:/graphics/java/android/graphics/OWNERS
 
+per-file ExifInterface.java,ExifInterfaceUtils.java,IMediaHTTPConnection.aidl,IMediaHTTPService.aidl,JetPlayer.java,MediaDataSource.java,MediaExtractor.java,MediaHTTPConnection.java,MediaHTTPService.java,MediaPlayer.java=set noparent
+per-file ExifInterface.java,ExifInterfaceUtils.java,IMediaHTTPConnection.aidl,IMediaHTTPService.aidl,JetPlayer.java,MediaDataSource.java,MediaExtractor.java,MediaHTTPConnection.java,MediaHTTPService.java,MediaPlayer.java=file:platform/frameworks/av:/media/janitors/media_solutions_OWNERS
+
 # Haptics team also works on Ringtone
 per-file *Ringtone* = file:/services/core/java/com/android/server/vibrator/OWNERS
diff --git a/media/java/android/media/projection/OWNERS b/media/java/android/media/projection/OWNERS
index 2273f81..cc9be9c 100644
--- a/media/java/android/media/projection/OWNERS
+++ b/media/java/android/media/projection/OWNERS
@@ -1,3 +1,5 @@
+# Bug component: 1345447
+
 michaelwr@google.com
 santoscordon@google.com
 chaviw@google.com
diff --git a/media/java/android/media/tv/tuner/Tuner.java b/media/java/android/media/tv/tuner/Tuner.java
index 13f7ee6..e6bcc95 100644
--- a/media/java/android/media/tv/tuner/Tuner.java
+++ b/media/java/android/media/tv/tuner/Tuner.java
@@ -443,6 +443,12 @@
         acquireTRMSLock("shareFrontendFromTuner()");
         mFrontendLock.lock();
         try {
+            if (mFeOwnerTuner != null) {
+                // unregister self from the Frontend callback
+                mFeOwnerTuner.unregisterFrontendCallbackListener(this);
+                mFeOwnerTuner = null;
+                nativeUnshareFrontend();
+            }
             mTunerResourceManager.shareFrontend(mClientId, tuner.mClientId);
             mFeOwnerTuner = tuner;
             mFeOwnerTuner.registerFrontendCallbackListener(this);
diff --git a/media/java/android/media/voice/KeyphraseModelManager.java b/media/java/android/media/voice/KeyphraseModelManager.java
index 8ec8967..290f1ac 100644
--- a/media/java/android/media/voice/KeyphraseModelManager.java
+++ b/media/java/android/media/voice/KeyphraseModelManager.java
@@ -35,7 +35,7 @@
  * This class provides management of voice based sound recognition models. Usage of this class is
  * restricted to system or signature applications only. This allows OEMs to write apps that can
  * manage voice based sound trigger models.
- * Callers of this class are expected to have whitelist manifest permission MANAGE_VOICE_KEYPHRASES.
+ * Callers of this class are expected to have allowlist manifest permission MANAGE_VOICE_KEYPHRASES.
  * Callers of this class are expected to be the designated voice interaction service via
  * {@link Settings.Secure.VOICE_INTERACTION_SERVICE} or a bundled voice model enrollment application
  * detected by {@link android.hardware.soundtrigger.KeyphraseEnrollmentInfo}.
diff --git a/media/jni/OWNERS b/media/jni/OWNERS
index 96894d1..e12d828 100644
--- a/media/jni/OWNERS
+++ b/media/jni/OWNERS
@@ -3,3 +3,6 @@
 
 # extra for TV related files
 per-file android_media_tv_*=hgchen@google.com,quxiangfang@google.com
+
+per-file android_media_JetPlayer.cpp,android_media_MediaDataSource.cpp,android_media_MediaDataSource.h,android_media_MediaPlayer.java=set noparent
+per-file android_media_JetPlayer.cpp,android_media_MediaDataSource.cpp,android_media_MediaDataSource.h,android_media_MediaPlayer.java=file:platform/frameworks/av:/media/janitors/media_solutions_OWNERS
diff --git a/media/jni/android_media_ImageReader.cpp b/media/jni/android_media_ImageReader.cpp
index 3b93b07..f7d4825 100644
--- a/media/jni/android_media_ImageReader.cpp
+++ b/media/jni/android_media_ImageReader.cpp
@@ -617,7 +617,7 @@
                         "match the ImageReader's configured buffer format 0x%x.",
                         bufferFormat, ctx->getBufferFormat());
                 jniThrowException(env, "java/lang/UnsupportedOperationException",
-                        msg.string());
+                        msg.c_str());
                 return -1;
             }
         }
@@ -789,7 +789,7 @@
         String8 msg;
         msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
                 " must be 0", halReaderFormat, numPlanes);
-        jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
+        jniThrowException(env, "java/lang/IllegalArgumentException", msg.c_str());
         return NULL;
     }
 
@@ -854,7 +854,7 @@
         String8 msg;
         msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
                 " must be 0", halReaderFormat, numPlanes);
-        jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
+        jniThrowException(env, "java/lang/IllegalArgumentException", msg.c_str());
         return NULL;
     }
 
diff --git a/media/jni/android_media_ImageWriter.cpp b/media/jni/android_media_ImageWriter.cpp
index 2c498e5..dd1652c9 100644
--- a/media/jni/android_media_ImageWriter.cpp
+++ b/media/jni/android_media_ImageWriter.cpp
@@ -1068,7 +1068,7 @@
         String8 msg;
         msg.appendFormat("Format 0x%x is opaque, thus not writable, the number of planes (%d)"
                 " must be 0", writerFormat, numPlanes);
-        jniThrowException(env, "java/lang/IllegalArgumentException", msg.string());
+        jniThrowException(env, "java/lang/IllegalArgumentException", msg.c_str());
         return NULL;
     }
 
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index b878bcf5..27fc6ae 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -1040,7 +1040,7 @@
     CHECK(ctor != NULL);
 
     ScopedLocalRef<jstring> msgObj(
-            env, env->NewStringUTF(msg != NULL ? msg : String8::format("Error %#x", err)));
+            env, env->NewStringUTF(msg != NULL ? msg : String8::format("Error %#x", err).c_str()));
 
     // translate action code to Java equivalent
     switch (actionCode) {
@@ -2491,7 +2491,7 @@
             return;
         }
         auto cryptoInfo =
-                cryptoInfoObj ? NativeCryptoInfo{size} : NativeCryptoInfo{env, cryptoInfoObj};
+                cryptoInfoObj ? NativeCryptoInfo{env, cryptoInfoObj} : NativeCryptoInfo{size};
         if (env->ExceptionCheck()) {
             // Creation of cryptoInfo failed. Let the exception bubble up.
             return;
@@ -2912,7 +2912,7 @@
     if (mode != NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW
             && mode != NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
         jniThrowException(env, "java/lang/IllegalArgumentException",
-                          String8::format("Unrecognized mode: %d", mode));
+                          String8::format("Unrecognized mode: %d", mode).c_str());
         return;
     }
 
@@ -3320,7 +3320,8 @@
         JNIEnv *env, jobject thiz,
         jstring name, jboolean nameIsType, jboolean encoder, int pid, int uid) {
     if (name == NULL) {
-        jniThrowException(env, "java/lang/NullPointerException", NULL);
+        jniThrowException(env, "java/lang/NullPointerException",
+                          "No codec name specified");
         return;
     }
 
@@ -3336,27 +3337,27 @@
     if (err == NAME_NOT_FOUND) {
         // fail and do not try again.
         jniThrowException(env, "java/lang/IllegalArgumentException",
-                String8::format("Failed to initialize %s, error %#x (NAME_NOT_FOUND)", tmp, err));
+                String8::format("Failed to initialize %s, error %#x (NAME_NOT_FOUND)", tmp, err).c_str());
         env->ReleaseStringUTFChars(name, tmp);
         return;
     }
     if (err == NO_MEMORY) {
         throwCodecException(env, err, ACTION_CODE_TRANSIENT,
-                String8::format("Failed to initialize %s, error %#x (NO_MEMORY)", tmp, err));
+                String8::format("Failed to initialize %s, error %#x (NO_MEMORY)", tmp, err).c_str());
         env->ReleaseStringUTFChars(name, tmp);
         return;
     }
     if (err == PERMISSION_DENIED) {
         jniThrowException(env, "java/lang/SecurityException",
                 String8::format("Failed to initialize %s, error %#x (PERMISSION_DENIED)", tmp,
-                err));
+                err).c_str());
         env->ReleaseStringUTFChars(name, tmp);
         return;
     }
     if (err != OK) {
         // believed possible to try again
         jniThrowException(env, "java/io/IOException",
-                String8::format("Failed to find matching codec %s, error %#x (?)", tmp, err));
+                String8::format("Failed to find matching codec %s, error %#x (?)", tmp, err).c_str());
         env->ReleaseStringUTFChars(name, tmp);
         return;
     }
diff --git a/media/jni/android_media_MediaCrypto.cpp b/media/jni/android_media_MediaCrypto.cpp
index f491be8..5506f61 100644
--- a/media/jni/android_media_MediaCrypto.cpp
+++ b/media/jni/android_media_MediaCrypto.cpp
@@ -299,7 +299,7 @@
             std::string strerr(StrCryptoError(err));
             msg.appendFormat(": general failure (%s)", strerr.c_str());
         }
-        jniThrowException(env, "android/media/MediaCryptoException", msg.string());
+        jniThrowException(env, "android/media/MediaCryptoException", msg.c_str());
     }
 }
 
diff --git a/media/jni/android_media_MediaDescrambler.cpp b/media/jni/android_media_MediaDescrambler.cpp
index c61365a..37111c2 100644
--- a/media/jni/android_media_MediaDescrambler.cpp
+++ b/media/jni/android_media_MediaDescrambler.cpp
@@ -368,7 +368,7 @@
 
     ScopedLocalRef<jstring> msgObj(
             env, env->NewStringUTF(msg != NULL ?
-                    msg : String8::format("Error %#x", serviceSpecificError)));
+                    msg : String8::format("Error %#x", serviceSpecificError).c_str()));
 
     return (jthrowable)env->NewObject(
             clazz.get(), ctor, serviceSpecificError, msgObj.get());
diff --git a/media/jni/android_media_MediaDrm.cpp b/media/jni/android_media_MediaDrm.cpp
index b70818d..c616b84f 100644
--- a/media/jni/android_media_MediaDrm.cpp
+++ b/media/jni/android_media_MediaDrm.cpp
@@ -708,8 +708,8 @@
     jclass clazz = gFields.hashmapClassId;
     jobject hashMap = env->NewObject(clazz, gFields.hashmap.init);
     for (size_t i = 0; i < map.size(); ++i) {
-        jstring jkey = env->NewStringUTF(map.keyAt(i).string());
-        jstring jvalue = env->NewStringUTF(map.valueAt(i).string());
+        jstring jkey = env->NewStringUTF(map.keyAt(i).c_str());
+        jstring jvalue = env->NewStringUTF(map.valueAt(i).c_str());
         env->CallObjectMethod(hashMap, gFields.hashmap.put, jkey, jvalue);
         env->DeleteLocalRef(jkey);
         env->DeleteLocalRef(jvalue);
@@ -1169,7 +1169,7 @@
         jbyteArray jrequest = VectorToJByteArray(env, request);
         env->SetObjectField(keyObj, gFields.keyRequest.data, jrequest);
 
-        jstring jdefaultUrl = env->NewStringUTF(defaultUrl.string());
+        jstring jdefaultUrl = env->NewStringUTF(defaultUrl.c_str());
         env->SetObjectField(keyObj, gFields.keyRequest.defaultUrl, jdefaultUrl);
 
         switch (keyRequestType) {
@@ -1332,7 +1332,7 @@
         jbyteArray jrequest = VectorToJByteArray(env, request);
         env->SetObjectField(provisionObj, gFields.provisionRequest.data, jrequest);
 
-        jstring jdefaultUrl = env->NewStringUTF(defaultUrl.string());
+        jstring jdefaultUrl = env->NewStringUTF(defaultUrl.c_str());
         env->SetObjectField(provisionObj, gFields.provisionRequest.defaultUrl, jdefaultUrl);
     }
 
@@ -1686,7 +1686,7 @@
         return NULL;
     }
 
-    return env->NewStringUTF(value.string());
+    return env->NewStringUTF(value.c_str());
 }
 
 static jbyteArray android_media_MediaDrm_getPropertyByteArray(
diff --git a/media/jni/android_media_MediaMetadataRetriever.cpp b/media/jni/android_media_MediaMetadataRetriever.cpp
index ddc51cd..1458758 100644
--- a/media/jni/android_media_MediaMetadataRetriever.cpp
+++ b/media/jni/android_media_MediaMetadataRetriever.cpp
@@ -126,7 +126,7 @@
     tmp = NULL;
 
     // Don't let somebody trick us in to reading some random block of memory
-    if (strncmp("mem://", pathStr.string(), 6) == 0) {
+    if (strncmp("mem://", pathStr.c_str(), 6) == 0) {
         jniThrowException(
                 env, "java/lang/IllegalArgumentException", "Invalid pathname");
         return;
@@ -149,7 +149,7 @@
             env,
             retriever->setDataSource(
                 httpService,
-                pathStr.string(),
+                pathStr.c_str(),
                 headersVector.size() > 0 ? &headersVector : NULL),
 
             "java/lang/RuntimeException",
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index a548a47..febaba9 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -260,7 +260,7 @@
     status_t opStatus =
         mp->setDataSource(
                 httpService,
-                pathStr,
+                pathStr.c_str(),
                 headersVector.size() > 0? &headersVector : NULL);
 
     process_media_player_call(
@@ -1214,7 +1214,7 @@
     String8 vendorMessage;
     if (err >= ERROR_DRM_VENDOR_MIN && err <= ERROR_DRM_VENDOR_MAX) {
         vendorMessage = String8::format("DRM vendor-defined error: %d", err);
-        drmMessage = vendorMessage.string();
+        drmMessage = vendorMessage.c_str();
     }
 
     if (err == BAD_VALUE) {
@@ -1240,7 +1240,7 @@
                 msg = drmMessage;
             } else {
                 errbuf = String8::format("%s: %s", msg, drmMessage);
-                msg = errbuf.string();
+                msg = errbuf.c_str();
             }
         }
         throwDrmStateException(env, msg, err);
diff --git a/media/jni/android_media_Streams.cpp b/media/jni/android_media_Streams.cpp
index 4fd5153..dffeb89 100644
--- a/media/jni/android_media_Streams.cpp
+++ b/media/jni/android_media_Streams.cpp
@@ -38,7 +38,7 @@
 
 FileStream::FileStream(const String8 filename)
     : mPosition(0) {
-    mFile = fopen(filename.string(), "r");
+    mFile = fopen(filename.c_str(), "r");
     if (mFile == NULL) {
         return;
     }
@@ -86,7 +86,7 @@
 
     if (!piex::IsRaw(stream)) {
         // Format not supported.
-        ALOGV("Format not supported: %s", filename.string());
+        ALOGV("Format not supported: %s", filename.c_str());
         return false;
     }
 
@@ -94,7 +94,7 @@
 
     if (err != piex::Error::kOk) {
         // The input data seems to be broken.
-        ALOGV("Raw image not detected: %s (piex error code: %d)", filename.string(), (int32_t)err);
+        ALOGV("Raw image not detected: %s (piex error code: %d)", filename.c_str(), (int32_t)err);
         return false;
     }
 
diff --git a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2ManagerTest.java b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2ManagerTest.java
index 4086dec..7f4a4fe 100644
--- a/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2ManagerTest.java
+++ b/media/tests/MediaRouter/src/com/android/mediaroutertest/MediaRouter2ManagerTest.java
@@ -872,7 +872,7 @@
         CountDownLatch addedLatch = new CountDownLatch(1);
         CountDownLatch preferenceLatch = new CountDownLatch(1);
 
-        // A dummy callback is required to send route feature info.
+        // A placeholder callback is required to send route feature info.
         RouteCallback routeCallback = new RouteCallback() {};
         MediaRouter2Manager.Callback managerCallback = new MediaRouter2Manager.Callback() {
             @Override
diff --git a/mime/Android.bp b/mime/Android.bp
index a3ea65c..757862b 100644
--- a/mime/Android.bp
+++ b/mime/Android.bp
@@ -12,7 +12,6 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-
 package {
     // See: http://go/android-license-faq
     // A large-scale-change added 'default_applicable_licenses' to import
@@ -125,6 +124,6 @@
     srcs: [
         "java-res/vendor.mime.types",
     ],
-    //    strip comments            normalize whitepace       drop empty lines   prepend ? to fields that are missing it
-    cmd: "awk '{gsub(/#.*$$/,\"\"); $$1=$$1; print;}' $(in) | grep ' '         | awk '{for(i=1;i<=NF;i++) { sub(/^\\??/, \"?\", $$i); }; print}' > $(out)",
+    //    strip comments            normalize whitepace       drop empty lines           prepend ? to fields that are missing it
+    cmd: "awk '{gsub(/#.*$$/,\"\"); $$1=$$1; print;}' $(in) | (grep ' ' || echo -n '') | awk '{for(i=1;i<=NF;i++) { sub(/^\\??/, \"?\", $$i); }; print}' > $(out)",
 }
diff --git a/native/android/OWNERS b/native/android/OWNERS
index cfe9734..884f849 100644
--- a/native/android/OWNERS
+++ b/native/android/OWNERS
@@ -23,3 +23,6 @@
 per-file native_window_jni.cpp = file:/graphics/java/android/graphics/OWNERS
 per-file surface_control.cpp = file:/graphics/java/android/graphics/OWNERS
 per-file surface_texture.cpp = file:/graphics/java/android/graphics/OWNERS
+
+# PerformanceHint
+per-file performance_hint.cpp = file:/ADPF_OWNERS
diff --git a/native/android/asset_manager.cpp b/native/android/asset_manager.cpp
index 69cf804..1878716 100644
--- a/native/android/asset_manager.cpp
+++ b/native/android/asset_manager.cpp
@@ -118,7 +118,7 @@
     // the string to return and advance the iterator for next time.
     if (index < max) {
         assetDir->mCachedFileName = assetDir->mAssetDir->getFileName(index);
-        returnName = assetDir->mCachedFileName.string();
+        returnName = assetDir->mCachedFileName.c_str();
         index++;
     }
 
@@ -134,7 +134,7 @@
 const char* AAssetDir_getFileName(AAssetDir* assetDir, int index)
 {
     assetDir->mCachedFileName = assetDir->mAssetDir->getFileName(index);
-    return assetDir->mCachedFileName.string();
+    return assetDir->mCachedFileName.c_str();
 }
 
 void AAssetDir_close(AAssetDir* assetDir)
diff --git a/native/android/obb.cpp b/native/android/obb.cpp
index e990024..a14fa7e 100644
--- a/native/android/obb.cpp
+++ b/native/android/obb.cpp
@@ -42,7 +42,7 @@
 }
 
 const char* AObbInfo_getPackageName(AObbInfo* obbInfo) {
-    return obbInfo->getPackageName();
+    return obbInfo->getPackageName().c_str();
 }
 
 int32_t AObbInfo_getVersion(AObbInfo* obbInfo) {
diff --git a/native/android/sensor.cpp b/native/android/sensor.cpp
index 968de34..bb8708b 100644
--- a/native/android/sensor.cpp
+++ b/native/android/sensor.cpp
@@ -304,12 +304,12 @@
 
 const char* ASensor_getName(ASensor const* sensor) {
     RETURN_IF_SENSOR_IS_NULL(nullptr);
-    return static_cast<Sensor const*>(sensor)->getName().string();
+    return static_cast<Sensor const*>(sensor)->getName().c_str();
 }
 
 const char* ASensor_getVendor(ASensor const* sensor) {
     RETURN_IF_SENSOR_IS_NULL(nullptr);
-    return static_cast<Sensor const*>(sensor)->getVendor().string();
+    return static_cast<Sensor const*>(sensor)->getVendor().c_str();
 }
 
 int ASensor_getType(ASensor const* sensor) {
@@ -339,7 +339,7 @@
 
 const char* ASensor_getStringType(ASensor const* sensor) {
     RETURN_IF_SENSOR_IS_NULL(nullptr);
-    return static_cast<Sensor const*>(sensor)->getStringType().string();
+    return static_cast<Sensor const*>(sensor)->getStringType().c_str();
 }
 
 int ASensor_getReportingMode(ASensor const* sensor) {
diff --git a/native/android/storage_manager.cpp b/native/android/storage_manager.cpp
index 294ca9c..6db87df 100644
--- a/native/android/storage_manager.cpp
+++ b/native/android/storage_manager.cpp
@@ -175,7 +175,7 @@
         String16 filename16(filename);
         String16 path16;
         if (mMountService->getMountedObbPath(filename16, path16)) {
-            return String8(path16).string();
+            return String8(path16).c_str();
         } else {
             return NULL;
         }
@@ -183,7 +183,7 @@
 };
 
 void ObbActionListener::onObbResult(const android::String16& filename, const int32_t nonce, const int32_t state) {
-    mStorageManager->fireCallback(String8(filename).string(), nonce, state);
+    mStorageManager->fireCallback(String8(filename).c_str(), nonce, state);
 }
 
 
diff --git a/native/android/tests/performance_hint/OWNERS b/native/android/tests/performance_hint/OWNERS
new file mode 100644
index 0000000..e3bbee92
--- /dev/null
+++ b/native/android/tests/performance_hint/OWNERS
@@ -0,0 +1 @@
+include /ADPF_OWNERS
diff --git a/packages/CredentialManager/horologist/OWNERS b/packages/CredentialManager/horologist/OWNERS
new file mode 100644
index 0000000..b679328
--- /dev/null
+++ b/packages/CredentialManager/horologist/OWNERS
@@ -0,0 +1,4 @@
+include /core/java/android/credentials/OWNERS
+
+shuanghao@google.com
+gustavopagani@google.com
diff --git a/packages/CredentialManager/shared/OWNERS b/packages/CredentialManager/shared/OWNERS
new file mode 100644
index 0000000..b679328
--- /dev/null
+++ b/packages/CredentialManager/shared/OWNERS
@@ -0,0 +1,4 @@
+include /core/java/android/credentials/OWNERS
+
+shuanghao@google.com
+gustavopagani@google.com
diff --git a/packages/CredentialManager/wear/OWNERS b/packages/CredentialManager/wear/OWNERS
new file mode 100644
index 0000000..b679328
--- /dev/null
+++ b/packages/CredentialManager/wear/OWNERS
@@ -0,0 +1,4 @@
+include /core/java/android/credentials/OWNERS
+
+shuanghao@google.com
+gustavopagani@google.com
diff --git a/packages/CtsShim/build/Android.bp b/packages/CtsShim/build/Android.bp
index af3e210..ae46f80 100644
--- a/packages/CtsShim/build/Android.bp
+++ b/packages/CtsShim/build/Android.bp
@@ -202,3 +202,22 @@
     ],
     min_sdk_version: "24",
 }
+
+//##########################################################
+// Variant: Add apk to an apex
+android_app {
+    name: "CtsShimAddApkToApex",
+    sdk_version: "current",
+    srcs: ["shim_add_apk_to_apex/src/android/addapktoapex/app/AddApkToApexDeviceActivity.java"],
+    optimize: {
+        enabled: false,
+    },
+    dex_preopt: {
+        enabled: false,
+    },
+    manifest: "shim_add_apk_to_apex/AndroidManifestAddApkToApex.xml",
+    apex_available: [
+        "//apex_available:platform",
+        "com.android.apex.cts.shim.v2_add_apk_to_apex",
+    ],
+}
diff --git a/packages/CtsShim/build/shim_add_apk_to_apex/AndroidManifestAddApkToApex.xml b/packages/CtsShim/build/shim_add_apk_to_apex/AndroidManifestAddApkToApex.xml
new file mode 100644
index 0000000..0e620b0
--- /dev/null
+++ b/packages/CtsShim/build/shim_add_apk_to_apex/AndroidManifestAddApkToApex.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2023 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+     package="android.addapktoapex.app">
+
+    <application>
+        <activity android:name=".AddApkToApexDeviceActivity"
+             android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
\ No newline at end of file
diff --git a/packages/CtsShim/build/shim_add_apk_to_apex/src/android/addapktoapex/app/AddApkToApexDeviceActivity.java b/packages/CtsShim/build/shim_add_apk_to_apex/src/android/addapktoapex/app/AddApkToApexDeviceActivity.java
new file mode 100644
index 0000000..c68904b
--- /dev/null
+++ b/packages/CtsShim/build/shim_add_apk_to_apex/src/android/addapktoapex/app/AddApkToApexDeviceActivity.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2023 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.addapktoapex.app;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.util.Log;
+
+/**
+ * A simple activity which logs to Logcat.
+ */
+public class AddApkToApexDeviceActivity extends Activity {
+
+    private static final String TAG = AddApkToApexDeviceActivity.class.getSimpleName();
+
+    /**
+     * The test string to log.
+     */
+    private static final String TEST_STRING = "AddApkToApexTestString";
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+        // Log the test string to Logcat.
+        Log.i(TAG, TEST_STRING);
+    }
+
+}
diff --git a/packages/DynamicSystemInstallationService/src/com/android/dynsystem/DynamicSystemInstallationService.java b/packages/DynamicSystemInstallationService/src/com/android/dynsystem/DynamicSystemInstallationService.java
index 3b56016..c390f31 100644
--- a/packages/DynamicSystemInstallationService/src/com/android/dynsystem/DynamicSystemInstallationService.java
+++ b/packages/DynamicSystemInstallationService/src/com/android/dynsystem/DynamicSystemInstallationService.java
@@ -419,12 +419,20 @@
         mDynSystem.remove();
     }
 
+    private boolean isDsuSlotLocked() {
+        // Slot names ending with ".lock" are a customized installation.
+        // We expect the client app to provide custom UI to enter/exit DSU mode.
+        // We will ignore the ACTION_REBOOT_TO_NORMAL command and will not show
+        // notifications in this case.
+        return mDynSystem.getActiveDsuSlot().endsWith(".lock");
+    }
+
     private void executeRebootToNormalCommand() {
         if (!isInDynamicSystem()) {
             Log.e(TAG, "It's already running in normal system.");
             return;
         }
-        if (mDynSystem.getActiveDsuSlot().endsWith(".lock")) {
+        if (isDsuSlotLocked()) {
             Log.e(TAG, "Ignore the reboot intent for a locked DSU slot");
             return;
         }
@@ -449,13 +457,13 @@
     private void executeNotifyIfInUseCommand() {
         switch (getStatus()) {
             case STATUS_IN_USE:
-                if (!mHideNotification) {
+                if (!mHideNotification && !isDsuSlotLocked()) {
                     startForeground(NOTIFICATION_ID,
                             buildNotification(STATUS_IN_USE, CAUSE_NOT_SPECIFIED));
                 }
                 break;
             case STATUS_READY:
-                if (!mHideNotification) {
+                if (!mHideNotification && !isDsuSlotLocked()) {
                     startForeground(NOTIFICATION_ID,
                             buildNotification(STATUS_READY, CAUSE_NOT_SPECIFIED));
                 }
diff --git a/packages/EasterEgg/Android.bp b/packages/EasterEgg/Android.bp
index e88410c..6d4e801 100644
--- a/packages/EasterEgg/Android.bp
+++ b/packages/EasterEgg/Android.bp
@@ -26,7 +26,10 @@
 android_app {
     // the build system in pi-dev can't quite handle R.java in kt
     // so we will have a mix of java and kotlin files
-    srcs: ["src/**/*.java", "src/**/*.kt"],
+    srcs: [
+        "src/**/*.java",
+        "src/**/*.kt",
+    ],
 
     resource_dirs: ["res"],
 
@@ -39,16 +42,16 @@
         proguard_flags_files: ["proguard.flags"],
     },
 
-	static_libs: [
-		"androidx.core_core",
-		"androidx.recyclerview_recyclerview",
+    static_libs: [
+        "androidx.core_core",
+        "androidx.recyclerview_recyclerview",
         "androidx.annotation_annotation",
-		"kotlinx-coroutines-android",
-		"kotlinx-coroutines-core",
-		//"kotlinx-coroutines-reactive",
-	],
+        "kotlinx-coroutines-android",
+        "kotlinx-coroutines-core",
+        //"kotlinx-coroutines-reactive",
+    ],
 
     manifest: "AndroidManifest.xml",
 
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
 }
diff --git a/packages/EasterEgg/src/com/android/egg/quares/Quare.kt b/packages/EasterEgg/src/com/android/egg/quares/Quare.kt
index eb77362..f0cc2a1 100644
--- a/packages/EasterEgg/src/com/android/egg/quares/Quare.kt
+++ b/packages/EasterEgg/src/com/android/egg/quares/Quare.kt
@@ -137,14 +137,12 @@
         return 0
     }
 
-    override fun writeToParcel(p: Parcel?, flags: Int) {
-        p?.let {
-            p.writeInt(width)
-            p.writeInt(height)
-            p.writeInt(depth)
-            p.writeIntArray(data)
-            p.writeIntArray(user)
-        }
+    override fun writeToParcel(p: Parcel, flags: Int) {
+        p.writeInt(width)
+        p.writeInt(height)
+        p.writeInt(depth)
+        p.writeIntArray(data)
+        p.writeIntArray(user)
     }
 
     companion object CREATOR : Parcelable.Creator<Quare> {
diff --git a/packages/EasterEgg/src/com/android/egg/quares/QuaresActivity.kt b/packages/EasterEgg/src/com/android/egg/quares/QuaresActivity.kt
index 578de01..5fa6137 100644
--- a/packages/EasterEgg/src/com/android/egg/quares/QuaresActivity.kt
+++ b/packages/EasterEgg/src/com/android/egg/quares/QuaresActivity.kt
@@ -60,8 +60,8 @@
 
         setContentView(R.layout.activity_quares)
 
-        grid = findViewById(R.id.grid)
-        label = findViewById(R.id.label)
+        grid = requireViewById(R.id.grid)
+        label = requireViewById(R.id.label)
 
         if (savedInstanceState != null) {
             Log.v(TAG, "restoring puzzle from state")
@@ -135,7 +135,7 @@
         if (q.check()) {
             val dp = resources.displayMetrics.density
 
-            val label: Button = findViewById(R.id.label)
+            val label: Button = requireViewById(R.id.label)
             label.text = resName.replace(Regex("^.*/"), "")
             val drawable = icon?.loadDrawable(this)?.also {
                 it.setBounds(0, 0, (32 * dp).toInt(), (32 * dp).toInt())
diff --git a/packages/EncryptedLocalTransport/Android.bp b/packages/EncryptedLocalTransport/Android.bp
index 09e5630..9ae6d96 100644
--- a/packages/EncryptedLocalTransport/Android.bp
+++ b/packages/EncryptedLocalTransport/Android.bp
@@ -27,9 +27,6 @@
     name: "EncryptedLocalTransport",
     defaults: ["platform_app_defaults"],
     srcs: ["src/**/*.java"],
-    optimize: {
-        proguard_flags_files: ["proguard.flags"],
-    },
     static_libs: ["LocalTransport"],
     platform_apis: true,
     certificate: "platform",
diff --git a/packages/EncryptedLocalTransport/proguard.flags b/packages/EncryptedLocalTransport/proguard.flags
deleted file mode 100644
index e4ce3c5..0000000
--- a/packages/EncryptedLocalTransport/proguard.flags
+++ /dev/null
@@ -1,2 +0,0 @@
--keep class com.android.localTransport.EncryptedLocalTransport
--keep class com.android.localTransport.EncryptedLocalTransportService
diff --git a/packages/Keyguard/proguard.flags b/packages/Keyguard/proguard.flags
deleted file mode 100644
index fb74b64..0000000
--- a/packages/Keyguard/proguard.flags
+++ /dev/null
@@ -1,27 +0,0 @@
--keep public class * {
-  public void setBackgroundAlpha(float);
-  public float getBackgroundAlpha();
-  public void setContentAlpha(float);
-  public float getContentAlpha();
-  public void setAlpha(float);
-  public float getAlpha();
-  public void setAlpha(int);
-  public int getAlpha();
-  public void setRotationX(float);
-  public float getRotationX();
-  public void setRotationY(float);
-  public float getRotationY();
-  public void setPivotX(float);
-  public float getPivotX();
-  public void setPivotY(float);
-  public float getPivotY();
-  public void setScaleX(float);
-  public float getScaleX();
-  public void setScaleY(float);
-  public float getScaleY();
-  public void setTranslationX(float);
-  public float getTranslationX();
-  public void setTranslationY(float);
-  public float getTranslationY();
-}
-
diff --git a/packages/LocalTransport/Android.bp b/packages/LocalTransport/Android.bp
index d4fa191..e7a273b 100644
--- a/packages/LocalTransport/Android.bp
+++ b/packages/LocalTransport/Android.bp
@@ -27,9 +27,7 @@
     name: "LocalTransport",
     defaults: ["platform_app_defaults"],
     srcs: ["src/**/*.java"],
-    optimize: {
-        proguard_flags_files: ["proguard.flags"],
-    },
+    libs: ["keepanno-annotations"],
     platform_apis: true,
     certificate: "platform",
     privileged: true,
diff --git a/packages/LocalTransport/proguard.flags b/packages/LocalTransport/proguard.flags
deleted file mode 100644
index c1f51b8..0000000
--- a/packages/LocalTransport/proguard.flags
+++ /dev/null
@@ -1,5 +0,0 @@
--keep class com.android.localTransport.LocalTransport
--keep class com.android.localTransport.LocalTransportParameters
--keep class com.android.localTransport.LocalTransportService
-
-
diff --git a/packages/LocalTransport/src/com/android/localtransport/LocalTransport.java b/packages/LocalTransport/src/com/android/localtransport/LocalTransport.java
index 4344e94..6540cc0 100644
--- a/packages/LocalTransport/src/com/android/localtransport/LocalTransport.java
+++ b/packages/LocalTransport/src/com/android/localtransport/LocalTransport.java
@@ -35,6 +35,9 @@
 import android.util.Base64;
 import android.util.Log;
 
+import com.android.tools.r8.keepanno.annotations.KeepTarget;
+import com.android.tools.r8.keepanno.annotations.UsesReflection;
+
 import libcore.io.IoUtils;
 
 import java.io.BufferedOutputStream;
@@ -122,6 +125,13 @@
         return mParameters;
     }
 
+
+    @UsesReflection({
+            // As the runtime class name is used to generate the returned name, and the returned
+            // name may be used used with reflection, generate the necessary keep rules.
+            @KeepTarget(classConstant = LocalTransport.class),
+            @KeepTarget(extendsClassConstant = LocalTransport.class)
+    })
     @Override
     public String name() {
         return new ComponentName(mContext, this.getClass()).flattenToShortString();
diff --git a/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java b/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
index 9c6113c..3de6cfd 100644
--- a/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
+++ b/packages/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
@@ -371,7 +371,7 @@
         if (mLocalLOGV) Log.i(TAG, "onResume(): mAppSnippet=" + mAppSnippet);
 
         if (mAppSnippet != null) {
-            // load dummy layout with OK button disabled until we override this layout in
+            // load placeholder layout with OK button disabled until we override this layout in
             // startInstallConfirm
             bindUi();
             checkIfAllowedAndInitiateInstall();
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java
index 2d958a9..1ab787e 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothUtils.java
@@ -294,8 +294,8 @@
      */
     public static boolean isDeviceClassMatched(@NonNull BluetoothDevice bluetoothDevice,
             int device) {
-        return bluetoothDevice.getBluetoothClass() != null
-                && bluetoothDevice.getBluetoothClass().getDeviceClass() == device;
+        final BluetoothClass bluetoothClass = bluetoothDevice.getBluetoothClass();
+        return bluetoothClass != null && bluetoothClass.getDeviceClass() == device;
     }
 
     private static boolean isAdvancedHeaderEnabled() {
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/OWNERS b/packages/SettingsLib/src/com/android/settingslib/bluetooth/OWNERS
index 5e66972..7669e79b 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/OWNERS
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/OWNERS
@@ -3,7 +3,10 @@
 hughchen@google.com
 timhypeng@google.com
 robertluo@google.com
-changbetty@google.com
 songferngwang@google.com
+yqian@google.com
+chelseahao@google.com
+yiyishen@google.com
+hahong@google.com
 
 # Emergency approvers in case the above are not available
diff --git a/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt b/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
index faea5b2..61a45f7 100644
--- a/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
+++ b/packages/SettingsLib/src/com/android/settingslib/graph/ThemedBatteryDrawable.kt
@@ -324,7 +324,7 @@
         return batteryLevel
     }
 
-    override fun onBoundsChange(bounds: Rect?) {
+    override fun onBoundsChange(bounds: Rect) {
         super.onBoundsChange(bounds)
         updateSize()
     }
diff --git a/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java b/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java
index b8887ae..cbfc914 100644
--- a/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java
+++ b/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java
@@ -24,7 +24,7 @@
     /**
      * These keys may be mentioned in the SETTINGS_TO_BACKUP arrays in SystemSettings
      * and SecureSettings as well.  This is because those tables drive both backup and
-     * restore, and restore needs to properly whitelist keys that used to live
+     * restore, and restore needs to properly allowlist keys that used to live
      * in those namespaces.
      *
      * NOTE: Settings are backed up and restored in the order they appear
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
index 11154d1..b404465 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
@@ -884,7 +884,7 @@
     @VisibleForTesting
     SettingsBackupWhitelist getBackupWhitelist(Uri contentUri) {
         // Figure out the white list and redirects to the global table.  We restore anything
-        // in either the backup whitelist or the legacy-restore whitelist for this table.
+        // in either the backup allowlist or the legacy-restore allowlist for this table.
         String[] whitelist;
         Map<String, Validator> validators = null;
         if (contentUri.equals(Settings.Secure.CONTENT_URI)) {
@@ -1432,7 +1432,7 @@
     }
 
     /**
-     * Store the whitelist of settings to be backed up and validators for them.
+     * Store the allowlist of settings to be backed up and validators for them.
      */
     @VisibleForTesting
     static class SettingsBackupWhitelist {
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 8ce33d3..8b5bc56 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -234,7 +234,7 @@
     public static final int WRITE_FALLBACK_SETTINGS_FILES_JOB_ID = 1;
     public static final long ONE_DAY_INTERVAL_MILLIS = 24 * 60 * 60 * 1000L;
 
-    // Overlay specified settings whitelisted for Instant Apps
+    // Overlay specified settings allowlisted for Instant Apps
     private static final Set<String> OVERLAY_ALLOWED_GLOBAL_INSTANT_APP_SETTINGS = new ArraySet<>();
     private static final Set<String> OVERLAY_ALLOWED_SYSTEM_INSTANT_APP_SETTINGS = new ArraySet<>();
     private static final Set<String> OVERLAY_ALLOWED_SECURE_INSTANT_APP_SETTINGS = new ArraySet<>();
@@ -2111,7 +2111,7 @@
 
     @GuardedBy("mLock")
     private List<String> getSettingsNamesLocked(int settingsType, int userId) {
-        // Don't enforce the instant app whitelist for now -- its too prone to unintended breakage
+        // Don't enforce the instant app allowlist for now -- its too prone to unintended breakage
         // in the current form.
         return mSettingsRegistry.getSettingsNamesLocked(settingsType, userId);
     }
@@ -2152,7 +2152,7 @@
         }
         if (!getInstantAppAccessibleSettings(settingsType).contains(settingName)
                 && !getOverlayInstantAppAccessibleSettings(settingsType).contains(settingName)) {
-            // Don't enforce the instant app whitelist for now -- its too prone to unintended
+            // Don't enforce the instant app allowlist for now -- its too prone to unintended
             // breakage in the current form.
             Slog.w(LOG_TAG, "Instant App " + ai.packageName
                     + " trying to access unexposed setting, this will be an error in the future.");
diff --git a/packages/SharedStorageBackup/Android.bp b/packages/SharedStorageBackup/Android.bp
index 21516fa..225b5b4 100644
--- a/packages/SharedStorageBackup/Android.bp
+++ b/packages/SharedStorageBackup/Android.bp
@@ -27,9 +27,6 @@
     name: "SharedStorageBackup",
     defaults: ["platform_app_defaults"],
     srcs: ["src/**/*.java"],
-    optimize: {
-        proguard_flags_files: ["proguard.flags"],
-    },
     platform_apis: true,
     certificate: "platform",
     privileged: true,
diff --git a/packages/SharedStorageBackup/proguard.flags b/packages/SharedStorageBackup/proguard.flags
deleted file mode 100644
index 6a66a47..0000000
--- a/packages/SharedStorageBackup/proguard.flags
+++ /dev/null
@@ -1,2 +0,0 @@
--keep class com.android.sharedstoragebackup.SharedStorageAgent
--keep class com.android.sharedstoragebackup.ObbBackupService
diff --git a/packages/SystemUI/Android.bp b/packages/SystemUI/Android.bp
index eb5a15f..71bd639 100644
--- a/packages/SystemUI/Android.bp
+++ b/packages/SystemUI/Android.bp
@@ -134,6 +134,7 @@
         "res-keyguard",
         "res",
     ],
+    use_resource_processor: true,
     static_libs: [
         "WifiTrackerLib",
         "WindowManager-Shell",
@@ -180,7 +181,7 @@
     ],
     manifest: "AndroidManifest.xml",
 
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
 
     plugins: ["dagger2-compiler"],
 
@@ -341,7 +342,7 @@
         "android.test.base",
         "android.test.mock",
     ],
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
     aaptflags: [
         "--extra-packages",
         "com.android.systemui",
@@ -452,12 +453,13 @@
     ],
     resource_dirs: [],
 
+    use_resource_processor: true,
     platform_apis: true,
     system_ext_specific: true,
     certificate: "platform",
     privileged: true,
 
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
 
     dxflags: ["--multi-dex"],
     required: [
diff --git a/packages/SystemUI/OWNERS b/packages/SystemUI/OWNERS
index 811b409..b1ba5c0 100644
--- a/packages/SystemUI/OWNERS
+++ b/packages/SystemUI/OWNERS
@@ -4,8 +4,8 @@
 
 dsandler@android.com
 
-aaliomer@google.com
 aaronjli@google.com
+achalke@google.com
 acul@google.com
 adamcohen@google.com
 aioana@google.com
@@ -23,6 +23,7 @@
 brycelee@google.com
 brzezinski@google.com
 caitlinshk@google.com
+cameronyee@google.com
 chandruis@google.com
 chrisgollner@google.com
 cinek@google.com
@@ -34,6 +35,7 @@
 gwasserman@google.com
 hwwang@google.com
 hyunyoungs@google.com
+ikateryna@google.com
 jaggies@google.com
 jamesoleary@google.com
 jbolinger@google.com
@@ -44,6 +46,7 @@
 jjaggi@google.com
 jonmiranda@google.com
 joshtrask@google.com
+juansmartinez@google.com
 juliacr@google.com
 juliatuttle@google.com
 justinkoh@google.com
@@ -70,25 +73,28 @@
 patmanning@google.com
 peanutbutter@google.com
 peskal@google.com
+petrcermak@google.com
 pinyaoting@google.com
 pixel@google.com
 pomini@google.com
 rahulbanerjee@google.com
-rasheedlewis@google.com
 roosa@google.com
 saff@google.com
 santie@google.com
 shanh@google.com
 snoeberger@google.com
 steell@google.com
+stevenckng@google.com
 stwu@google.com
 syeonlee@google.com
 sunnygoyal@google.com
 thiruram@google.com
+tkachenkoi@google.com
 tracyzhou@google.com
 tsuji@google.com
 twickham@google.com
 vadimt@google.com
+vanjan@google.com
 victortulias@google.com
 winsonc@google.com
 wleshner@google.com
@@ -98,7 +104,6 @@
 yuandizhou@google.com
 yurilin@google.com
 zakcohen@google.com
-zoepage@google.com
 
 #Android TV
 rgl@google.com
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityLaunchAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityLaunchAnimator.kt
index 296c2ae..32085ce 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityLaunchAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityLaunchAnimator.kt
@@ -302,10 +302,9 @@
 
     interface Callback {
         /** Whether we are currently on the keyguard or not. */
-        @JvmDefault fun isOnKeyguard(): Boolean = false
+        fun isOnKeyguard(): Boolean = false
 
         /** Hide the keyguard and animate using [runner]. */
-        @JvmDefault
         fun hideKeyguardWithAnimation(runner: IRemoteAnimationRunner) {
             throw UnsupportedOperationException()
         }
@@ -316,16 +315,16 @@
 
     interface Listener {
         /** Called when an activity launch animation started. */
-        @JvmDefault fun onLaunchAnimationStart() {}
+        fun onLaunchAnimationStart() {}
 
         /**
          * Called when an activity launch animation is finished. This will be called if and only if
          * [onLaunchAnimationStart] was called earlier.
          */
-        @JvmDefault fun onLaunchAnimationEnd() {}
+        fun onLaunchAnimationEnd() {}
 
         /** Called when an activity launch animation made progress. */
-        @JvmDefault fun onLaunchAnimationProgress(linearProgress: Float) {}
+        fun onLaunchAnimationProgress(linearProgress: Float) {}
     }
 
     /**
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/FontInterpolator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/FontInterpolator.kt
index f0a8211..83e44b6 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/FontInterpolator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/FontInterpolator.kt
@@ -18,8 +18,10 @@
 
 import android.graphics.fonts.Font
 import android.graphics.fonts.FontVariationAxis
+import android.util.LruCache
 import android.util.MathUtils
 import android.util.MathUtils.abs
+import androidx.annotation.VisibleForTesting
 import java.lang.Float.max
 import java.lang.Float.min
 
@@ -34,6 +36,10 @@
 private const val FONT_ITALIC_ANIMATION_STEP = 0.1f
 private const val FONT_ITALIC_DEFAULT_VALUE = 0f
 
+// Benchmarked via Perfetto, difference between 10 and 50 entries is about 0.3ms in
+// frame draw time on a Pixel 6.
+@VisibleForTesting const val FONT_CACHE_MAX_ENTRIES = 10
+
 /** Provide interpolation of two fonts by adjusting font variation settings. */
 class FontInterpolator {
 
@@ -81,8 +87,8 @@
     // Font interpolator has two level caches: one for input and one for font with different
     // variation settings. No synchronization is needed since FontInterpolator is not designed to be
     // thread-safe and can be used only on UI thread.
-    private val interpCache = hashMapOf<InterpKey, Font>()
-    private val verFontCache = hashMapOf<VarFontKey, Font>()
+    private val interpCache = LruCache<InterpKey, Font>(FONT_CACHE_MAX_ENTRIES)
+    private val verFontCache = LruCache<VarFontKey, Font>(FONT_CACHE_MAX_ENTRIES)
 
     // Mutable keys for recycling.
     private val tmpInterpKey = InterpKey(null, null, 0f)
@@ -152,7 +158,7 @@
         tmpVarFontKey.set(start, newAxes)
         val axesCachedFont = verFontCache[tmpVarFontKey]
         if (axesCachedFont != null) {
-            interpCache[InterpKey(start, end, progress)] = axesCachedFont
+            interpCache.put(InterpKey(start, end, progress), axesCachedFont)
             return axesCachedFont
         }
 
@@ -160,8 +166,8 @@
         // Font.Builder#build won't throw IOException since creating fonts from existing fonts will
         // not do any IO work.
         val newFont = Font.Builder(start).setFontVariationSettings(newAxes.toTypedArray()).build()
-        interpCache[InterpKey(start, end, progress)] = newFont
-        verFontCache[VarFontKey(start, newAxes)] = newFont
+        interpCache.put(InterpKey(start, end, progress), newFont)
+        verFontCache.put(VarFontKey(start, newAxes), newFont)
         return newFont
     }
 
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt
index 9e9929e..3ee97be 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt
@@ -24,8 +24,10 @@
 import android.graphics.Typeface
 import android.graphics.fonts.Font
 import android.text.Layout
+import android.util.LruCache
 
 private const val DEFAULT_ANIMATION_DURATION: Long = 300
+private const val TYPEFACE_CACHE_MAX_ENTRIES = 5
 
 typealias GlyphCallback = (TextAnimator.PositionedGlyph, Float) -> Unit
 /**
@@ -114,7 +116,7 @@
 
     private val fontVariationUtils = FontVariationUtils()
 
-    private val typefaceCache = HashMap<String, Typeface?>()
+    private val typefaceCache = LruCache<String, Typeface>(TYPEFACE_CACHE_MAX_ENTRIES)
 
     fun updateLayout(layout: Layout) {
         textInterpolator.layout = layout
@@ -218,12 +220,12 @@
         }
 
         if (!fvar.isNullOrBlank()) {
-            textInterpolator.targetPaint.typeface =
-                typefaceCache.getOrElse(fvar) {
-                    textInterpolator.targetPaint.fontVariationSettings = fvar
+            textInterpolator.targetPaint.typeface = typefaceCache.get(fvar) ?: run {
+                textInterpolator.targetPaint.fontVariationSettings = fvar
+                textInterpolator.targetPaint.typeface?.also {
                     typefaceCache.put(fvar, textInterpolator.targetPaint.typeface)
-                    textInterpolator.targetPaint.typeface
                 }
+            }
         }
 
         if (color != null) {
diff --git a/packages/SystemUI/compose/core/tests/Android.bp b/packages/SystemUI/compose/core/tests/Android.bp
index 6119e96..06d94ac 100644
--- a/packages/SystemUI/compose/core/tests/Android.bp
+++ b/packages/SystemUI/compose/core/tests/Android.bp
@@ -44,5 +44,5 @@
         "androidx.compose.ui_ui-test-manifest",
     ],
 
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
 }
diff --git a/packages/SystemUI/compose/features/tests/Android.bp b/packages/SystemUI/compose/features/tests/Android.bp
index ff534bd..c7c9140 100644
--- a/packages/SystemUI/compose/features/tests/Android.bp
+++ b/packages/SystemUI/compose/features/tests/Android.bp
@@ -44,5 +44,5 @@
         "androidx.compose.ui_ui-test-manifest",
     ],
 
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
 }
diff --git a/packages/SystemUI/customization/Android.bp b/packages/SystemUI/customization/Android.bp
index dc450bb..fc37b355 100644
--- a/packages/SystemUI/customization/Android.bp
+++ b/packages/SystemUI/customization/Android.bp
@@ -48,5 +48,5 @@
     ],
     min_sdk_version: "current",
     plugins: ["dagger2-compiler"],
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
 }
diff --git a/packages/SystemUI/docs/qs-tiles.md b/packages/SystemUI/docs/qs-tiles.md
index 488f8c7..bd0b4ab 100644
--- a/packages/SystemUI/docs/qs-tiles.md
+++ b/packages/SystemUI/docs/qs-tiles.md
@@ -123,7 +123,7 @@
 
 ### API classes
 
-The classes that define the public API are in [core/java/android/service/quicksettings](core/java/android/service/quicksettings).
+The classes that define the public API are in [core/java/android/service/quicksettings](/core/java/android/service/quicksettings).
 
 #### Tile
 
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 3faacf2..adc4c55 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -396,7 +396,7 @@
     <dimen name="navigation_key_width">70dp</dimen>
 
     <!-- The width/height of the icon of a navigation button -->
-    <dimen name="navigation_icon_size">32dp</dimen>
+    <dimen name="navigation_icon_size">24dp</dimen>
 
     <!-- The padding on the side of the navigation bar. Must be greater than or equal to
          navigation_extra_key_width -->
diff --git a/packages/SystemUI/shared/Android.bp b/packages/SystemUI/shared/Android.bp
index 28e786b..ca30e15 100644
--- a/packages/SystemUI/shared/Android.bp
+++ b/packages/SystemUI/shared/Android.bp
@@ -65,7 +65,7 @@
     ],
     min_sdk_version: "current",
     plugins: ["dagger2-compiler"],
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
 }
 
 java_library {
diff --git a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
index 3b9060a..d2e4640 100644
--- a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
+++ b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
@@ -30,7 +30,7 @@
 import androidx.annotation.VisibleForTesting
 import androidx.lifecycle.Lifecycle
 import androidx.lifecycle.repeatOnLifecycle
-import com.android.systemui.R
+import com.android.systemui.customization.R
 import com.android.systemui.broadcast.BroadcastDispatcher
 import com.android.systemui.dagger.qualifiers.Background
 import com.android.systemui.dagger.qualifiers.Main
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
index 0326b6d..bc45e31 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitch.java
@@ -52,7 +52,9 @@
         int largeClockTopMargin = parent.getResources()
                 .getDimensionPixelSize(R.dimen.keyguard_large_clock_top_margin);
         int targetHeight = parent.getResources()
-                .getDimensionPixelSize(R.dimen.large_clock_text_size) * 2;
+                .getDimensionPixelSize(
+                        com.android.systemui.customization.R.dimen.large_clock_text_size)
+                * 2;
         int top = parent.getHeight() / 2 - targetHeight / 2
                 + largeClockTopMargin / 2;
         return new Rect(
@@ -152,7 +154,8 @@
         if (mClock != null) {
             if (mSmallClockFrame.isLaidOut()) {
                 int targetHeight =  getResources()
-                        .getDimensionPixelSize(R.dimen.small_clock_text_size);
+                        .getDimensionPixelSize(
+                            com.android.systemui.customization.R.dimen.small_clock_text_size);
                 mClock.getSmallClock().getEvents().onTargetRegionChanged(new Rect(
                         mSmallClockFrame.getLeft(),
                         mSmallClockFrame.getTop(),
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
index ba21780..bf98717 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardClockSwitchController.java
@@ -470,7 +470,8 @@
 
     private void updateDoubleLineClock() {
         mCanShowDoubleLineClock = mSecureSettings.getIntForUser(
-            Settings.Secure.LOCKSCREEN_USE_DOUBLE_LINE_CLOCK, 1,
+            Settings.Secure.LOCKSCREEN_USE_DOUBLE_LINE_CLOCK, mView.getResources()
+                .getInteger(com.android.internal.R.integer.config_doublelineClockDefault),
                 UserHandle.USER_CURRENT) != 0;
 
         if (!mCanShowDoubleLineClock) {
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
index ba5a8c9..ccc1e45 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
@@ -1150,7 +1150,8 @@
                     }
                     drawable.setTint(iconColor);
 
-                    Drawable bg = context.getDrawable(R.drawable.user_avatar_bg);
+                    Drawable bg = context.getDrawable(
+                            com.android.settingslib.R.drawable.user_avatar_bg);
                     bg.setTintBlendMode(BlendMode.DST);
                     bg.setTint(Utils.getColorAttrDefaultColor(context,
                                 com.android.internal.R.attr.colorSurfaceVariant));
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
index 061bab8..16299c7 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
@@ -752,7 +752,7 @@
                 case SimPuk:
                     // Shortcut for SIM PIN/PUK to go to directly to user's security screen or home
                     SecurityMode securityMode = mSecurityModel.getSecurityMode(targetUserId);
-                    if (securityMode == SecurityMode.None && mLockPatternUtils.isLockScreenDisabled(
+                    if (securityMode == SecurityMode.None || mLockPatternUtils.isLockScreenDisabled(
                             KeyguardUpdateMonitor.getCurrentUser())) {
                         finish = true;
                         eventSubtype = BOUNCER_DISMISS_SIM;
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
index a08f540..6507488 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -549,6 +549,18 @@
         dispatchErrorMessage(message);
     }
 
+    @Override
+    public void onEnabledTrustAgentsChanged(int userId) {
+        Assert.isMainThread();
+
+        for (int i = 0; i < mCallbacks.size(); i++) {
+            KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
+            if (cb != null) {
+                cb.onEnabledTrustAgentsChanged(userId);
+            }
+        }
+    }
+
     private void handleSimSubscriptionInfoChanged() {
         Assert.isMainThread();
         mLogger.v("onSubscriptionInfoChanged()");
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
index feff216..7394005 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
@@ -322,4 +322,9 @@
      * Called when keyguard is going away or not going away.
      */
     public void onKeyguardGoingAway() { }
+
+    /**
+     * Called when the enabled trust agents associated with the specified user.
+     */
+    public void onEnabledTrustAgentsChanged(int userId) { }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/GuestSessionNotification.java b/packages/SystemUI/src/com/android/systemui/GuestSessionNotification.java
index fa9a83e..7a6b1c3 100644
--- a/packages/SystemUI/src/com/android/systemui/GuestSessionNotification.java
+++ b/packages/SystemUI/src/com/android/systemui/GuestSessionNotification.java
@@ -64,12 +64,15 @@
         }
         String contentText;
         if (userInfo.isEphemeral()) {
-            contentText = mContext.getString(R.string.guest_notification_ephemeral);
+            contentText = mContext.getString(
+                    com.android.settingslib.R.string.guest_notification_ephemeral);
         } else if (isGuestFirstLogin) {
-            contentText = mContext.getString(R.string.guest_notification_non_ephemeral);
+            contentText = mContext.getString(
+                    com.android.settingslib.R.string.guest_notification_non_ephemeral);
         } else {
             contentText = mContext.getString(
-                            R.string.guest_notification_non_ephemeral_non_first_login);
+                    com.android.settingslib.R.string
+                        .guest_notification_non_ephemeral_non_first_login);
         }
 
         final Intent guestExitIntent = new Intent(
@@ -89,7 +92,7 @@
 
         Notification.Builder builder = new Notification.Builder(mContext,
                                                                 NotificationChannels.ALERTS)
-                .setSmallIcon(R.drawable.ic_account_circle)
+                .setSmallIcon(com.android.settingslib.R.drawable.ic_account_circle)
                 .setContentTitle(mContext.getString(R.string.guest_notification_session_active))
                 .setContentText(contentText)
                 .setPriority(Notification.PRIORITY_DEFAULT)
diff --git a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
index 370628c..eb004fb 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
+++ b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
@@ -106,7 +106,7 @@
         TypedArray atts = context.obtainStyledAttributes(attrs, R.styleable.BatteryMeterView,
                 defStyle, 0);
         final int frameColor = atts.getColor(R.styleable.BatteryMeterView_frameColor,
-                context.getColor(R.color.meter_background_color));
+                context.getColor(com.android.settingslib.R.color.meter_background_color));
         mPercentageStyleId = atts.getResourceId(R.styleable.BatteryMeterView_textAppearance, 0);
         mDrawable = new AccessorizedBatteryDrawable(context, frameColor);
         atts.recycle();
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/SideFpsController.kt b/packages/SystemUI/src/com/android/systemui/biometrics/SideFpsController.kt
index c98a62f..2bf8050 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/SideFpsController.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/SideFpsController.kt
@@ -460,7 +460,7 @@
             for (key in listOf(".blue600", ".blue400")) {
                 addValueCallback(KeyPath(key, "**"), LottieProperty.COLOR_FILTER) {
                     PorterDuffColorFilter(
-                        context.getColor(R.color.settingslib_color_blue400),
+                        context.getColor(com.android.settingslib.R.color.settingslib_color_blue400),
                         PorterDuff.Mode.SRC_ATOP
                     )
                 }
diff --git a/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStateController.java b/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStateController.java
index a475653..a2872e3 100644
--- a/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStateController.java
+++ b/packages/SystemUI/src/com/android/systemui/dreams/DreamOverlayStateController.java
@@ -182,6 +182,10 @@
      * Returns collection of present {@link Complication}.
      */
     public Collection<Complication> getComplications(boolean filterByAvailability) {
+        if (isLowLightActive()) {
+            // Don't show complications on low light.
+            return Collections.emptyList();
+        }
         return Collections.unmodifiableCollection(filterByAvailability
                 ? mComplications
                 .stream()
@@ -193,7 +197,8 @@
                     if (mShouldShowComplications) {
                         return (requiredTypes & getAvailableComplicationTypes()) == requiredTypes;
                     }
-                    return (requiredTypes & mSupportedTypes) == requiredTypes;
+                    final int typesToAlwaysShow = mSupportedTypes & getAvailableComplicationTypes();
+                    return (requiredTypes & typesToAlwaysShow) == requiredTypes;
                 })
                 .collect(Collectors.toCollection(HashSet::new))
                 : mComplications);
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt
index 90562dc..7992a34 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardUnlockAnimationController.kt
@@ -167,7 +167,6 @@
          * for the canned animation (if applicable) so interested parties can sync with it. If no
          * canned animation is playing, these are both 0.
          */
-        @JvmDefault
         fun onUnlockAnimationStarted(
             playingCannedAnimation: Boolean,
             fromWakeAndUnlock: Boolean,
@@ -180,7 +179,6 @@
          * The keyguard is no longer visible in this state and the app/launcher behind the keyguard
          * is now completely visible.
          */
-        @JvmDefault
         fun onUnlockAnimationFinished() {}
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfig.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfig.kt
index c9f645d..f2d6e1f 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfig.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/quickaffordance/CameraQuickAffordanceConfig.kt
@@ -34,7 +34,7 @@
 import javax.inject.Inject
 import kotlinx.coroutines.CoroutineDispatcher
 import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.flow
 import kotlinx.coroutines.withContext
 
 @SysUISingleton
@@ -59,16 +59,21 @@
         get() = R.drawable.ic_camera
 
     override val lockScreenState: Flow<KeyguardQuickAffordanceConfig.LockScreenState>
-        get() =
-            flowOf(
-                KeyguardQuickAffordanceConfig.LockScreenState.Visible(
-                    icon =
-                        Icon.Resource(
-                            R.drawable.ic_camera,
-                            ContentDescription.Resource(R.string.accessibility_camera_button)
-                        )
-                )
+        get() = flow {
+            emit(
+                if (isLaunchable()) {
+                    KeyguardQuickAffordanceConfig.LockScreenState.Visible(
+                        icon =
+                            Icon.Resource(
+                                R.drawable.ic_camera,
+                                ContentDescription.Resource(R.string.accessibility_camera_button)
+                            )
+                    )
+                } else {
+                    KeyguardQuickAffordanceConfig.LockScreenState.Hidden
+                }
             )
+        }
 
     override suspend fun getPickerScreenState(): KeyguardQuickAffordanceConfig.PickerScreenState {
         return if (isLaunchable()) {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/TrustRepository.kt b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/TrustRepository.kt
index d90f328..e912053 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/TrustRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/data/repository/TrustRepository.kt
@@ -75,6 +75,8 @@
                         override fun onTrustError(message: CharSequence?) = Unit
 
                         override fun onTrustManagedChanged(enabled: Boolean, userId: Int) = Unit
+
+                        override fun onEnabledTrustAgentsChanged(userId: Int) = Unit
                     }
                 trustManager.registerTrustListener(callback)
                 logger.trustListenerRegistered()
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToLockscreenTransitionViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToLockscreenTransitionViewModel.kt
index 5770f3e..ddce516 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToLockscreenTransitionViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToLockscreenTransitionViewModel.kt
@@ -47,6 +47,7 @@
             duration = TO_LOCKSCREEN_DURATION,
             onStep = { value -> -translatePx + value * translatePx },
             interpolator = EMPHASIZED_DECELERATE,
+            onCancel = { 0f },
         )
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/ColorSchemeTransition.kt b/packages/SystemUI/src/com/android/systemui/media/controls/ui/ColorSchemeTransition.kt
index 2b42604..14d4b68 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/ColorSchemeTransition.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/ColorSchemeTransition.kt
@@ -119,7 +119,7 @@
         ::AnimatingColorTransition
     )
 
-    val bgColor = context.getColor(com.android.systemui.R.color.material_dynamic_secondary95)
+    val bgColor = context.getColor(com.google.android.material.R.color.material_dynamic_secondary95)
     val surfaceColor =
         animatingColorTransitionFactory(bgColor, ::surfaceFromScheme) { surfaceColor ->
             val colorList = ColorStateList.valueOf(surfaceColor)
diff --git a/packages/SystemUI/src/com/android/systemui/people/PeopleStoryIconFactory.java b/packages/SystemUI/src/com/android/systemui/people/PeopleStoryIconFactory.java
index 58e700f..25965fc 100644
--- a/packages/SystemUI/src/com/android/systemui/people/PeopleStoryIconFactory.java
+++ b/packages/SystemUI/src/com/android/systemui/people/PeopleStoryIconFactory.java
@@ -33,7 +33,6 @@
 import androidx.core.graphics.drawable.RoundedBitmapDrawable;
 
 import com.android.settingslib.Utils;
-import com.android.systemui.R;
 
 class PeopleStoryIconFactory implements AutoCloseable {
 
@@ -59,7 +58,8 @@
         mIconSize = mDensity * iconSizeDp;
         mPackageManager = pm;
         mIconDrawableFactory = iconDrawableFactory;
-        mImportantConversationColor = mContext.getColor(R.color.important_conversation);
+        mImportantConversationColor = mContext.getColor(
+                com.android.launcher3.icons.R.color.important_conversation);
         mAccentColor = Utils.getColorAttr(mContext,
                 com.android.internal.R.attr.colorAccentPrimaryVariant).getDefaultColor();
     }
@@ -224,4 +224,4 @@
     @Override
     public void close() {
     }
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyConfig.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyConfig.kt
index d652889..d949a2a 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyConfig.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyConfig.kt
@@ -145,13 +145,10 @@
     }
 
     interface Callback {
-        @JvmDefault
         fun onFlagMicCameraChanged(flag: Boolean) {}
 
-        @JvmDefault
         fun onFlagLocationChanged(flag: Boolean) {}
 
-        @JvmDefault
         fun onFlagMediaProjectionChanged(flag: Boolean) {}
     }
 }
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt
index a676150..eb8ef9b 100644
--- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItemController.kt
@@ -216,7 +216,6 @@
     interface Callback : PrivacyConfig.Callback {
         fun onPrivacyItemsChanged(privacyItems: List<PrivacyItem>)
 
-        @JvmDefault
         fun onFlagAllChanged(flag: Boolean) {}
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
index 6bf8b76..30bfd6d 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
@@ -178,7 +178,8 @@
     private String getSecondaryLabel(boolean isActive, boolean isTransient,
             boolean isDataSaverEnabled, int numConnectedDevices, boolean isWifiTetheringAllowed) {
         if (!isWifiTetheringAllowed) {
-            return mContext.getString(R.string.wifitrackerlib_admin_restricted_network);
+            return mContext.getString(
+                    com.android.wifitrackerlib.R.string.wifitrackerlib_admin_restricted_network);
         } else if (isTransient) {
             return mContext.getString(R.string.quick_settings_hotspot_secondary_label_transient);
         } else if (isDataSaverEnabled) {
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/ScrollCaptureClient.java b/packages/SystemUI/src/com/android/systemui/screenshot/ScrollCaptureClient.java
index 93e5021..e93f737 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/ScrollCaptureClient.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/ScrollCaptureClient.java
@@ -365,6 +365,9 @@
         @Override
         public void onImageAvailable(ImageReader reader) {
             synchronized (mLock) {
+                if (mCapturedImage != null) {
+                    mCapturedImage.close();
+                }
                 mCapturedImage = mReader.acquireLatestImage();
                 if (mCapturedArea != null) {
                     completeCaptureRequest();
diff --git a/packages/SystemUI/src/com/android/systemui/settings/DisplayTracker.kt b/packages/SystemUI/src/com/android/systemui/settings/DisplayTracker.kt
index bb7f721..468a75d 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/DisplayTracker.kt
+++ b/packages/SystemUI/src/com/android/systemui/settings/DisplayTracker.kt
@@ -52,12 +52,12 @@
     interface Callback {
 
         /** Notifies that a display has been added. */
-        @JvmDefault fun onDisplayAdded(displayId: Int) {}
+        fun onDisplayAdded(displayId: Int) {}
 
         /** Notifies that a display has been removed. */
-        @JvmDefault fun onDisplayRemoved(displayId: Int) {}
+        fun onDisplayRemoved(displayId: Int) {}
 
         /** Notifies a display has been changed */
-        @JvmDefault fun onDisplayChanged(displayId: Int) {}
+        fun onDisplayChanged(displayId: Int) {}
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt b/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt
index 33a3125..93a3e90 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt
+++ b/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt
@@ -71,7 +71,6 @@
          * Same as {@link onUserChanging(Int, Context, CountDownLatch)} but the latch will be
          * auto-decremented after the completion of this method.
          */
-        @JvmDefault
         fun onUserChanging(newUser: Int, userContext: Context) {}
 
         /**
@@ -82,7 +81,6 @@
          * user switch duration. When overriding this method, countDown() MUST be called on the
          * latch once execution is complete.
          */
-        @JvmDefault
         fun onUserChanging(newUser: Int, userContext: Context, latch: CountDownLatch) {
             onUserChanging(newUser, userContext)
             latch.countDown()
@@ -93,13 +91,11 @@
          * Override this method to run things after the screen is unfrozen for the user switch.
          * Please see {@link #onUserChanging} if you need to hide jank.
          */
-        @JvmDefault
         fun onUserChanged(newUser: Int, userContext: Context) {}
 
         /**
          * Notifies that the current user's profiles have changed.
          */
-        @JvmDefault
         fun onProfilesChanged(profiles: List<@JvmSuppressWildcards UserInfo>) {}
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeStateEvents.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeStateEvents.kt
index 56bb1a6..5804040 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeStateEvents.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeStateEvents.kt
@@ -29,12 +29,12 @@
     interface ShadeStateEventsListener {
 
         /** Invoked when the notification panel starts or stops collapsing. */
-        @JvmDefault fun onPanelCollapsingChanged(isCollapsing: Boolean) {}
+        fun onPanelCollapsingChanged(isCollapsing: Boolean) {}
 
         /**
          * Invoked when the notification panel starts or stops launching an [android.app.Activity].
          */
-        @JvmDefault fun onLaunchingActivityChanged(isLaunchingActivity: Boolean) {}
+        fun onLaunchingActivityChanged(isLaunchingActivity: Boolean) {}
 
         /**
          * Invoked when the "expand immediate" attribute changes.
@@ -45,6 +45,6 @@
          * Another example is when full QS is showing, and we swipe up from the bottom. Instead of
          * going to QQS, the panel fully collapses.
          */
-        @JvmDefault fun onExpandImmediateChanged(isExpandImmediateEnabled: Boolean) {}
+        fun onExpandImmediateChanged(isExpandImmediateEnabled: Boolean) {}
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
index 8dc7842..a23e3f29 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
@@ -546,7 +546,6 @@
          */
         fun onWallpaperZoomOutChanged(zoomOut: Float)
 
-        @JvmDefault
         fun onBlurRadiusChanged(blurRadius: Int) {}
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/SignalCallback.kt b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/SignalCallback.kt
index 599beec..6be407a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/SignalCallback.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/SignalCallback.kt
@@ -29,7 +29,6 @@
      *
      * @param wifiIndicators a box type containing enough information to properly draw a Wi-Fi icon
      */
-    @JvmDefault
     fun setWifiIndicators(wifiIndicators: WifiIndicators) {}
 
     /**
@@ -42,7 +41,6 @@
      * NOTE: phones can have multiple subscriptions, so this [mobileDataIndicators] object should be
      * indexed based on its [subId][MobileDataIndicators.subId]
      */
-    @JvmDefault
     fun setMobileDataIndicators(mobileDataIndicators: MobileDataIndicators) {}
 
     /**
@@ -51,7 +49,6 @@
      *
      * @param subs a [SubscriptionInfo] for each subscription that we know about
      */
-    @JvmDefault
     fun setSubs(subs: List<@JvmSuppressWildcards SubscriptionInfo>) {}
 
     /**
@@ -63,7 +60,6 @@
      * @param show whether or not to show a "no sim" view
      * @param simDetected whether any SIM is detected or not
      */
-    @JvmDefault
     fun setNoSims(show: Boolean, simDetected: Boolean) {}
 
     /**
@@ -72,7 +68,6 @@
      *
      * @param icon an [IconState] for the current ethernet status
      */
-    @JvmDefault
     fun setEthernetIndicators(icon: IconState) {}
 
     /**
@@ -80,7 +75,6 @@
      *
      * @param icon an [IconState] for the current airplane mode status
      */
-    @JvmDefault
     fun setIsAirplaneMode(icon: IconState) {}
 
     /**
@@ -88,7 +82,6 @@
      *
      * @param enabled the current mobile data feature ennabled state
      */
-    @JvmDefault
     fun setMobileDataEnabled(enabled: Boolean) {}
 
     /**
@@ -97,7 +90,6 @@
      * @param noValidatedNetwork whether there is any validated network.
      * @param noNetworksAvailable whether there is any WiFi networks available.
      */
-    @JvmDefault
     fun setConnectivityStatus(
         noDefaultNetwork: Boolean,
         noValidatedNetwork: Boolean,
@@ -109,7 +101,6 @@
      * @param statusIcon the icon for the call indicator
      * @param subId subscription ID for which to update the UI
      */
-    @JvmDefault
     fun setCallIndicator(statusIcon: IconState, subId: Int) {}
 }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationScheduler.kt b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationScheduler.kt
index 2a18f1f..ef90890 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationScheduler.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationScheduler.kt
@@ -49,11 +49,10 @@
     fun onSystemEventAnimationFinish(hasPersistentDot: Boolean): Animator? { return null }
 
     // Best method name, change my mind
-    @JvmDefault
     fun onSystemStatusAnimationTransitionToPersistentDot(contentDescription: String?): Animator? {
         return null
     }
-    @JvmDefault fun onHidePersistentDot(): Animator? { return null }
+    fun onHidePersistentDot(): Animator? { return null }
 }
 
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
index 20af6ca..31a9f96 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationWakeUpCoordinator.kt
@@ -613,20 +613,20 @@
 
     interface WakeUpListener {
         /** Called whenever the notifications are fully hidden or shown */
-        @JvmDefault fun onFullyHiddenChanged(isFullyHidden: Boolean) {}
+        fun onFullyHiddenChanged(isFullyHidden: Boolean) {}
 
         /**
          * Called whenever the pulseExpansion changes
          *
          * @param expandingChanged if the user has started or stopped expanding
          */
-        @JvmDefault fun onPulseExpansionChanged(expandingChanged: Boolean) {}
+        fun onPulseExpansionChanged(expandingChanged: Boolean) {}
 
         /**
          * Called when the animator started by [scheduleDelayedDozeAmountAnimation] begins running
          * after the start delay, or after it ends/is cancelled.
          */
-        @JvmDefault fun onDelayedDozeAmountAnimationRunning(running: Boolean) {}
+        fun onDelayedDozeAmountAnimationRunning(running: Boolean) {}
     }
 
     companion object {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/OWNERS b/packages/SystemUI/src/com/android/systemui/statusbar/notification/OWNERS
index ed80f33..5558ab1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/OWNERS
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/OWNERS
@@ -2,13 +2,17 @@
 
 # Bug component: 78010
 
-aaliomer@google.com
+aioana@google.com
 aroederer@google.com
+iyz@google.com
 jeffdq@google.com
 juliacr@google.com
 juliatuttle@google.com
+kurucz@google.com
+liuyining@google.com
 lynhan@google.com
-steell@google.com
+matiashe@google.com
+valiiftime@google.com
 yurilin@google.com
 
 per-file MediaNotificationProcessor.java = ethibodeau@google.com, asc@google.com
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/Roundable.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/Roundable.kt
index 6deef2e..9675b43 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/Roundable.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/Roundable.kt
@@ -22,33 +22,27 @@
 
     /** Current top roundness */
     @get:FloatRange(from = 0.0, to = 1.0)
-    @JvmDefault
     val topRoundness: Float
         get() = roundableState.topRoundness
 
     /** Current bottom roundness */
     @get:FloatRange(from = 0.0, to = 1.0)
-    @JvmDefault
     val bottomRoundness: Float
         get() = roundableState.bottomRoundness
 
     /** Max radius in pixel */
-    @JvmDefault
     val maxRadius: Float
         get() = roundableState.maxRadius
 
     /** Current top corner in pixel, based on [topRoundness] and [maxRadius] */
-    @JvmDefault
     val topCornerRadius: Float
         get() = topRoundness * maxRadius
 
     /** Current bottom corner in pixel, based on [bottomRoundness] and [maxRadius] */
-    @JvmDefault
     val bottomCornerRadius: Float
         get() = bottomRoundness * maxRadius
 
     /** Get and update the current radii */
-    @JvmDefault
     val updatedRadii: FloatArray
         get() =
             roundableState.radiiBuffer.also { radii ->
@@ -71,7 +65,6 @@
      * @param sourceType the source from which the request for roundness comes.
      * @return Whether the roundness was changed.
      */
-    @JvmDefault
     fun requestTopRoundness(
         @FloatRange(from = 0.0, to = 1.0) value: Float,
         sourceType: SourceType,
@@ -116,7 +109,6 @@
      * @param sourceType the source from which the request for roundness comes.
      * @return Whether the roundness was changed.
      */
-    @JvmDefault
     fun requestTopRoundness(
         @FloatRange(from = 0.0, to = 1.0) value: Float,
         sourceType: SourceType,
@@ -140,7 +132,6 @@
      * @param sourceType the source from which the request for roundness comes.
      * @return Whether the roundness was changed.
      */
-    @JvmDefault
     fun requestBottomRoundness(
         @FloatRange(from = 0.0, to = 1.0) value: Float,
         sourceType: SourceType,
@@ -185,7 +176,6 @@
      * @param sourceType the source from which the request for roundness comes.
      * @return Whether the roundness was changed.
      */
-    @JvmDefault
     fun requestBottomRoundness(
         @FloatRange(from = 0.0, to = 1.0) value: Float,
         sourceType: SourceType,
@@ -210,7 +200,6 @@
      * @param animate true if it should animate to that value.
      * @return Whether the roundness was changed.
      */
-    @JvmDefault
     fun requestRoundness(
         @FloatRange(from = 0.0, to = 1.0) top: Float,
         @FloatRange(from = 0.0, to = 1.0) bottom: Float,
@@ -237,7 +226,6 @@
      * @param sourceType the source from which the request for roundness comes.
      * @return Whether the roundness was changed.
      */
-    @JvmDefault
     fun requestRoundness(
         @FloatRange(from = 0.0, to = 1.0) top: Float,
         @FloatRange(from = 0.0, to = 1.0) bottom: Float,
@@ -261,7 +249,6 @@
      * @param sourceType the source from which the request for roundness comes.
      * @param animate true if it should animate to that value.
      */
-    @JvmDefault
     fun requestRoundnessReset(sourceType: SourceType, animate: Boolean) {
         requestRoundness(top = 0f, bottom = 0f, sourceType = sourceType, animate = animate)
     }
@@ -275,19 +262,16 @@
      *
      * @param sourceType the source from which the request for roundness comes.
      */
-    @JvmDefault
     fun requestRoundnessReset(sourceType: SourceType) {
         requestRoundnessReset(sourceType = sourceType, animate = roundableState.targetView.isShown)
     }
 
     /** Apply the roundness changes, usually means invalidate the [RoundableState.targetView]. */
-    @JvmDefault
     fun applyRoundnessAndInvalidate() {
         roundableState.targetView.invalidate()
     }
 
     /** @return true if top or bottom roundness is not zero. */
-    @JvmDefault
     fun hasRoundedCorner(): Boolean {
         return topRoundness != 0f || bottomRoundness != 0f
     }
@@ -298,7 +282,6 @@
      *
      * This method reuses the previous [radii] for performance reasons.
      */
-    @JvmDefault
     fun updateRadii(
         topCornerRadius: Float,
         bottomCornerRadius: Float,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipelineChoreographer.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipelineChoreographer.kt
index 4ebf337..ad22c61 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipelineChoreographer.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotifPipelineChoreographer.kt
@@ -51,7 +51,7 @@
 object NotifPipelineChoreographerModule
 
 @Module
-private interface PrivateModule {
+interface PrivateModule {
     @Binds
     fun bindChoreographer(impl: NotifPipelineChoreographerImpl): NotifPipelineChoreographer
 }
@@ -59,7 +59,7 @@
 private const val TIMEOUT_MS: Long = 100
 
 @SysUISingleton
-private class NotifPipelineChoreographerImpl @Inject constructor(
+class NotifPipelineChoreographerImpl @Inject constructor(
     private val viewChoreographer: Choreographer,
     @Main private val executor: DelayableExecutor
 ) : NotifPipelineChoreographer {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt
index aeeeb4f..9ba1f7a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/SensitiveContentCoordinator.kt
@@ -38,7 +38,7 @@
 interface SensitiveContentCoordinatorModule
 
 @Module
-private interface PrivateSensitiveContentCoordinatorModule {
+interface PrivateSensitiveContentCoordinatorModule {
     @Binds
     fun bindCoordinator(impl: SensitiveContentCoordinatorImpl): SensitiveContentCoordinator
 }
@@ -47,7 +47,7 @@
 interface SensitiveContentCoordinator : Coordinator
 
 @CoordinatorScope
-private class SensitiveContentCoordinatorImpl @Inject constructor(
+class SensitiveContentCoordinatorImpl @Inject constructor(
     private val dynamicPrivacyController: DynamicPrivacyController,
     private val lockscreenUserManager: NotificationLockscreenUserManager,
     private val keyguardUpdateMonitor: KeyguardUpdateMonitor,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt
index 357c5b2..c00bb93 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/coordinator/dagger/CoordinatorsModule.kt
@@ -50,7 +50,7 @@
 @Module(includes = [
     SensitiveContentCoordinatorModule::class,
 ])
-private abstract class InternalCoordinatorsModule {
+abstract class InternalCoordinatorsModule {
     @Binds
     @Internal
     abstract fun bindNotifCoordinators(impl: NotifCoordinatorsImpl): NotifCoordinators
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/SectionHeaderController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/SectionHeaderController.kt
index 7b59266..49990d9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/SectionHeaderController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/render/SectionHeaderController.kt
@@ -38,7 +38,7 @@
 }
 
 @SectionHeaderScope
-internal class SectionHeaderNodeControllerImpl @Inject constructor(
+class SectionHeaderNodeControllerImpl @Inject constructor(
     @NodeLabel override val nodeLabel: String,
     private val layoutInflater: LayoutInflater,
     @HeaderText @StringRes private val headerTextResId: Int,
@@ -103,4 +103,4 @@
     override fun offerToKeepInParentForAnimation(): Boolean = false
     override fun removeFromParentIfKeptForAnimation(): Boolean = false
     override fun resetKeepInParentForAnimation() {}
-}
\ No newline at end of file
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt
index 2a9cfd0..75801a8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/dagger/NotificationSectionHeadersModule.kt
@@ -145,7 +145,7 @@
 }
 
 @Module
-private abstract class SectionHeaderBindingModule {
+abstract class SectionHeaderBindingModule {
     @Binds abstract fun bindsNodeController(impl: SectionHeaderNodeControllerImpl): NodeController
     @Binds abstract fun bindsSectionHeaderController(
         impl: SectionHeaderNodeControllerImpl
@@ -182,4 +182,4 @@
 
 @Scope
 @Retention(AnnotationRetention.BINARY)
-annotation class SectionHeaderScope
\ No newline at end of file
+annotation class SectionHeaderScope
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/KeyguardNotificationVisibilityProvider.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/KeyguardNotificationVisibilityProvider.kt
index 7513aa7..55ca0ab 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/KeyguardNotificationVisibilityProvider.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/interruption/KeyguardNotificationVisibilityProvider.kt
@@ -57,7 +57,7 @@
 object KeyguardNotificationVisibilityProviderModule
 
 @Module
-private interface KeyguardNotificationVisibilityProviderImplModule {
+interface KeyguardNotificationVisibilityProviderImplModule {
     @Binds
     fun bindImpl(impl: KeyguardNotificationVisibilityProviderImpl):
             KeyguardNotificationVisibilityProvider
@@ -69,7 +69,7 @@
 }
 
 @SysUISingleton
-private class KeyguardNotificationVisibilityProviderImpl @Inject constructor(
+class KeyguardNotificationVisibilityProviderImpl @Inject constructor(
     @Main private val handler: Handler,
     private val keyguardStateController: KeyguardStateController,
     private val lockscreenUserManager: NotificationLockscreenUserManager,
@@ -87,6 +87,7 @@
 
     private val userTrackerCallback = object : UserTracker.Callback {
         override fun onUserChanged(newUser: Int, userContext: Context) {
+            readShowSilentNotificationSetting()
             if (isLockedOrLocking) {
                 // maybe public mode changed
                 notifyStateChanged("onUserSwitched")
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
index 87d54a4..3130f7f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
@@ -1394,8 +1394,8 @@
         if (shouldShowBubbleButton(entry)) {
             // explicitly resolve drawable resource using SystemUI's theme
             Drawable d = mContext.getDrawable(entry.isBubble()
-                    ? R.drawable.bubble_ic_stop_bubble
-                    : R.drawable.bubble_ic_create_bubble);
+                    ? com.android.wm.shell.R.drawable.bubble_ic_stop_bubble
+                    : com.android.wm.shell.R.drawable.bubble_ic_create_bubble);
 
             String contentDescription = mContext.getResources().getString(entry.isBubble()
                     ? R.string.notification_conversation_unbubble
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DarkIconDispatcherImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DarkIconDispatcherImpl.java
index 2677c3f2..bb64beb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/DarkIconDispatcherImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/DarkIconDispatcherImpl.java
@@ -23,7 +23,6 @@
 import android.util.ArrayMap;
 import android.widget.ImageView;
 
-import com.android.systemui.R;
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dump.DumpManager;
 
@@ -54,8 +53,10 @@
             Context context,
             LightBarTransitionsController.Factory lightBarTransitionsControllerFactory,
             DumpManager dumpManager) {
-        mDarkModeIconColorSingleTone = context.getColor(R.color.dark_mode_icon_color_single_tone);
-        mLightModeIconColorSingleTone = context.getColor(R.color.light_mode_icon_color_single_tone);
+        mDarkModeIconColorSingleTone = context.getColor(
+                com.android.settingslib.R.color.dark_mode_icon_color_single_tone);
+        mLightModeIconColorSingleTone = context.getColor(
+                com.android.settingslib.R.color.light_mode_icon_color_single_tone);
 
         mTransitionsController = lightBarTransitionsControllerFactory.create(this);
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
index 13566ef..feace12 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
@@ -458,8 +458,9 @@
         @ColorInt int textColor = Utils.getColorAttrDefaultColor(mContext,
                 R.attr.wallpaperTextColor);
         @ColorInt int iconColor = Utils.getColorStateListDefaultColor(mContext,
-                Color.luminance(textColor) < 0.5 ? R.color.dark_mode_icon_color_single_tone :
-                R.color.light_mode_icon_color_single_tone);
+                Color.luminance(textColor) < 0.5
+                        ? com.android.settingslib.R.color.dark_mode_icon_color_single_tone
+                        : com.android.settingslib.R.color.light_mode_icon_color_single_tone);
         float intensity = textColor == Color.WHITE ? 0 : 1;
         mCarrierLabel.setTextColor(iconColor);
 
@@ -467,7 +468,7 @@
         if (userSwitcherName != null) {
             userSwitcherName.setTextColor(Utils.getColorStateListDefaultColor(
                     mContext,
-                    R.color.light_mode_icon_color_single_tone));
+                    com.android.settingslib.R.color.light_mode_icon_color_single_tone));
         }
 
         if (iconManager != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarController.java
index fe2a913..9a7be10 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LightBarController.java
@@ -32,7 +32,6 @@
 import com.android.internal.colorextraction.ColorExtractor.GradientColors;
 import com.android.internal.view.AppearanceRegion;
 import com.android.systemui.Dumpable;
-import com.android.systemui.R;
 import com.android.systemui.dagger.SysUISingleton;
 import com.android.systemui.dump.DumpManager;
 import com.android.systemui.navigationbar.NavigationModeController;
@@ -96,8 +95,10 @@
             NavigationModeController navModeController,
             DumpManager dumpManager,
             DisplayTracker displayTracker) {
-        mDarkIconColor = ctx.getColor(R.color.dark_mode_icon_color_single_tone);
-        mLightIconColor = ctx.getColor(R.color.light_mode_icon_color_single_tone);
+        mDarkIconColor = ctx.getColor(
+                com.android.settingslib.R.color.dark_mode_icon_color_single_tone);
+        mLightIconColor = ctx.getColor(
+                com.android.settingslib.R.color.light_mode_icon_color_single_tone);
         mStatusBarIconController = (SysuiDarkIconDispatcher) darkIconDispatcher;
         mBatteryController = batteryController;
         mBatteryController.addCallback(this);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java
index 924ae4a..92e1e4b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SystemUIDialog.java
@@ -415,7 +415,8 @@
         // We first look for the background on the dialogContentWithBackground added by
         // DialogLaunchAnimator. If it's not there, we use the background of the DecorView.
         View viewWithBackground = decorView.findViewByPredicate(
-                view -> view.getTag(R.id.tag_dialog_background) != null);
+                view -> view.getTag(
+                        com.android.systemui.animation.R.id.tag_dialog_background) != null);
         Drawable background = viewWithBackground != null ? viewWithBackground.getBackground()
                 : decorView.getBackground();
         Insets insets = background != null ? background.getOpticalInsets() : Insets.NONE;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardQsUserSwitchController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardQsUserSwitchController.java
index c8ee647..880e0d2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardQsUserSwitchController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardQsUserSwitchController.java
@@ -319,7 +319,7 @@
             drawable = new CircleFramedDrawable(mCurrentUser.picture, avatarSize);
         }
 
-        Drawable bg = mContext.getDrawable(R.drawable.user_avatar_bg);
+        Drawable bg = mContext.getDrawable(com.android.settingslib.R.drawable.user_avatar_bg);
         drawable = new LayerDrawable(new Drawable[]{bg, drawable});
         return drawable;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java
index f1269f2..f4cf4ef 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardStateControllerImpl.java
@@ -452,5 +452,10 @@
         public void onBiometricsCleared() {
             update(false /* alwaysUpdate */);
         }
+
+        @Override
+        public void onEnabledTrustAgentsChanged(int userId) {
+            update(false /* updateAlways */);
+        }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardUserSwitcherController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardUserSwitcherController.java
index e9f0dcb..9a6e71c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardUserSwitcherController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardUserSwitcherController.java
@@ -533,7 +533,7 @@
             }
             drawable.setTint(mResources.getColor(iconColorRes, mContext.getTheme()));
 
-            Drawable bg = mContext.getDrawable(R.drawable.user_avatar_bg);
+            Drawable bg = mContext.getDrawable(com.android.settingslib.R.drawable.user_avatar_bg);
             drawable = new LayerDrawable(new Drawable[]{bg, drawable});
             return drawable;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/RemoteInput.kt b/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/RemoteInput.kt
index d4abc40..d31c001 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/RemoteInput.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/dagger/RemoteInput.kt
@@ -41,7 +41,7 @@
 }
 
 @Module
-private interface InternalRemoteInputViewModule {
+interface InternalRemoteInputViewModule {
     @Binds
     fun bindController(impl: RemoteInputViewControllerImpl): RemoteInputViewController
 }
diff --git a/packages/SystemUI/src/com/android/systemui/touch/TouchInsetManager.java b/packages/SystemUI/src/com/android/systemui/touch/TouchInsetManager.java
index a4f1ef4f..ef0fa01 100644
--- a/packages/SystemUI/src/com/android/systemui/touch/TouchInsetManager.java
+++ b/packages/SystemUI/src/com/android/systemui/touch/TouchInsetManager.java
@@ -90,6 +90,9 @@
             final Region cumulativeRegion = Region.obtain();
 
             mTrackedViews.stream().forEach(view -> {
+                if (!view.isAttachedToWindow()) {
+                    return;
+                }
                 final Rect boundaries = new Rect();
                 view.getDrawingRect(boundaries);
                 ((ViewGroup) view.getRootView()).offsetDescendantRectToMyCoords(view, boundaries);
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/TunerActivity.java b/packages/SystemUI/src/com/android/systemui/tuner/TunerActivity.java
index 32ecb67..ecaf792 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/TunerActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/TunerActivity.java
@@ -61,7 +61,7 @@
 
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        setTheme(R.style.Theme_AppCompat_DayNight);
+        setTheme(androidx.appcompat.R.style.Theme_AppCompat_DayNight);
 
         getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
         requestWindowFeature(Window.FEATURE_NO_TITLE);
diff --git a/packages/SystemUI/src/com/android/systemui/user/domain/interactor/UserInteractor.kt b/packages/SystemUI/src/com/android/systemui/user/domain/interactor/UserInteractor.kt
index 667a3ca..83b272e 100644
--- a/packages/SystemUI/src/com/android/systemui/user/domain/interactor/UserInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/user/domain/interactor/UserInteractor.kt
@@ -747,7 +747,9 @@
         userId: Int,
     ): Drawable {
         if (isGuest) {
-            return checkNotNull(applicationContext.getDrawable(R.drawable.ic_account_circle))
+            return checkNotNull(
+                applicationContext.getDrawable(com.android.settingslib.R.drawable.ic_account_circle)
+            )
         }
 
         // TODO(b/246631653): cache the bitmaps to avoid the background work to fetch them.
diff --git a/packages/SystemUI/src/com/android/systemui/user/legacyhelper/ui/LegacyUserUiHelper.kt b/packages/SystemUI/src/com/android/systemui/user/legacyhelper/ui/LegacyUserUiHelper.kt
index e74232d..00ca92d 100644
--- a/packages/SystemUI/src/com/android/systemui/user/legacyhelper/ui/LegacyUserUiHelper.kt
+++ b/packages/SystemUI/src/com/android/systemui/user/legacyhelper/ui/LegacyUserUiHelper.kt
@@ -42,13 +42,13 @@
         isManageUsers: Boolean,
     ): Int {
         return if (isAddUser && isTablet) {
-            R.drawable.ic_account_circle_filled
+            com.android.settingslib.R.drawable.ic_account_circle_filled
         } else if (isAddUser) {
             R.drawable.ic_add
         } else if (isGuest) {
-            R.drawable.ic_account_circle
+            com.android.settingslib.R.drawable.ic_account_circle
         } else if (isAddSupervisedUser) {
-            R.drawable.ic_add_supervised_user
+            com.android.settingslib.R.drawable.ic_add_supervised_user
         } else if (isManageUsers) {
             R.drawable.ic_manage_users
         } else {
diff --git a/packages/SystemUI/src/com/android/systemui/user/ui/viewmodel/UserSwitcherViewModel.kt b/packages/SystemUI/src/com/android/systemui/user/ui/viewmodel/UserSwitcherViewModel.kt
index afd72e7..aeed5fc 100644
--- a/packages/SystemUI/src/com/android/systemui/user/ui/viewmodel/UserSwitcherViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/user/ui/viewmodel/UserSwitcherViewModel.kt
@@ -128,7 +128,7 @@
             viewKey = model.id,
             name =
                 if (model.isGuest && model.isSelected) {
-                    Text.Resource(R.string.guest_exit_quick_settings_button)
+                    Text.Resource(com.android.settingslib.R.string.guest_exit_quick_settings_button)
                 } else {
                     model.name
                 },
diff --git a/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java b/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java
index 2efeda9..904a98b 100644
--- a/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java
+++ b/packages/SystemUI/src/com/android/systemui/util/NotificationChannels.java
@@ -112,7 +112,7 @@
             // priority, so it can be shown in all times.
             nm.createNotificationChannel(new NotificationChannel(
                     TVPIP,
-                    context.getString(R.string.notification_channel_tv_pip),
+                    context.getString(com.android.wm.shell.R.string.notification_channel_tv_pip),
                     NotificationManager.IMPORTANCE_MAX));
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/util/UserAwareController.kt b/packages/SystemUI/src/com/android/systemui/util/UserAwareController.kt
index 693c270..5582ced 100644
--- a/packages/SystemUI/src/com/android/systemui/util/UserAwareController.kt
+++ b/packages/SystemUI/src/com/android/systemui/util/UserAwareController.kt
@@ -23,7 +23,6 @@
  * changes.
  */
 interface UserAwareController {
-    @JvmDefault
     fun changeUser(newUser: UserHandle) {}
 
     val currentUserId: Int
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
index 35cb834..cd0fc79 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
@@ -1747,8 +1747,10 @@
             if (!ss.dynamic) continue;
             mDynamic.put(stream, true);
             if (findRow(stream) == null) {
-                addRow(stream, R.drawable.ic_volume_remote, R.drawable.ic_volume_remote_mute, true,
-                        false, true);
+                addRow(stream,
+                        com.android.settingslib.R.drawable.ic_volume_remote,
+                        com.android.settingslib.R.drawable.ic_volume_remote_mute,
+                        true, false, true);
             }
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/wallet/ui/DotIndicatorDecoration.java b/packages/SystemUI/src/com/android/systemui/wallet/ui/DotIndicatorDecoration.java
index d2142dc..e5c55b0 100644
--- a/packages/SystemUI/src/com/android/systemui/wallet/ui/DotIndicatorDecoration.java
+++ b/packages/SystemUI/src/com/android/systemui/wallet/ui/DotIndicatorDecoration.java
@@ -48,8 +48,10 @@
                         R.dimen.card_carousel_dot_selected_radius);
         mDotMargin = context.getResources().getDimensionPixelSize(R.dimen.card_carousel_dot_margin);
 
-        mUnselectedColor = context.getColor(R.color.material_dynamic_neutral70);
-        mSelectedColor = context.getColor(R.color.material_dynamic_neutral100);
+        mUnselectedColor = context.getColor(
+                com.google.android.material.R.color.material_dynamic_neutral70);
+        mSelectedColor = context.getColor(
+                com.google.android.material.R.color.material_dynamic_neutral100);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletActivity.java b/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletActivity.java
index d03148c..2491e2b 100644
--- a/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/wallet/ui/WalletActivity.java
@@ -278,7 +278,7 @@
 
     private Drawable getHomeIndicatorDrawable() {
         Drawable drawable = getDrawable(R.drawable.ic_close);
-        drawable.setTint(getColor(R.color.material_dynamic_neutral70));
+        drawable.setTint(getColor(com.google.android.material.R.color.material_dynamic_neutral70));
         return drawable;
     }
 }
diff --git a/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java b/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java
index 0369d5b..ddc4e32 100644
--- a/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java
+++ b/packages/SystemUI/tests/src/com/android/AAAPlusPlusVerifySysuiRequiredTestPropertiesTest.java
@@ -131,7 +131,7 @@
         // with the main process dependency graph because it will not exist
         // at runtime and could lead to incorrect tests which assume
         // the main SystemUI process. Therefore, exclude this package
-        // from the base class whitelist.
+        // from the base class allowlist.
         filter.add(s -> !s.startsWith("com.android.systemui.screenshot"));
         return filter;
     }
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerTest.java
index b15ac39..82d3994 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardClockSwitchControllerTest.java
@@ -149,6 +149,9 @@
         when(mResources.getDimensionPixelSize(R.dimen.keyguard_large_clock_top_margin))
                 .thenReturn(-200);
 
+        when(mResources.getInteger(com.android.internal.R.integer.config_doublelineClockDefault))
+                .thenReturn(1);
+
         when(mView.findViewById(R.id.lockscreen_clock_view_large)).thenReturn(mLargeClockFrame);
         when(mView.findViewById(R.id.lockscreen_clock_view)).thenReturn(mSmallClockFrame);
         when(mSmallClockView.getContext()).thenReturn(getContext());
@@ -309,6 +312,7 @@
 
         // When a settings change has occurred to the small clock, make sure the view is adjusted
         reset(mView);
+        when(mView.getResources()).thenReturn(mResources);
         observer.onChange(true);
         mExecutor.runAllReady();
         verify(mView).switchToClock(KeyguardClockSwitch.SMALL, /* animate */ true);
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java
index d492758..3b3df23 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java
@@ -163,8 +163,6 @@
     @Captor
     private ArgumentCaptor<KeyguardSecurityContainer.SwipeListener> mSwipeListenerArgumentCaptor;
 
-    private Configuration mConfiguration;
-
     private KeyguardSecurityContainerController mKeyguardSecurityContainerController;
     private KeyguardPasswordViewController mKeyguardPasswordViewController;
     private KeyguardPasswordView mKeyguardPasswordView;
@@ -172,12 +170,12 @@
 
     @Before
     public void setup() {
-        mConfiguration = new Configuration();
-        mConfiguration.setToDefaults(); // Defaults to ORIENTATION_UNDEFINED.
         mTestableResources = mContext.getOrCreateTestableResources();
+        mTestableResources.getResources().getConfiguration().orientation =
+                Configuration.ORIENTATION_UNDEFINED;
 
         when(mView.getContext()).thenReturn(mContext);
-        when(mView.getResources()).thenReturn(mContext.getResources());
+        when(mView.getResources()).thenReturn(mTestableResources.getResources());
         FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(/* width=  */ 0, /* height= */
                 0);
         lp.gravity = 0;
@@ -254,6 +252,8 @@
 
     @Test
     public void onResourcesUpdate_callsThroughOnRotationChange() {
+        clearInvocations(mView);
+
         // Rotation is the same, shouldn't cause an update
         mKeyguardSecurityContainerController.updateResources();
         verify(mView, never()).initMode(eq(MODE_DEFAULT), eq(mGlobalSettings), eq(mFalsingManager),
@@ -579,12 +579,12 @@
         // Set initial gravity
         mTestableResources.addOverride(R.integer.keyguard_host_view_gravity,
                 Gravity.CENTER);
+        mTestableResources.addOverride(
+                R.bool.can_use_one_handed_bouncer, false);
 
         // Kick off the initial pass...
         mKeyguardSecurityContainerController.onInit();
-        verify(mView).setLayoutParams(argThat(
-                (ArgumentMatcher<FrameLayout.LayoutParams>) argument ->
-                        argument.gravity == Gravity.CENTER));
+        verify(mView).setLayoutParams(any());
         clearInvocations(mView);
 
         // Now simulate a config change
@@ -592,9 +592,7 @@
                 Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
 
         mKeyguardSecurityContainerController.updateResources();
-        verify(mView).setLayoutParams(argThat(
-                (ArgumentMatcher<FrameLayout.LayoutParams>) argument ->
-                        argument.gravity == (Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM)));
+        verify(mView).setLayoutParams(any());
     }
 
     @Test
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
index b1051af..417eb40 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardUpdateMonitorTest.java
@@ -144,6 +144,7 @@
 import java.util.Arrays;
 import java.util.List;
 import java.util.Optional;
+import java.util.Random;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -722,6 +723,18 @@
     }
 
     @Test
+    public void testOnEnabledTrustAgentsChangedCallback() {
+        final Random random = new Random();
+        final int userId = random.nextInt();
+        final KeyguardUpdateMonitorCallback callback = mock(KeyguardUpdateMonitorCallback.class);
+
+        mKeyguardUpdateMonitor.registerCallback(callback);
+        mKeyguardUpdateMonitor.onEnabledTrustAgentsChanged(userId);
+
+        verify(callback).onEnabledTrustAgentsChanged(eq(userId));
+    }
+
+    @Test
     public void trustAgentHasTrust_fingerprintLockout() {
         // GIVEN user has trust
         mKeyguardUpdateMonitor.onTrustChanged(true, true, getCurrentUser(), 0, null);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationAnimationControllerTest.java
index 21c3d6e..662dec8 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/accessibility/WindowMagnificationAnimationControllerTest.java
@@ -51,7 +51,6 @@
 
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Answers;
@@ -64,7 +63,6 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicReference;
 
-@Ignore
 @LargeTest
 @RunWith(AndroidTestingRunner.class)
 public class WindowMagnificationAnimationControllerTest extends SysuiTestCase {
@@ -72,8 +70,11 @@
     private static final float DEFAULT_SCALE = 4.0f;
     private static final float DEFAULT_CENTER_X = 400.0f;
     private static final float DEFAULT_CENTER_Y = 500.0f;
-    // The duration couldn't too short, otherwise the ValueAnimator won't work in expectation.
-    private static final long ANIMATION_DURATION_MS = 300;
+    // The duration and period can't be too short, otherwise the ValueAnimator and
+    //    Instrumentation.runOnMainSync won't work in expectation. (b/288926821)
+    private static final long ANIMATION_DURATION_MS = 600;
+    private static final long WAIT_FULL_ANIMATION_PERIOD = 1000;
+    private static final long WAIT_INTERMEDIATE_ANIMATION_PERIOD = 250;
 
     private AtomicReference<Float> mCurrentScale = new AtomicReference<>((float) 0);
     private AtomicReference<Float> mCurrentCenterX = new AtomicReference<>((float) 0);
@@ -113,8 +114,8 @@
         mWindowManager = spy(new TestableWindowManager(wm));
         mContext.addMockSystemService(Context.WINDOW_SERVICE, mWindowManager);
 
-        mWaitingAnimationPeriod = 2 * ANIMATION_DURATION_MS;
-        mWaitIntermediateAnimationPeriod = ANIMATION_DURATION_MS / 2;
+        mWaitingAnimationPeriod = WAIT_FULL_ANIMATION_PERIOD;
+        mWaitIntermediateAnimationPeriod = WAIT_INTERMEDIATE_ANIMATION_PERIOD;
         mWindowMagnificationAnimationController = new WindowMagnificationAnimationController(
                 mContext, newValueAnimator());
         mController = new SpyWindowMagnificationController(mContext, mHandler,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/animation/FontInterpolatorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/animation/FontInterpolatorTest.kt
index 8a5c5b5..57a355f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/animation/FontInterpolatorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/animation/FontInterpolatorTest.kt
@@ -106,4 +106,29 @@
         val reversedFont = interp.lerp(endFont, startFont, 0.5f)
         assertThat(resultFont).isSameInstanceAs(reversedFont)
     }
+
+    @Test
+    fun testCacheMaxSize() {
+        val interp = FontInterpolator()
+
+        val startFont = Font.Builder(sFont)
+                .setFontVariationSettings("'wght' 100")
+                .build()
+        val endFont = Font.Builder(sFont)
+                .setFontVariationSettings("'wght' 1")
+                .build()
+        val resultFont = interp.lerp(startFont, endFont, 0.5f)
+        for (i in 0..FONT_CACHE_MAX_ENTRIES + 1) {
+            val f1 = Font.Builder(sFont)
+                    .setFontVariationSettings("'wght' ${i * 100}")
+                    .build()
+            val f2 = Font.Builder(sFont)
+                    .setFontVariationSettings("'wght' $i")
+                    .build()
+            interp.lerp(f1, f2, 0.5f)
+        }
+
+        val cachedFont = interp.lerp(startFont, endFont, 0.5f)
+        assertThat(resultFont).isNotSameInstanceAs(cachedFont)
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStateControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStateControllerTest.java
index 34fa76f..d0c1c4d 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStateControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/dreams/DreamOverlayStateControllerTest.java
@@ -235,6 +235,23 @@
     }
 
     @Test
+    public void testComplicationsNotShownForLowLight() {
+        final Complication complication = Mockito.mock(Complication.class);
+        final DreamOverlayStateController stateController = getDreamOverlayStateController(true);
+
+        // Add a complication and verify it's returned in getComplications.
+        stateController.addComplication(complication);
+        mExecutor.runAllReady();
+        assertThat(stateController.getComplications().contains(complication))
+                .isTrue();
+
+        stateController.setLowLightActive(true);
+        mExecutor.runAllReady();
+
+        assertThat(stateController.getComplications()).isEmpty();
+    }
+
+    @Test
     public void testNotifyLowLightChanged() {
         final DreamOverlayStateController stateController = getDreamOverlayStateController(true);
 
@@ -336,6 +353,34 @@
         }
     }
 
+    @Test
+    public void testHomeControlsDoNotShowIfNotAvailable_featureEnabled() {
+        when(mFeatureFlags.isEnabled(Flags.ALWAYS_SHOW_HOME_CONTROLS_ON_DREAMS)).thenReturn(true);
+
+        final DreamOverlayStateController stateController = getDreamOverlayStateController(true);
+        stateController.setShouldShowComplications(true);
+
+        final Complication homeControlsComplication = Mockito.mock(Complication.class);
+        when(homeControlsComplication.getRequiredTypeAvailability())
+                .thenReturn(Complication.COMPLICATION_TYPE_HOME_CONTROLS);
+
+        stateController.addComplication(homeControlsComplication);
+
+        final DreamOverlayStateController.Callback callback =
+                Mockito.mock(DreamOverlayStateController.Callback.class);
+
+        stateController.addCallback(callback);
+        mExecutor.runAllReady();
+
+        // No home controls since it is not available.
+        assertThat(stateController.getComplications()).doesNotContain(homeControlsComplication);
+
+        stateController.setAvailableComplicationTypes(Complication.COMPLICATION_TYPE_HOME_CONTROLS
+                | Complication.COMPLICATION_TYPE_WEATHER);
+        mExecutor.runAllReady();
+        assertThat(stateController.getComplications()).contains(homeControlsComplication);
+    }
+
     private DreamOverlayStateController getDreamOverlayStateController(boolean overlayEnabled) {
         return new DreamOverlayStateController(mExecutor, overlayEnabled, mFeatureFlags);
     }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToLockscreenTransitionViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToLockscreenTransitionViewModelTest.kt
index 0c4e845..efa5f0c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToLockscreenTransitionViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/ui/viewmodel/OccludedToLockscreenTransitionViewModelTest.kt
@@ -92,6 +92,21 @@
             job.cancel()
         }
 
+    @Test
+    fun lockscreenTranslationYResettedAfterJobCancelled() =
+        runTest(UnconfinedTestDispatcher()) {
+            val values = mutableListOf<Float>()
+
+            val pixels = 100
+            val job =
+                underTest.lockscreenTranslationY(pixels).onEach { values.add(it) }.launchIn(this)
+            repository.sendTransitionStep(step(0.5f, TransitionState.CANCELED))
+
+            assertThat(values.last()).isEqualTo(0f)
+
+            job.cancel()
+        }
+
     private fun step(
         value: Float,
         state: TransitionState = TransitionState.RUNNING
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java
index 5e2fa98..1b75909 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/InflatedSmartRepliesTest.java
@@ -64,7 +64,7 @@
 public class InflatedSmartRepliesTest extends SysuiTestCase {
 
     private static final Intent TEST_INTENT = new Intent("com.android.SMART_REPLY_VIEW_ACTION");
-    private static final Intent WHITELISTED_TEST_INTENT =
+    private static final Intent ALLOWLISTED_TEST_INTENT =
             new Intent("com.android.WHITELISTED_TEST_ACTION");
 
     @Mock private SmartReplyConstants mSmartReplyConstants;
@@ -343,7 +343,7 @@
 
         assertThat(smartReplyState.getSmartReplies().choices)
                 .containsExactlyElementsIn(mEntry.getSmartReplies()).inOrder();
-        // Since no apps are whitelisted no actions should be shown.
+        // Since no apps are allowlisted no actions should be shown.
         assertThat(smartReplyState.getSmartActions().actions).isEmpty();
         assertThat(smartReplyState.getSuppressedActions()).isNull();
         assertThat(smartReplyState.getHasPhishingAction()).isFalse();
@@ -358,7 +358,7 @@
         allowedResolveInfo.activityInfo.packageName = allowedPackage;
         when(mPackageManagerWrapper
                 .resolveActivity(
-                        argThat(intent -> WHITELISTED_TEST_INTENT.getAction().equals(
+                        argThat(intent -> ALLOWLISTED_TEST_INTENT.getAction().equals(
                                 intent.getAction())),
                         anyInt() /* flags */))
                 .thenReturn(allowedResolveInfo);
@@ -368,7 +368,7 @@
         // suggestions.
         setupAppGeneratedReplies(null /* smartReplies */);
         ArrayList<Notification.Action> actions = new ArrayList<>();
-        actions.add(createAction("allowed action", WHITELISTED_TEST_INTENT));
+        actions.add(createAction("allowed action", ALLOWLISTED_TEST_INTENT));
         actions.add(createAction("non-allowed action", TEST_INTENT));
 
         modifyRanking(mEntry)
@@ -379,7 +379,7 @@
         InflatedSmartReplyState smartReplyState =
                 mSmartReplyStateInflater.chooseSmartRepliesAndActions(mEntry);
 
-        // Only the action for the whitelisted package should be allowed.
+        // Only the action for the allowlisted package should be allowed.
         assertThat(smartReplyState.getSmartActions().actions)
                 .containsExactly(mEntry.getSmartActions().get(0));
         assertThat(smartReplyState.getSuppressedActions()).isNull();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyguardStateControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyguardStateControllerTest.java
index 8f363ef..d787ada 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyguardStateControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/KeyguardStateControllerTest.java
@@ -31,18 +31,23 @@
 
 import com.android.internal.widget.LockPatternUtils;
 import com.android.keyguard.KeyguardUpdateMonitor;
+import com.android.keyguard.KeyguardUpdateMonitorCallback;
 import com.android.keyguard.logging.KeyguardUpdateMonitorLogger;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.dump.DumpManager;
 import com.android.systemui.keyguard.KeyguardUnlockAnimationController;
 
+import dagger.Lazy;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
-import dagger.Lazy;
+import java.util.Random;
+
 
 @SmallTest
 @TestableLooper.RunWithLooper
@@ -169,4 +174,19 @@
         verify(callback).onKeyguardDismissAmountChanged();
     }
 
+    @Test
+    public void testOnEnabledTrustAgentsChangedCallback() {
+        final Random random = new Random();
+        final ArgumentCaptor<KeyguardUpdateMonitorCallback> updateCallbackCaptor =
+                ArgumentCaptor.forClass(KeyguardUpdateMonitorCallback.class);
+
+        verify(mKeyguardUpdateMonitor).registerCallback(updateCallbackCaptor.capture());
+        final KeyguardStateController.Callback stateCallback =
+                mock(KeyguardStateController.Callback.class);
+        mKeyguardStateController.addCallback(stateCallback);
+
+        when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
+        updateCallbackCaptor.getValue().onEnabledTrustAgentsChanged(random.nextInt());
+        verify(stateCallback).onUnlockedChanged();
+    }
 }
diff --git a/packages/SystemUI/tests/src/com/android/systemui/user/domain/interactor/UserInteractorTest.kt b/packages/SystemUI/tests/src/com/android/systemui/user/domain/interactor/UserInteractorTest.kt
index e3b8649..9737759 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/user/domain/interactor/UserInteractorTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/user/domain/interactor/UserInteractorTest.kt
@@ -633,6 +633,7 @@
             val userInfos = createUserInfos(count = 2, includeGuest = false)
             userRepository.setUserInfos(userInfos)
             userRepository.setSelectedUserInfo(userInfos[0])
+            runCurrent()
             val refreshUsersCallCount = userRepository.refreshUsersCallCount
 
             fakeBroadcastDispatcher.registeredReceivers.forEach {
@@ -653,6 +654,7 @@
             val userInfos = createUserInfos(count = 2, includeGuest = false)
             userRepository.setUserInfos(userInfos)
             userRepository.setSelectedUserInfo(userInfos[0])
+            runCurrent()
             val refreshUsersCallCount = userRepository.refreshUsersCallCount
 
             fakeBroadcastDispatcher.registeredReceivers.forEach {
diff --git a/packages/SystemUI/unfold/Android.bp b/packages/SystemUI/unfold/Android.bp
index 2e0a946..1f0181f 100644
--- a/packages/SystemUI/unfold/Android.bp
+++ b/packages/SystemUI/unfold/Android.bp
@@ -33,7 +33,7 @@
         "dagger2",
         "jsr330",
     ],
-    kotlincflags: ["-Xjvm-default=enable"],
+    kotlincflags: ["-Xjvm-default=all"],
     java_version: "1.8",
     sdk_version: "current",
     min_sdk_version: "current",
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt
index fee485d..896444d 100644
--- a/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/UnfoldTransitionProgressProvider.kt
@@ -35,14 +35,12 @@
 
     interface TransitionProgressListener {
         /** Called when transition is started */
-        @JvmDefault
         fun onTransitionStarted() {}
 
         /**
          * Called whenever transition progress is updated, [progress] is a value of the animation
          * where 0 is fully folded, 1 is fully unfolded
          */
-        @JvmDefault
         fun onTransitionProgress(@FloatRange(from = 0.0, to = 1.0) progress: Float) {}
 
         /**
@@ -51,11 +49,9 @@
          * For example, in [PhysicsBasedUnfoldTransitionProgressProvider] this could happen when the
          * animation is not tied to the hinge angle anymore and it is about to run fixed animation.
          */
-        @JvmDefault
         fun onTransitionFinishing() {}
 
         /** Called when transition is completely finished */
-        @JvmDefault
         fun onTransitionFinished() {}
     }
 }
diff --git a/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldStateProvider.kt b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldStateProvider.kt
index 0af372f..bce7e88 100644
--- a/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldStateProvider.kt
+++ b/packages/SystemUI/unfold/src/com/android/systemui/unfold/updates/FoldStateProvider.kt
@@ -31,9 +31,9 @@
     val isFinishedOpening: Boolean
 
     interface FoldUpdatesListener {
-        @JvmDefault fun onHingeAngleUpdate(@FloatRange(from = 0.0, to = 180.0) angle: Float) {}
-        @JvmDefault fun onFoldUpdate(@FoldUpdate update: Int) {}
-        @JvmDefault fun onUnfoldedScreenAvailable() {}
+        fun onHingeAngleUpdate(@FloatRange(from = 0.0, to = 180.0) angle: Float) {}
+        fun onFoldUpdate(@FoldUpdate update: Int) {}
+        fun onUnfoldedScreenAvailable() {}
     }
 
     @IntDef(
diff --git a/packages/WAPPushManager/tests/src/com/android/smspush/unitTests/WapPushTest.java b/packages/WAPPushManager/tests/src/com/android/smspush/unitTests/WapPushTest.java
index b9dac4e..c7abed8 100644
--- a/packages/WAPPushManager/tests/src/com/android/smspush/unitTests/WapPushTest.java
+++ b/packages/WAPPushManager/tests/src/com/android/smspush/unitTests/WapPushTest.java
@@ -2237,10 +2237,6 @@
 
 
         mClassName = "com.android.smspush.unitTests.ReceiverActivity";
-        // Phone dummy = new DummyPhone(getContext());
-        // Phone gsm = PhoneFactory.getGsmPhone();
-        // GSMPhone gsm = new GSMPhone(getContext(), new SimulatedCommands(), null, true);
-        // WapPushOverSms dispatcher = new WapPushOverSms(dummy, null);
 
         try {
             // set up data
diff --git a/packages/WallpaperBackup/Android.bp b/packages/WallpaperBackup/Android.bp
index d142f25..840e99a 100644
--- a/packages/WallpaperBackup/Android.bp
+++ b/packages/WallpaperBackup/Android.bp
@@ -27,9 +27,6 @@
     name: "WallpaperBackup",
     defaults: ["platform_app_defaults"],
     srcs: ["src/**/*.java"],
-    optimize: {
-        proguard_flags_files: ["proguard.flags"],
-    },
     platform_apis: true,
     certificate: "platform",
     privileged: false,
diff --git a/packages/WallpaperBackup/proguard.flags b/packages/WallpaperBackup/proguard.flags
deleted file mode 100644
index 247e6ef..0000000
--- a/packages/WallpaperBackup/proguard.flags
+++ /dev/null
@@ -1 +0,0 @@
--keep class com.android.wallpaperbackup.WallpaperBackupAgent
diff --git a/packages/services/VirtualCamera/OWNERS b/packages/services/VirtualCamera/OWNERS
new file mode 100644
index 0000000..c66443f
--- /dev/null
+++ b/packages/services/VirtualCamera/OWNERS
@@ -0,0 +1,3 @@
+include /services/companion/java/com/android/server/companion/virtual/OWNERS
+caen@google.com
+jsebechlebsky@google.com
\ No newline at end of file
diff --git a/services/Android.bp b/services/Android.bp
index eb56c25..5b15392f 100644
--- a/services/Android.bp
+++ b/services/Android.bp
@@ -255,4 +255,5 @@
             tag: ".removed-api.txt",
         },
     ],
+    api_surface: "system-server",
 }
diff --git a/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java b/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
index 2cf0e3e..c80bed2 100644
--- a/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
+++ b/services/accessibility/java/com/android/server/accessibility/gestures/TouchExplorer.java
@@ -634,7 +634,7 @@
             MotionEvent event, MotionEvent rawEvent, int policyFlags) {
         switch (event.getActionMasked()) {
             case ACTION_DOWN:
-                // We should have already received ACTION_DOWN. Ignore.
+                handleActionDownStateTouchExploring(event, rawEvent, policyFlags);
                 break;
             case ACTION_POINTER_DOWN:
                 handleActionPointerDown(event, rawEvent, policyFlags);
@@ -840,6 +840,15 @@
         }
     }
 
+    private void handleActionDownStateTouchExploring(
+            MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+        // This is an interrupted and continued touch exploration. Maintain the consistency of the
+        // event stream.
+        mSendTouchExplorationEndDelayed.cancel();
+        mSendTouchInteractionEndDelayed.cancel();
+        sendTouchExplorationGestureStartAndHoverEnterIfNeeded(policyFlags);
+    }
+
     /**
      * Handles move events while touch exploring. this is also where we drag or delegate based on
      * the number of fingers moving on the screen.
@@ -1097,12 +1106,15 @@
     }
 
     /**
-     * Sends the enter events if needed. Such events are hover enter and touch explore
-     * gesture start.
+     * Sends the enter events if needed. Such events are hover enter and touch explore gesture
+     * start.
      *
      * @param policyFlags The policy flags associated with the event.
      */
     private void sendTouchExplorationGestureStartAndHoverEnterIfNeeded(int policyFlags) {
+        if (!mState.isTouchExploring()) {
+            mDispatcher.sendAccessibilityEvent(TYPE_TOUCH_EXPLORATION_GESTURE_START);
+        }
         MotionEvent event = mState.getLastInjectedHoverEvent();
         if (event != null && event.getActionMasked() == ACTION_HOVER_EXIT) {
             final int pointerIdBits = event.getPointerIdBits();
@@ -1115,7 +1127,6 @@
         }
     }
 
-
     /**
      * Determines whether a two pointer gesture is a dragging one.
      *
@@ -1341,6 +1352,8 @@
                 Slog.e(LOG_TAG, "Unable to find a valid pointer for touch exploration.");
                 return;
             }
+            // Send hover exit if we haven't closed a previous touch exploration event stream.
+            sendHoverExitAndTouchExplorationGestureEndIfNeeded(pointerId);
             final int pointerIdBits = (1 << pointerId);
             final int policyFlags = mState.getLastReceivedPolicyFlags();
             mSendHoverEnterAndMoveDelayed.setPointerIdBits(pointerIdBits);
diff --git a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
index 9d91b97..3714bed 100644
--- a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
+++ b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
@@ -3960,14 +3960,14 @@
                 mContext.enforceCallingOrSelfPermission(
                         android.Manifest.permission.BIND_APPWIDGET, null);
             } catch (SecurityException se) {
-                if (!isCallerBindAppWidgetWhiteListedLocked(packageName)) {
+                if (!isCallerBindAppWidgetAllowListedLocked(packageName)) {
                     return false;
                 }
             }
             return true;
         }
 
-        private boolean isCallerBindAppWidgetWhiteListedLocked(String packageName) {
+        private boolean isCallerBindAppWidgetAllowListedLocked(String packageName) {
             final int userId = UserHandle.getCallingUserId();
             final int packageUid = getUidForPackage(packageName, userId);
             if (packageUid < 0) {
diff --git a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
index 20b2a74..7b3c330 100644
--- a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
+++ b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
@@ -1351,7 +1351,7 @@
             Slog.v(TAG, "setAugmentedAutofillWhitelistLocked(packages=" + packages + ", activities="
                     + activities + ")");
         }
-        whitelistForAugmentedAutofillPackages(packages, activities);
+        allowlistForAugmentedAutofillPackages(packages, activities);
         final String serviceName;
         if (mRemoteAugmentedAutofillServiceInfo != null) {
             serviceName = mRemoteAugmentedAutofillServiceInfo.getComponentName()
@@ -1415,7 +1415,7 @@
     /**
      * @throws IllegalArgumentException if packages or components are empty.
      */
-    private void whitelistForAugmentedAutofillPackages(@Nullable List<String> packages,
+    private void allowlistForAugmentedAutofillPackages(@Nullable List<String> packages,
             @Nullable List<ComponentName> components) {
         // TODO(b/123100824): add CTS test for when it's null
         synchronized (mLock) {
diff --git a/services/backup/backuplib/java/com/android/server/backup/TransportManager.java b/services/backup/backuplib/java/com/android/server/backup/TransportManager.java
index 930f49e..ff5f509f 100644
--- a/services/backup/backuplib/java/com/android/server/backup/TransportManager.java
+++ b/services/backup/backuplib/java/com/android/server/backup/TransportManager.java
@@ -706,6 +706,9 @@
         try {
             String transportName = transport.name();
             String transportDirName = transport.transportDirName();
+            if (transportName == null || transportDirName == null) {
+                return BackupManager.ERROR_TRANSPORT_INVALID;
+            }
             registerTransport(transportComponent, transport);
             // If registerTransport() hasn't thrown...
             Slog.d(TAG, "Transport " + transportString + " registered");
diff --git a/services/companion/OWNERS b/services/companion/OWNERS
index 734d8b6..dcf2377 100644
--- a/services/companion/OWNERS
+++ b/services/companion/OWNERS
@@ -1 +1,3 @@
-include /core/java/android/companion/OWNERS
\ No newline at end of file
+include /core/java/android/companion/OWNERS
+
+per-file Android.bp,lint-baseline.xml,OWNERS=file:java/com/android/server/companion/virtual/OWNERS
\ No newline at end of file
diff --git a/services/companion/java/com/android/server/companion/virtual/OWNERS b/services/companion/java/com/android/server/companion/virtual/OWNERS
index 5e8291f..83143a4 100644
--- a/services/companion/java/com/android/server/companion/virtual/OWNERS
+++ b/services/companion/java/com/android/server/companion/virtual/OWNERS
@@ -2,4 +2,5 @@
 
 ogunwale@google.com
 michaelwr@google.com
-vladokom@google.com
\ No newline at end of file
+vladokom@google.com
+marvinramin@google.com
\ No newline at end of file
diff --git a/services/core/Android.bp b/services/core/Android.bp
index 81f600e..e687aa9 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -215,8 +215,7 @@
     name: "services.core.json.gz",
     srcs: [":checked-protolog.json"],
     out: ["services.core.protolog.json.gz"],
-    cmd: "$(location minigzip) -c < $(in) > $(out)",
-    tools: ["minigzip"],
+    cmd: "gzip -c < $(in) > $(out)",
 }
 
 prebuilt_etc {
diff --git a/services/core/java/com/android/server/CertBlacklister.java b/services/core/java/com/android/server/CertBlacklister.java
index c16378b..e726c6a 100644
--- a/services/core/java/com/android/server/CertBlacklister.java
+++ b/services/core/java/com/android/server/CertBlacklister.java
@@ -31,17 +31,17 @@
 import libcore.io.IoUtils;
 
 /**
- * <p>CertBlacklister provides a simple mechanism for updating the platform blacklists for SSL
+ * <p>CertBlacklister provides a simple mechanism for updating the platform denylists for SSL
  * certificate public keys and serial numbers.
  */
 public class CertBlacklister extends Binder {
 
     private static final String TAG = "CertBlacklister";
 
-    private static final String BLACKLIST_ROOT = System.getenv("ANDROID_DATA") + "/misc/keychain/";
+    private static final String DENYLIST_ROOT = System.getenv("ANDROID_DATA") + "/misc/keychain/";
 
-    public static final String PUBKEY_PATH = BLACKLIST_ROOT + "pubkey_blacklist.txt";
-    public static final String SERIAL_PATH = BLACKLIST_ROOT + "serial_blacklist.txt";
+    public static final String PUBKEY_PATH = DENYLIST_ROOT + "pubkey_blacklist.txt";
+    public static final String SERIAL_PATH = DENYLIST_ROOT + "serial_blacklist.txt";
 
     public static final String PUBKEY_BLACKLIST_KEY = "pubkey_blacklist";
     public static final String SERIAL_BLACKLIST_KEY = "serial_blacklist";
@@ -66,14 +66,14 @@
         @Override
         public void onChange(boolean selfChange) {
             super.onChange(selfChange);
-            writeBlacklist();
+            writeDenylist();
         }
 
         public String getValue() {
             return Settings.Secure.getString(mContentResolver, mKey);
         }
 
-        private void writeBlacklist() {
+        private void writeDenylist() {
             new Thread("BlacklistUpdater") {
                 public void run() {
                     synchronized(mTmpDir) {
diff --git a/services/core/java/com/android/server/ExplicitHealthCheckController.java b/services/core/java/com/android/server/ExplicitHealthCheckController.java
index 77059d9..81db70a 100644
--- a/services/core/java/com/android/server/ExplicitHealthCheckController.java
+++ b/services/core/java/com/android/server/ExplicitHealthCheckController.java
@@ -343,7 +343,7 @@
             };
 
             mContext.bindServiceAsUser(intent, mConnection,
-                    Context.BIND_AUTO_CREATE, UserHandle.of(UserHandle.USER_SYSTEM));
+                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM);
             Slog.i(TAG, "Explicit health check service is bound");
         }
     }
diff --git a/services/core/java/com/android/server/NetworkManagementService.java b/services/core/java/com/android/server/NetworkManagementService.java
index a027e04..1da368e 100644
--- a/services/core/java/com/android/server/NetworkManagementService.java
+++ b/services/core/java/com/android/server/NetworkManagementService.java
@@ -75,6 +75,7 @@
 import com.android.internal.app.IBatteryStats;
 import com.android.internal.util.DumpUtils;
 import com.android.internal.util.HexDump;
+import com.android.modules.utils.build.SdkLevel;
 import com.android.net.module.util.NetdUtils;
 import com.android.net.module.util.NetdUtils.ModifyOperation;
 import com.android.net.module.util.PermissionUtils;
@@ -779,7 +780,10 @@
     @Override
     public boolean getIpForwardingEnabled() throws IllegalStateException{
         PermissionUtils.enforceNetworkStackPermission(mContext);
-
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException(
+                    "NMS#getIpForwardingEnabled not supported in V+");
+        }
         try {
             return mNetdService.ipfwdEnabled();
         } catch (RemoteException | ServiceSpecificException e) {
@@ -790,6 +794,10 @@
     @Override
     public void setIpForwardingEnabled(boolean enable) {
         PermissionUtils.enforceNetworkStackPermission(mContext);
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException(
+                    "NMS#setIpForwardingEnabled not supported in V+");
+        }
         try {
             if (enable) {
                 mNetdService.ipfwdEnableForwarding("tethering");
@@ -804,6 +812,9 @@
     @Override
     public void startTethering(String[] dhcpRange) {
         PermissionUtils.enforceNetworkStackPermission(mContext);
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException("NMS#startTethering not supported in V+");
+        }
         try {
             NetdUtils.tetherStart(mNetdService, true /* usingLegacyDnsProxy */, dhcpRange);
         } catch (RemoteException | ServiceSpecificException e) {
@@ -814,6 +825,9 @@
     @Override
     public void stopTethering() {
         PermissionUtils.enforceNetworkStackPermission(mContext);
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException("NMS#stopTethering not supported in V+");
+        }
         try {
             mNetdService.tetherStop();
         } catch (RemoteException | ServiceSpecificException e) {
@@ -824,6 +838,9 @@
     @Override
     public boolean isTetheringStarted() {
         PermissionUtils.enforceNetworkStackPermission(mContext);
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException("NMS#isTetheringStarted not supported in V+");
+        }
         try {
             return mNetdService.tetherIsEnabled();
         } catch (RemoteException | ServiceSpecificException e) {
@@ -834,6 +851,9 @@
     @Override
     public void tetherInterface(String iface) {
         PermissionUtils.enforceNetworkStackPermission(mContext);
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException("NMS#tetherInterface not supported in V+");
+        }
         try {
             final LinkAddress addr = getInterfaceConfig(iface).getLinkAddress();
             final IpPrefix dest = new IpPrefix(addr.getAddress(), addr.getPrefixLength());
@@ -846,6 +866,9 @@
     @Override
     public void untetherInterface(String iface) {
         PermissionUtils.enforceNetworkStackPermission(mContext);
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException("NMS#untetherInterface not supported in V+");
+        }
         try {
             NetdUtils.untetherInterface(mNetdService, iface);
         } catch (RemoteException | ServiceSpecificException e) {
@@ -856,6 +879,10 @@
     @Override
     public String[] listTetheredInterfaces() {
         PermissionUtils.enforceNetworkStackPermission(mContext);
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException(
+                    "NMS#listTetheredInterfaces not supported in V+");
+        }
         try {
             return mNetdService.tetherInterfaceList();
         } catch (RemoteException | ServiceSpecificException e) {
@@ -866,6 +893,9 @@
     @Override
     public void enableNat(String internalInterface, String externalInterface) {
         PermissionUtils.enforceNetworkStackPermission(mContext);
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException("NMS#enableNat not supported in V+");
+        }
         try {
             mNetdService.tetherAddForward(internalInterface, externalInterface);
         } catch (RemoteException | ServiceSpecificException e) {
@@ -876,6 +906,9 @@
     @Override
     public void disableNat(String internalInterface, String externalInterface) {
         PermissionUtils.enforceNetworkStackPermission(mContext);
+        if (SdkLevel.isAtLeastV()) {
+            throw new UnsupportedOperationException("NMS#disableNat not supported in V+");
+        }
         try {
             mNetdService.tetherRemoveForward(internalInterface, externalInterface);
         } catch (RemoteException | ServiceSpecificException e) {
diff --git a/services/core/java/com/android/server/RescueParty.java b/services/core/java/com/android/server/RescueParty.java
index c1c9fbb..97f65dd 100644
--- a/services/core/java/com/android/server/RescueParty.java
+++ b/services/core/java/com/android/server/RescueParty.java
@@ -500,7 +500,8 @@
         Exception res = null;
         final ContentResolver resolver = context.getContentResolver();
         try {
-            Settings.Global.resetToDefaultsAsUser(resolver, null, mode, UserHandle.USER_SYSTEM);
+            Settings.Global.resetToDefaultsAsUser(resolver, null, mode,
+                UserHandle.SYSTEM.getIdentifier());
         } catch (Exception e) {
             res = new RuntimeException("Failed to reset global settings", e);
         }
@@ -741,12 +742,13 @@
     }
 
     private static int[] getAllUserIds() {
-        int[] userIds = { UserHandle.USER_SYSTEM };
+        int systemUserId = UserHandle.SYSTEM.getIdentifier();
+        int[] userIds = { systemUserId };
         try {
             for (File file : FileUtils.listFilesOrEmpty(Environment.getDataSystemDeDirectory())) {
                 try {
                     final int userId = Integer.parseInt(file.getName());
-                    if (userId != UserHandle.USER_SYSTEM) {
+                    if (userId != systemUserId) {
                         userIds = ArrayUtils.appendInt(userIds, userId);
                     }
                 } catch (NumberFormatException ignored) {
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index a3137a6..cb58855 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -266,17 +266,17 @@
 
         @Override
         public void onUserUnlocking(@NonNull TargetUser user) {
-            mStorageManagerService.onUnlockUser(user.getUserIdentifier());
+            mStorageManagerService.onUserUnlocking(user.getUserIdentifier());
         }
 
         @Override
         public void onUserStopped(@NonNull TargetUser user) {
-            mStorageManagerService.onCleanupUser(user.getUserIdentifier());
+            mStorageManagerService.onUserStopped(user.getUserIdentifier());
         }
 
         @Override
         public void onUserStopping(@NonNull TargetUser user) {
-            mStorageManagerService.onStopUser(user.getUserIdentifier());
+            mStorageManagerService.onUserStopping(user.getUserIdentifier());
         }
 
         @Override
@@ -736,6 +736,7 @@
     private static final int H_VOLUME_STATE_CHANGED = 15;
     private static final int H_CLOUD_MEDIA_PROVIDER_CHANGED = 16;
     private static final int H_SECURE_KEYGUARD_STATE_CHANGED = 17;
+    private static final int H_REMOUNT_VOLUMES_ON_MOVE = 18;
 
     class StorageManagerServiceHandler extends Handler {
         public StorageManagerServiceHandler(Looper looper) {
@@ -883,6 +884,10 @@
                     }
                     break;
                 }
+                case H_REMOUNT_VOLUMES_ON_MOVE: {
+                    remountVolumesForRunningUsersOnMove();
+                    break;
+                }
             }
         }
     }
@@ -1242,8 +1247,8 @@
         }
     }
 
-    private void onUnlockUser(int userId) {
-        Slog.d(TAG, "onUnlockUser " + userId);
+    private void onUserUnlocking(int userId) {
+        Slog.d(TAG, "onUserUnlocking " + userId);
 
         if (userId != UserHandle.USER_SYSTEM) {
             // Check if this user shares media with another user
@@ -1306,8 +1311,8 @@
         }
     }
 
-    private void onCleanupUser(int userId) {
-        Slog.d(TAG, "onCleanupUser " + userId);
+    private void onUserStopped(int userId) {
+        Slog.d(TAG, "onUserStopped " + userId);
 
         try {
             mVold.onUserStopped(userId);
@@ -1321,8 +1326,8 @@
         }
     }
 
-    private void onStopUser(int userId) {
-        Slog.i(TAG, "onStopUser " + userId);
+    private void onUserStopping(int userId) {
+        Slog.i(TAG, "onUserStopping " + userId);
         try {
             mStorageSessionController.onUserStopping(userId);
         } catch (Exception e) {
@@ -1357,11 +1362,74 @@
         }
     }
 
+    /**
+     * This method checks if the volume is public and the volume is visible and the volume it is
+     * trying to mount doesn't have the same mount user id as the current user being maintained by
+     * StorageManagerService and change the mount Id. The checks are same as
+     * {@link StorageManagerService#maybeRemountVolumes(int)}
+     * @param VolumeInfo object to consider for changing the mountId
+     */
+    private void updateVolumeMountIdIfRequired(VolumeInfo vol) {
+        synchronized (mLock) {
+            if (!vol.isPrimary() && vol.isVisible() && vol.getMountUserId() != mCurrentUserId) {
+                vol.mountUserId = mCurrentUserId;
+            }
+        }
+    }
+
+    /**
+     * This method informs vold and storaged that the user has stopped and started whenever move
+     * storage is performed. This ensures that the correct emulated volumes are mounted for the
+     * users other than the current user. This solves an edge case wherein the correct emulated
+     * volumes are not mounted, this will cause the media data to be still stored on internal
+     * storage whereas the data should be stored in the adopted primary storage. This method stops
+     * the users at vold first which will remove the old volumes which and starts the users at vold
+     * which will reattach the correct volumes. This does not performs a full reset as full reset
+     * clears every state from vold and SMS {@link #resetIfRebootedAndConnected} which is expensive
+     * and causes instability.
+     */
+    private void remountVolumesForRunningUsersOnMove() {
+        // Do not want to hold the lock for long
+        final List<Integer> unlockedUsers = new ArrayList<>();
+        synchronized (mLock) {
+            for (int userId : mSystemUnlockedUsers) {
+                if (userId == mCurrentUserId) continue;
+                unlockedUsers.add(userId);
+            }
+        }
+        for (Integer userId : unlockedUsers) {
+            try {
+                mVold.onUserStopped(userId);
+                mStoraged.onUserStopped(userId);
+            } catch (Exception e) {
+                Slog.wtf(TAG, e);
+            }
+        }
+        for (Integer userId : unlockedUsers) {
+            try {
+                mVold.onUserStarted(userId);
+                mStoraged.onUserStarted(userId);
+            } catch (Exception e) {
+                Slog.wtf(TAG, e);
+            }
+        }
+    }
+
     private boolean supportsBlockCheckpoint() throws RemoteException {
         enforcePermission(android.Manifest.permission.MOUNT_FORMAT_FILESYSTEMS);
         return mVold.supportsBlockCheckpoint();
     }
 
+    private void prepareUserStorageForMoveInternal(String fromVolumeUuid, String toVolumeUuid,
+            List<UserInfo> users) throws Exception {
+
+        final int flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
+        for (UserInfo user : users) {
+            prepareUserStorageInternal(fromVolumeUuid, user.id, user.serialNumber, flags);
+            prepareUserStorageInternal(toVolumeUuid, user.id, user.serialNumber, flags);
+        }
+    }
+
     @Override
     public void onAwakeStateChanged(boolean isAwake) {
         // Ignored
@@ -1468,13 +1536,14 @@
         }
 
         @Override
-        public void onVolumeStateChanged(String volId, final int newState) {
+        public void onVolumeStateChanged(String volId, final int newState, final int userId) {
             synchronized (mLock) {
                 final VolumeInfo vol = mVolumes.get(volId);
                 if (vol != null) {
                     final int oldState = vol.state;
                     vol.state = newState;
                     final VolumeInfo vInfo = new VolumeInfo(vol);
+                    vInfo.mountUserId = userId;
                     final SomeArgs args = SomeArgs.obtain();
                     args.arg1 = vInfo;
                     args.argi1 = oldState;
@@ -1719,6 +1788,23 @@
     }
 
     private void onVolumeStateChangedAsync(VolumeInfo vol, int oldState, int newState) {
+        if (newState == VolumeInfo.STATE_MOUNTED) {
+            // Private volumes can be unmounted and re-mounted even after a user has
+            // been unlocked; on devices that support encryption keys tied to the filesystem,
+            // this requires setting up the keys again.
+            try {
+                prepareUserStorageIfNeeded(vol);
+            } catch (Exception e) {
+                // Unusable partition, unmount.
+                try {
+                    mVold.unmount(vol.id);
+                } catch (Exception ee) {
+                    Slog.wtf(TAG, ee);
+                }
+                return;
+            }
+        }
+
         synchronized (mLock) {
             // Remember that we saw this volume so we're ready to accept user
             // metadata, or so we can annoy them when a private volume is ejected
@@ -1744,13 +1830,6 @@
             }
         }
 
-        if (newState == VolumeInfo.STATE_MOUNTED) {
-            // Private volumes can be unmounted and re-mounted even after a user has
-            // been unlocked; on devices that support encryption keys tied to the filesystem,
-            // this requires setting up the keys again.
-            prepareUserStorageIfNeeded(vol);
-        }
-
         // This is a blocking call to Storage Service which needs to process volume state changed
         // before notifying other listeners.
         // Intentionally called without the mLock to avoid deadlocking from the Storage Service.
@@ -1871,6 +1950,7 @@
 
             mPrimaryStorageUuid = mMoveTargetUuid;
             writeSettingsLocked();
+            mHandler.obtainMessage(H_REMOUNT_VOLUMES_ON_MOVE).sendToTarget();
         }
 
         if (PackageManager.isMoveStatusFinished(status)) {
@@ -2322,7 +2402,7 @@
         if (isMountDisallowed(vol)) {
             throw new SecurityException("Mounting " + volId + " restricted by policy");
         }
-
+        updateVolumeMountIdIfRequired(vol);
         mount(vol);
     }
 
@@ -2960,6 +3040,7 @@
 
         final VolumeInfo from;
         final VolumeInfo to;
+        final List<UserInfo> users;
 
         synchronized (mLock) {
             if (Objects.equals(mPrimaryStorageUuid, volumeUuid)) {
@@ -2973,7 +3054,7 @@
             mMoveTargetUuid = volumeUuid;
 
             // We need all the users unlocked to move their primary storage
-            final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
+            users = mContext.getSystemService(UserManager.class).getUsers();
             for (UserInfo user : users) {
                 if (StorageManager.isFileEncrypted() && !isUserKeyUnlocked(user.id)) {
                     Slog.w(TAG, "Failing move due to locked user " + user.id);
@@ -3009,6 +3090,19 @@
             }
         }
 
+        // Prepare the storage before move, this is required to unlock adoptable storage (as the
+        // keys are tied to prepare user data step) & also is required for the destination files to
+        // end up with the correct SELinux labels and encryption policies for directories
+        try {
+            prepareUserStorageForMoveInternal(mPrimaryStorageUuid, volumeUuid, users);
+        } catch (Exception e) {
+            Slog.w(TAG, "Failing move due to failure on prepare user data", e);
+            synchronized (mLock) {
+                onMoveStatusLocked(PackageManager.MOVE_FAILED_INTERNAL_ERROR);
+            }
+            return;
+        }
+
         try {
             mVold.moveStorage(from.id, to.id, new IVoldTaskListener.Stub() {
                 @Override
@@ -3339,7 +3433,7 @@
         }
     }
 
-    private void prepareUserStorageIfNeeded(VolumeInfo vol) {
+    private void prepareUserStorageIfNeeded(VolumeInfo vol) throws Exception {
         if (vol.type != VolumeInfo.TYPE_PRIVATE) {
             return;
         }
@@ -3366,11 +3460,15 @@
     public void prepareUserStorage(String volumeUuid, int userId, int serialNumber, int flags) {
         enforcePermission(android.Manifest.permission.STORAGE_INTERNAL);
 
-        prepareUserStorageInternal(volumeUuid, userId, serialNumber, flags);
+        try {
+            prepareUserStorageInternal(volumeUuid, userId, serialNumber, flags);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
     }
 
     private void prepareUserStorageInternal(String volumeUuid, int userId, int serialNumber,
-            int flags) {
+            int flags) throws Exception {
         try {
             mVold.prepareUserStorage(volumeUuid, userId, serialNumber, flags);
             // After preparing user storage, we should check if we should mount data mirror again,
@@ -3397,7 +3495,7 @@
                         + "; device may be insecure!");
                 return;
             }
-            throw new RuntimeException(e);
+            throw e;
         }
     }
 
@@ -4994,5 +5092,16 @@
             mCloudProviderChangeListeners.add(listener);
             mHandler.obtainMessage(H_CLOUD_MEDIA_PROVIDER_CHANGED, listener);
         }
+
+        @Override
+        public void prepareUserStorageForMove(String fromVolumeUuid, String toVolumeUuid,
+                List<UserInfo> users) {
+            try {
+                prepareUserStorageForMoveInternal(fromVolumeUuid, toVolumeUuid, users);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        }
+
     }
 }
diff --git a/services/core/java/com/android/server/TEST_MAPPING b/services/core/java/com/android/server/TEST_MAPPING
index 4b00aca..ada63c6 100644
--- a/services/core/java/com/android/server/TEST_MAPPING
+++ b/services/core/java/com/android/server/TEST_MAPPING
@@ -61,6 +61,15 @@
         {
             "name": "CtsVcnTestCases",
             "file_patterns": ["VcnManagementService\\.java"]
+        },
+        {
+            "name": "FrameworksNetTests",
+            "options": [
+                {
+                    "exclude-annotation": "com.android.testutils.SkipPresubmit"
+                }
+            ],
+            "file_patterns": ["VpnManagerService\\.java"]
         }
     ],
     "presubmit-large": [
@@ -78,6 +87,21 @@
                 }
             ],
             "file_patterns": ["ClipboardService\\.java"]
+        },
+        {
+            "name": "CtsHostsideNetworkTests",
+            "options": [
+                {
+                    "exclude-annotation": "androidx.test.filters.FlakyTest"
+                },
+                {
+                    "exclude-annotation": "android.platform.test.annotations.FlakyTest"
+                },
+                {
+                    "exclude-annotation": "com.android.testutils.SkipPresubmit"
+                }
+            ],
+            "file_patterns": ["VpnManagerService\\.java"]
         }
     ],
     "postsubmit": [
diff --git a/services/core/java/com/android/server/VcnManagementService.java b/services/core/java/com/android/server/VcnManagementService.java
index c6e9a7d..7acca19 100644
--- a/services/core/java/com/android/server/VcnManagementService.java
+++ b/services/core/java/com/android/server/VcnManagementService.java
@@ -456,7 +456,13 @@
         final List<SubscriptionInfo> subscriptionInfos = new ArrayList<>();
         Binder.withCleanCallingIdentity(
                 () -> {
-                    subscriptionInfos.addAll(subMgr.getSubscriptionsInGroup(subscriptionGroup));
+                    List<SubscriptionInfo> subsInGroup =
+                            subMgr.getSubscriptionsInGroup(subscriptionGroup);
+                    if (subsInGroup == null) {
+                        logWtf("Received null from getSubscriptionsInGroup");
+                        subsInGroup = Collections.emptyList();
+                    }
+                    subscriptionInfos.addAll(subsInGroup);
                 });
 
         for (SubscriptionInfo info : subscriptionInfos) {
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index 2a9dc52..f1bcb2b 100644
--- a/services/core/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/core/java/com/android/server/accounts/AccountManagerService.java
@@ -4854,7 +4854,6 @@
             if (accountType == null) throw new IllegalArgumentException("accountType is null");
             mAccounts = accounts;
             mStripAuthTokenFromResult = stripAuthTokenFromResult;
-            mResponse = response;
             mAccountType = accountType;
             mExpectActivityLaunch = expectActivityLaunch;
             mCreationTime = SystemClock.elapsedRealtime();
@@ -4868,8 +4867,8 @@
             if (response != null) {
                 try {
                     response.asBinder().linkToDeath(this, 0 /* flags */);
+                    mResponse = response;
                 } catch (RemoteException e) {
-                    mResponse = null;
                     binderDied();
                 }
             }
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index a5662ed..1d028c8 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -4201,21 +4201,6 @@
                         profile.addPss(mi.getTotalPss(),
                                 mi.getTotalUss(), mi.getTotalRss(), false,
                                 ProcessStats.ADD_PSS_EXTERNAL_SLOW, duration);
-                        proc.getPkgList().forEachPackageProcessStats(holder -> {
-                            final ProcessState state = holder.state;
-                            FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
-                                    proc.info.uid,
-                                    state != null ? state.getName() : proc.processName,
-                                    state != null ? state.getPackage() : proc.info.packageName,
-                                    mi.getTotalPss(),
-                                    mi.getTotalUss(),
-                                    mi.getTotalRss(),
-                                    ProcessStats.ADD_PSS_EXTERNAL_SLOW,
-                                    duration,
-                                    holder.appVersion,
-                                    profile.getCurrentHostingComponentTypes(),
-                                    profile.getHistoricalHostingComponentTypes());
-                        });
                     }
                 }
             }
@@ -4262,20 +4247,6 @@
                         // Record this for posterity if the process has been stable.
                         profile.addPss(pi, tmpUss[0], tmpUss[2], false,
                                 ProcessStats.ADD_PSS_EXTERNAL, duration);
-                        proc.getPkgList().forEachPackageProcessStats(holder -> {
-                            FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
-                                    proc.info.uid,
-                                    holder.state.getName(),
-                                    holder.state.getPackage(),
-                                    pi,
-                                    tmpUss[0],
-                                    tmpUss[2],
-                                    ProcessStats.ADD_PSS_EXTERNAL,
-                                    duration,
-                                    holder.appVersion,
-                                    profile.getCurrentHostingComponentTypes(),
-                                    profile.getHistoricalHostingComponentTypes());
-                        });
                     }
                 }
             }
@@ -5176,6 +5147,9 @@
             // Tell anyone interested that we are done booting!
             SystemProperties.set("sys.boot_completed", "1");
 
+            // Start PSI monitoring in LMKD if it was skipped earlier.
+            ProcessList.startPsiMonitoringAfterBoot();
+
             // And trigger dev.bootcomplete if we are not showing encryption progress
             if (!"trigger_restart_min_framework".equals(VoldProperties.decrypt().orElse(""))
                     || "".equals(VoldProperties.encrypt_progress().orElse(""))) {
@@ -11408,17 +11382,6 @@
                         // Record this for posterity if the process has been stable.
                         r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true,
                                 reportType, endTime - startTime);
-                        r.getPkgList().forEachPackageProcessStats(holder -> {
-                            FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
-                                    r.info.uid,
-                                    holder.state.getName(),
-                                    holder.state.getPackage(),
-                                    myTotalPss, myTotalUss, myTotalRss, reportType,
-                                    endTime-startTime,
-                                    holder.appVersion,
-                                    r.mProfile.getCurrentHostingComponentTypes(),
-                                    r.mProfile.getHistoricalHostingComponentTypes());
-                        });
                     }
                 }
 
@@ -12054,16 +12017,6 @@
                     // Record this for posterity if the process has been stable.
                     r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true,
                                 reportType, endTime - startTime);
-                    r.getPkgList().forEachPackageProcessStats(holder -> {
-                        FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
-                                r.info.uid,
-                                holder.state.getName(),
-                                holder.state.getPackage(),
-                                myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime,
-                                holder.appVersion,
-                                r.mProfile.getCurrentHostingComponentTypes(),
-                                r.mProfile.getHistoricalHostingComponentTypes());
-                    });
                 }
             }
 
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index 5d8c3b6..e3d31ad 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -658,37 +658,37 @@
                     out.println(
                             "Error: Activity not started, unable to "
                                     + "resolve " + intent.toString());
-                    break;
+                    return 1;
                 case ActivityManager.START_CLASS_NOT_FOUND:
                     out.println(NO_CLASS_ERROR_CODE);
                     out.println("Error: Activity class " +
                             intent.getComponent().toShortString()
                             + " does not exist.");
-                    break;
+                    return 1;
                 case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
                     out.println(
                             "Error: Activity not started, you requested to "
                                     + "both forward and receive its result");
-                    break;
+                    return 1;
                 case ActivityManager.START_PERMISSION_DENIED:
                     out.println(
                             "Error: Activity not started, you do not "
                                     + "have permission to access it.");
-                    break;
+                    return 1;
                 case ActivityManager.START_NOT_VOICE_COMPATIBLE:
                     out.println(
                             "Error: Activity not started, voice control not allowed for: "
                                     + intent);
-                    break;
+                    return 1;
                 case ActivityManager.START_NOT_CURRENT_USER_ACTIVITY:
                     out.println(
                             "Error: Not allowed to start background user activity"
                                     + " that shouldn't be displayed for all users.");
-                    break;
+                    return 1;
                 default:
                     out.println(
                             "Error: Activity not started, unknown error code " + res);
-                    break;
+                    return 1;
             }
             out.flush();
             if (mWaitOption && launched) {
diff --git a/services/core/java/com/android/server/am/AppProfiler.java b/services/core/java/com/android/server/am/AppProfiler.java
index 15efb7d..7c04a57 100644
--- a/services/core/java/com/android/server/am/AppProfiler.java
+++ b/services/core/java/com/android/server/am/AppProfiler.java
@@ -567,17 +567,6 @@
                 swapPss * 1024, rss * 1024, statType, procState, pssDuration);
         profile.setLastPssTime(now);
         profile.addPss(pss, uss, rss, true, statType, pssDuration);
-        proc.getPkgList().forEachPackageProcessStats(holder -> {
-            FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
-                    proc.info.uid,
-                    holder.state.getName(),
-                    holder.state.getPackage(),
-                    pss, uss, rss,
-                    statType, pssDuration,
-                    holder.appVersion,
-                    profile.getCurrentHostingComponentTypes(),
-                    profile.getHistoricalHostingComponentTypes());
-        });
         if (DEBUG_PSS) {
             Slog.d(TAG_PSS,
                     "pss of " + proc.toShortString() + ": " + pss
diff --git a/services/core/java/com/android/server/am/OWNERS b/services/core/java/com/android/server/am/OWNERS
index ef15beb..bf7cc10 100644
--- a/services/core/java/com/android/server/am/OWNERS
+++ b/services/core/java/com/android/server/am/OWNERS
@@ -32,7 +32,7 @@
 per-file *Assist* = file:/core/java/android/service/voice/OWNERS
 per-file *Voice* = file:/core/java/android/service/voice/OWNERS
 
-per-file SettingsToPropertiesMapper.java = omakoto@google.com, yamasani@google.com
+per-file SettingsToPropertiesMapper.java = omakoto@google.com, yamasani@google.com, dzshen@google.com, zhidou@google.com, tedbauer@google.com
 
 per-file CarUserSwitchingDialog.java = file:platform/packages/services/Car:/OWNERS
 
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index 5efaafe..3ed4df7 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -276,8 +276,8 @@
     // don't have an oom adj assigned by the system).
     public static final int NATIVE_ADJ = -1000;
 
-    // Memory pages are 4K.
-    static final int PAGE_SIZE = 4 * 1024;
+    // Memory page size.
+    static final int PAGE_SIZE = (int) Os.sysconf(OsConstants._SC_PAGESIZE);
 
     // Activity manager's version of Process.THREAD_GROUP_BACKGROUND
     static final int SCHED_GROUP_BACKGROUND = 0;
@@ -350,6 +350,7 @@
     static final byte LMK_UPDATE_PROPS = 7;
     static final byte LMK_KILL_OCCURRED = 8; // Msg to subscribed clients on kill occurred event
     static final byte LMK_STATE_CHANGED = 9; // Msg to subscribed clients on state changed
+    static final byte LMK_START_MONITORING = 9; // Start monitoring if delayed earlier
 
     // Low Memory Killer Daemon command codes.
     // These must be kept in sync with async_event_type definitions in lmkd.h
@@ -1483,6 +1484,15 @@
         return true;
     }
 
+    /**
+     * {@hide}
+     */
+    public static void startPsiMonitoringAfterBoot() {
+        ByteBuffer buf = ByteBuffer.allocate(4);
+        buf.putInt(LMK_START_MONITORING);
+        writeLmkd(buf, null);
+    }
+
     private static boolean writeLmkd(ByteBuffer buf, ByteBuffer repl) {
         if (!sLmkdConnection.isConnected()) {
             // try to connect immediately and then keep retrying
@@ -1741,6 +1751,7 @@
 
             if (debuggableFlag) {
                 runtimeFlags |= Zygote.DEBUG_ENABLE_JDWP;
+                runtimeFlags |= Zygote.DEBUG_ENABLE_PTRACE;
                 runtimeFlags |= Zygote.DEBUG_JAVA_DEBUGGABLE;
                 // Also turn on CheckJNI for debuggable apps. It's quite
                 // awkward to turn on otherwise.
diff --git a/services/core/java/com/android/server/audio/AudioDeviceBroker.java b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
index 3d0f487..1ad2420 100644
--- a/services/core/java/com/android/server/audio/AudioDeviceBroker.java
+++ b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
@@ -395,6 +395,20 @@
             mBtHelper.stopBluetoothSco(eventSource);
         }
 
+        // In BT classic for communication, the device changes from a2dp to sco device, but for
+        // LE Audio it stays the same and we must trigger the proper stream volume alignment, if
+        // LE Audio communication device is activated after the audio system has already switched to
+        // MODE_IN_CALL mode.
+        if (isBluetoothLeAudioRequested()) {
+            final int streamType = mAudioService.getBluetoothContextualVolumeStream();
+            final int leAudioVolIndex = getVssVolumeForDevice(streamType, device.getInternalType());
+            final int leAudioMaxVolIndex = getMaxVssVolumeForStream(streamType);
+            if (AudioService.DEBUG_COMM_RTE) {
+                Log.v(TAG, "setCommunicationRouteForClient restoring LE Audio device volume lvl.");
+            }
+            postSetLeAudioVolumeIndex(leAudioVolIndex, leAudioMaxVolIndex, streamType);
+        }
+
         sendLMsgNoDelay(MSG_L_UPDATE_COMMUNICATION_ROUTE, SENDMSG_QUEUE, eventSource);
     }
 
@@ -608,6 +622,16 @@
     }
 
     /**
+     * Helper method on top of isDeviceRequestedForCommunication() indicating if
+     * Bluetooth LE Audio communication device is currently requested or not.
+     * @return true if Bluetooth LE Audio device is requested, false otherwise.
+     */
+    /*package*/ boolean isBluetoothLeAudioRequested() {
+        return isDeviceRequestedForCommunication(AudioDeviceInfo.TYPE_BLE_HEADSET)
+                || isDeviceRequestedForCommunication(AudioDeviceInfo.TYPE_BLE_SPEAKER);
+    }
+
+    /**
      * Indicates if preferred route selection for communication is Bluetooth SCO.
      * @return true if Bluetooth SCO is preferred , false otherwise.
      */
@@ -1917,7 +1941,7 @@
         if (btSCoOn) {
             // Use the SCO device known to BtHelper so that it matches exactly
             // what has been communicated to audio policy manager. The device
-            // returned by requestedCommunicationDevice() can be a dummy SCO device if legacy
+            // returned by requestedCommunicationDevice() can be a placeholder SCO device if legacy
             // APIs are used to start SCO audio.
             AudioDeviceAttributes device = mBtHelper.getHeadsetAudioDevice();
             if (device != null) {
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index 47a98e8..7e9c253 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -146,6 +146,7 @@
 import android.os.RemoteCallbackList;
 import android.os.RemoteException;
 import android.os.ResultReceiver;
+import android.os.ServiceDebugInfo;
 import android.os.ServiceManager;
 import android.os.ShellCallback;
 import android.os.SystemClock;
@@ -2254,8 +2255,8 @@
                 synchronized (VolumeStreamState.class) {
                     mStreamStates[AudioSystem.STREAM_DTMF]
                             .setAllIndexes(mStreamStates[dtmfStreamAlias], caller);
-                    mStreamStates[AudioSystem.STREAM_ACCESSIBILITY].mVolumeIndexSettingName =
-                            System.VOLUME_SETTINGS_INT[a11yStreamAlias];
+                    mStreamStates[AudioSystem.STREAM_ACCESSIBILITY].setSettingName(
+                            System.VOLUME_SETTINGS_INT[a11yStreamAlias]);
                     mStreamStates[AudioSystem.STREAM_ACCESSIBILITY].setAllIndexes(
                             mStreamStates[a11yStreamAlias], caller);
                 }
@@ -3449,8 +3450,14 @@
                         hdmiClient = mHdmiTvClient;
                     }
 
-                    if (((mHdmiPlaybackClient != null && isFullVolumeDevice(device))
-                            || (mHdmiTvClient != null && mHdmiSystemAudioSupported))
+                    boolean playbackDeviceConditions = mHdmiPlaybackClient != null
+                            && isFullVolumeDevice(device);
+                    boolean tvConditions = mHdmiTvClient != null
+                            && mHdmiSystemAudioSupported
+                            && !isAbsoluteVolumeDevice(device)
+                            && !isA2dpAbsoluteVolumeDevice(device);
+
+                    if ((playbackDeviceConditions || tvConditions)
                             && mHdmiCecVolumeControlEnabled
                             && streamTypeAlias == AudioSystem.STREAM_MUSIC) {
                         int keyCode = KeyEvent.KEYCODE_UNKNOWN;
@@ -7512,7 +7519,7 @@
         private int mPublicStreamType = AudioSystem.STREAM_MUSIC;
         private AudioAttributes mAudioAttributes = AudioProductStrategy.getDefaultAttributes();
         private boolean mIsMuted = false;
-        private final String mSettingName;
+        private String mSettingName;
 
         // No API in AudioSystem to get a device from strategy or from attributes.
         // Need a valid public stream type to use current API getDeviceForStream
@@ -7841,15 +7848,19 @@
         }
 
         private void persistVolumeGroup(int device) {
-            if (mUseFixedVolume) {
+            // No need to persist the index if the volume group is backed up
+            // by a public stream type as this is redundant
+            if (mUseFixedVolume || mHasValidStreamType) {
                 return;
             }
             if (DEBUG_VOL) {
                 Log.v(TAG, "persistVolumeGroup: storing index " + getIndex(device) + " for group "
                         + mAudioVolumeGroup.name()
                         + ", device " + AudioSystem.getOutputDeviceName(device)
-                        + " and User=" + getCurrentUserId());
+                        + " and User=" + getCurrentUserId()
+                        + " mSettingName: " + mSettingName);
             }
+
             boolean success = mSettings.putSystemIntForUser(mContentResolver,
                     getSettingNameForDevice(device),
                     getIndex(device),
@@ -7912,6 +7923,14 @@
             return mSettingName + "_" + AudioSystem.getOutputDeviceName(device);
         }
 
+        void setSettingName(String settingName) {
+            mSettingName = settingName;
+        }
+
+        String getSettingName() {
+            return mSettingName;
+        }
+
         private void dump(PrintWriter pw) {
             pw.println("- VOLUME GROUP " + mAudioVolumeGroup.name() + ":");
             pw.print("   Muted: ");
@@ -8036,6 +8055,9 @@
          */
         public void setVolumeGroupState(VolumeGroupState volumeGroupState) {
             mVolumeGroupState = volumeGroupState;
+            if (mVolumeGroupState != null) {
+                mVolumeGroupState.setSettingName(mVolumeIndexSettingName);
+            }
         }
         /**
          * Update the minimum index that can be used without MODIFY_AUDIO_SETTINGS permission
@@ -8106,6 +8128,17 @@
             return (mVolumeIndexSettingName != null && !mVolumeIndexSettingName.isEmpty());
         }
 
+        void setSettingName(String settingName) {
+            mVolumeIndexSettingName = settingName;
+            if (mVolumeGroupState != null) {
+                mVolumeGroupState.setSettingName(mVolumeIndexSettingName);
+            }
+        }
+
+        String getSettingName() {
+            return mVolumeIndexSettingName;
+        }
+
         public void readSettings() {
             synchronized (mSettingsLock) {
                 synchronized (VolumeStreamState.class) {
@@ -8754,7 +8787,7 @@
             if (streamState.hasValidSettingsName()) {
                 mSettings.putSystemIntForUser(mContentResolver,
                         streamState.getSettingNameForDevice(device),
-                        (streamState.getIndex(device) + 5)/ 10,
+                        (streamState.getIndex(device) + 5) / 10,
                         UserHandle.USER_CURRENT);
             }
         }
@@ -12290,12 +12323,25 @@
 
     private static final String AUDIO_HAL_SERVICE_PREFIX = "android.hardware.audio";
 
-    private Set<Integer> getAudioHalPids() {
+    private void getAudioAidlHalPids(HashSet<Integer> pids) {
+        try {
+            ServiceDebugInfo[] infos = ServiceManager.getServiceDebugInfo();
+            if (infos == null) return;
+            for (ServiceDebugInfo info : infos) {
+                if (info.debugPid > 0 && info.name.startsWith(AUDIO_HAL_SERVICE_PREFIX)) {
+                    pids.add(info.debugPid);
+                }
+            }
+        } catch (RuntimeException e) {
+            // ignored, pid hashset does not change
+        }
+    }
+
+    private void getAudioHalHidlPids(HashSet<Integer> pids) {
         try {
             IServiceManager serviceManager = IServiceManager.getService();
             ArrayList<IServiceManager.InstanceDebugInfo> dump =
                     serviceManager.debugDump();
-            HashSet<Integer> pids = new HashSet<>();
             for (IServiceManager.InstanceDebugInfo info : dump) {
                 if (info.pid != IServiceManager.PidConstant.NO_PID
                         && info.interfaceName != null
@@ -12303,12 +12349,18 @@
                     pids.add(info.pid);
                 }
             }
-            return pids;
         } catch (RemoteException | RuntimeException e) {
-            return new HashSet<Integer>();
+            // ignored, pid hashset does not change
         }
     }
 
+    private Set<Integer> getAudioHalPids() {
+        HashSet<Integer> pids = new HashSet<>();
+        getAudioAidlHalPids(pids);
+        getAudioHalHidlPids(pids);
+        return pids;
+    }
+
     private void updateAudioHalPids() {
         Set<Integer> pidsSet = getAudioHalPids();
         if (pidsSet.isEmpty()) {
diff --git a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21UdfpsMock.java b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21UdfpsMock.java
index 846c2d9..a53d096 100644
--- a/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21UdfpsMock.java
+++ b/services/core/java/com/android/server/biometrics/sensors/fingerprint/hidl/Fingerprint21UdfpsMock.java
@@ -433,6 +433,11 @@
     }
 
     @Override
+    public void onEnabledTrustAgentsChanged(int userId) {
+
+    }
+
+    @Override
     @NonNull
     public List<FingerprintSensorPropertiesInternal> getSensorProperties() {
         final List<FingerprintSensorPropertiesInternal> properties = new ArrayList<>();
diff --git a/services/core/java/com/android/server/camera/CameraServiceProxy.java b/services/core/java/com/android/server/camera/CameraServiceProxy.java
index 5a3a3df..2f354b3 100644
--- a/services/core/java/com/android/server/camera/CameraServiceProxy.java
+++ b/services/core/java/com/android/server/camera/CameraServiceProxy.java
@@ -595,16 +595,26 @@
 
         @Override
         public boolean isCameraDisabled(int userId) {
-            DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
-            if (dpm == null) {
-                Slog.e(TAG, "Failed to get the device policy manager service");
+            if (Binder.getCallingUid() != Process.CAMERASERVER_UID) {
+                Slog.e(TAG, "Calling UID: " + Binder.getCallingUid()
+                        + " doesn't match expected camera service UID!");
                 return false;
             }
+            final long ident = Binder.clearCallingIdentity();
             try {
-                return dpm.getCameraDisabled(null, userId);
-            } catch (Exception e) {
-                e.printStackTrace();
-                return false;
+                DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
+                if (dpm == null) {
+                    Slog.e(TAG, "Failed to get the device policy manager service");
+                    return false;
+                }
+                try {
+                    return dpm.getCameraDisabled(null, userId);
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    return false;
+                }
+            } finally {
+                Binder.restoreCallingIdentity(ident);
             }
         }
     };
diff --git a/services/core/java/com/android/server/connectivity/OWNERS b/services/core/java/com/android/server/connectivity/OWNERS
index 62c5737..c24680e9 100644
--- a/services/core/java/com/android/server/connectivity/OWNERS
+++ b/services/core/java/com/android/server/connectivity/OWNERS
@@ -1,2 +1,2 @@
 set noparent
-file:platform/packages/modules/Connectivity:master:/OWNERS_core_networking
+file:platform/packages/modules/Connectivity:main:/OWNERS_core_networking
diff --git a/services/core/java/com/android/server/connectivity/TEST_MAPPING b/services/core/java/com/android/server/connectivity/TEST_MAPPING
new file mode 100644
index 0000000..687d4b0
--- /dev/null
+++ b/services/core/java/com/android/server/connectivity/TEST_MAPPING
@@ -0,0 +1,30 @@
+{
+  "presubmit": [
+      {
+          "name": "FrameworksNetTests",
+          "options": [
+              {
+                  "exclude-annotation": "com.android.testutils.SkipPresubmit"
+              }
+          ],
+          "file_patterns": ["Vpn\\.java", "VpnIkeV2Utils\\.java", "VpnProfileStore\\.java"]
+      }
+  ],
+  "presubmit-large": [
+      {
+          "name": "CtsHostsideNetworkTests",
+          "options": [
+              {
+                "exclude-annotation": "androidx.test.filters.FlakyTest"
+              },
+              {
+                "exclude-annotation": "android.platform.test.annotations.FlakyTest"
+              },
+              {
+                "exclude-annotation": "com.android.testutils.SkipPresubmit"
+              }
+          ],
+        "file_patterns": ["Vpn\\.java", "VpnIkeV2Utils\\.java", "VpnProfileStore\\.java"]
+      }
+  ]
+}
\ No newline at end of file
diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java
index 63bb026..53fbe8f 100644
--- a/services/core/java/com/android/server/connectivity/Vpn.java
+++ b/services/core/java/com/android/server/connectivity/Vpn.java
@@ -1741,6 +1741,7 @@
                 .setBypassableVpn(bypassable)
                 .setVpnRequiresValidation(mConfig.requiresInternetValidation)
                 .setLocalRoutesExcludedForVpn(mConfig.excludeLocalRoutes)
+                .setLegacyExtraInfo("VPN:" + mPackage)
                 .build();
 
         capsBuilder.setOwnerUid(mOwnerUID);
@@ -3066,7 +3067,8 @@
          * <p>This variable controls the retry delay, and is reset when the VPN pass network
          * validation.
          */
-        private int mValidationFailRetryCount = 0;
+        @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
+        int mValidationFailRetryCount = 0;
 
         /**
          * The number of attempts since the last successful connection.
@@ -3296,13 +3298,6 @@
                         }
                         agentConnect(this::onValidationStatus);
                         return; // Link properties are already sent.
-                    } else {
-                        // Underlying networks also set in agentConnect()
-                        doSetUnderlyingNetworks(networkAgent, Collections.singletonList(network));
-                        mNetworkCapabilities =
-                                new NetworkCapabilities.Builder(mNetworkCapabilities)
-                                        .setUnderlyingNetworks(Collections.singletonList(network))
-                                        .build();
                     }
 
                     lp = makeLinkProperties(); // Accesses VPN instance fields; must be locked
@@ -3346,7 +3341,7 @@
                 // Transforms do not need to be persisted; the IkeSession will keep
                 // them alive for us
                 mIpSecManager.applyTunnelModeTransform(mTunnelIface, direction, transform);
-            } catch (IOException e) {
+            } catch (IOException | IllegalArgumentException e) {
                 Log.d(TAG, "Transform application failed for token " + token, e);
                 onSessionLost(token, e);
             }
@@ -3384,8 +3379,6 @@
 
                     final LinkProperties oldLp = makeLinkProperties();
 
-                    final boolean underlyingNetworkHasChanged =
-                            !Arrays.equals(mConfig.underlyingNetworks, new Network[]{network});
                     mConfig.underlyingNetworks = new Network[] {network};
                     mConfig.mtu = calculateVpnMtu();
 
@@ -3417,18 +3410,9 @@
                                     removed.getAddress(), removed.getPrefixLength());
                         }
                     } else {
-                        // Put below 3 updates into else block is because agentConnect() will do
-                        // those things, so there is no need to do the redundant work.
+                        // Put below update into else block is because agentConnect() will do
+                        // the same things, so there is no need to do the redundant work.
                         if (!newLp.equals(oldLp)) doSendLinkProperties(mNetworkAgent, newLp);
-                        if (underlyingNetworkHasChanged) {
-                            mNetworkCapabilities =
-                                    new NetworkCapabilities.Builder(mNetworkCapabilities)
-                                            .setUnderlyingNetworks(
-                                                    Collections.singletonList(network))
-                                            .build();
-                            doSetUnderlyingNetworks(mNetworkAgent,
-                                    Collections.singletonList(network));
-                        }
                     }
                 }
 
@@ -3440,7 +3424,7 @@
                         mTunnelIface, IpSecManager.DIRECTION_IN, inTransform);
                 mIpSecManager.applyTunnelModeTransform(
                         mTunnelIface, IpSecManager.DIRECTION_OUT, outTransform);
-            } catch (IOException e) {
+            } catch (IOException | IllegalArgumentException e) {
                 Log.d(TAG, "Transform application failed for token " + token, e);
                 onSessionLost(token, e);
             }
@@ -3554,10 +3538,28 @@
          */
         private void startOrMigrateIkeSession(@Nullable Network underlyingNetwork) {
             if (underlyingNetwork == null) {
+                // For null underlyingNetwork case, there will not be a NetworkAgent available so
+                // no underlying network update is necessary here. Note that updating
+                // mNetworkCapabilities here would also be reasonable, but it will be updated next
+                // time the VPN connects anyway.
                 Log.d(TAG, "There is no active network for starting an IKE session");
                 return;
             }
 
+            final List<Network> networks = Collections.singletonList(underlyingNetwork);
+            // Update network capabilities if underlying network is changed.
+            if (!networks.equals(mNetworkCapabilities.getUnderlyingNetworks())) {
+                mNetworkCapabilities =
+                        new NetworkCapabilities.Builder(mNetworkCapabilities)
+                                .setUnderlyingNetworks(networks)
+                                .build();
+                // No NetworkAgent case happens when Vpn tries to start a new VPN. The underlying
+                // network update will be done later with NetworkAgent connected event.
+                if (mNetworkAgent != null) {
+                    doSetUnderlyingNetworks(mNetworkAgent, networks);
+                }
+            }
+
             if (maybeMigrateIkeSessionAndUpdateVpnTransportInfo(underlyingNetwork)) return;
 
             startIkeSession(underlyingNetwork);
@@ -3897,6 +3899,18 @@
                 // Skip other invalid status if the scheduled recovery exists.
                 if (mScheduledHandleDataStallFuture != null) return;
 
+                // Trigger network validation on the underlying network to possibly cause system
+                // switch default network or try recover if the current default network is broken.
+                //
+                // For the same underlying network, the first validation result should clarify if
+                // it's caused by broken underlying network. So only perform underlying network
+                // re-evaluation after first validation failure to prevent extra network resource
+                // costs on sending probes.
+                if (mValidationFailRetryCount == 0) {
+                    mConnectivityManager.reportNetworkConnectivity(
+                            mActiveNetwork, false /* hasConnectivity */);
+                }
+
                 if (mValidationFailRetryCount < MAX_MOBIKE_RECOVERY_ATTEMPT) {
                     Log.d(TAG, "Validation failed");
 
diff --git a/services/core/java/com/android/server/content/SyncManager.java b/services/core/java/com/android/server/content/SyncManager.java
index eb81e70..7df66e6 100644
--- a/services/core/java/com/android/server/content/SyncManager.java
+++ b/services/core/java/com/android/server/content/SyncManager.java
@@ -714,7 +714,7 @@
         // This can be noisy, therefore we will allowlist sync adapters installed
         // before we started checking for account access because they already know
         // the account (they run before) which is the genie is out of the bottle.
-        whiteListExistingSyncAdaptersIfNeeded();
+        allowListExistingSyncAdaptersIfNeeded();
 
         mLogger.log("Sync manager initialized: " + Build.FINGERPRINT);
     }
@@ -755,7 +755,7 @@
         }
     }
 
-    private void whiteListExistingSyncAdaptersIfNeeded() {
+    private void allowListExistingSyncAdaptersIfNeeded() {
         if (!mSyncStorageEngine.shouldGrantSyncAdaptersAccountAccess()) {
             return;
         }
diff --git a/services/core/java/com/android/server/content/SyncManagerConstants.java b/services/core/java/com/android/server/content/SyncManagerConstants.java
index 2a5858c..409b469 100644
--- a/services/core/java/com/android/server/content/SyncManagerConstants.java
+++ b/services/core/java/com/android/server/content/SyncManagerConstants.java
@@ -52,11 +52,11 @@
     private static final int DEF_MAX_RETRIES_WITH_APP_STANDBY_EXEMPTION = 5;
     private int mMaxRetriesWithAppStandbyExemption = DEF_MAX_RETRIES_WITH_APP_STANDBY_EXEMPTION;
 
-    private static final String KEY_EXEMPTION_TEMP_WHITELIST_DURATION_IN_SECONDS =
+    private static final String KEY_EXEMPTION_TEMP_ALLOWLIST_DURATION_IN_SECONDS =
             "exemption_temp_whitelist_duration_in_seconds";
-    private static final int DEF_EXEMPTION_TEMP_WHITELIST_DURATION_IN_SECONDS = 10 * 60;
+    private static final int DEF_EXEMPTION_TEMP_ALLOWLIST_DURATION_IN_SECONDS = 10 * 60;
     private int mKeyExemptionTempWhitelistDurationInSeconds
-            = DEF_EXEMPTION_TEMP_WHITELIST_DURATION_IN_SECONDS;
+            = DEF_EXEMPTION_TEMP_ALLOWLIST_DURATION_IN_SECONDS;
 
     protected SyncManagerConstants(Context context) {
         super(null);
@@ -105,8 +105,8 @@
                     DEF_MAX_RETRIES_WITH_APP_STANDBY_EXEMPTION);
 
             mKeyExemptionTempWhitelistDurationInSeconds = parser.getInt(
-                    KEY_EXEMPTION_TEMP_WHITELIST_DURATION_IN_SECONDS,
-                    DEF_EXEMPTION_TEMP_WHITELIST_DURATION_IN_SECONDS);
+                    KEY_EXEMPTION_TEMP_ALLOWLIST_DURATION_IN_SECONDS,
+                    DEF_EXEMPTION_TEMP_ALLOWLIST_DURATION_IN_SECONDS);
 
         }
     }
diff --git a/services/core/java/com/android/server/display/OWNERS b/services/core/java/com/android/server/display/OWNERS
index fcaa957..9439eaa 100644
--- a/services/core/java/com/android/server/display/OWNERS
+++ b/services/core/java/com/android/server/display/OWNERS
@@ -6,5 +6,6 @@
 flc@google.com
 wilczynskip@google.com
 brup@google.com
+petsjonkin@google.com
 
 per-file ColorDisplayService.java=christyfranks@google.com
diff --git a/services/core/java/com/android/server/display/WifiDisplayController.java b/services/core/java/com/android/server/display/WifiDisplayController.java
index cd36dd0..04ae13f 100644
--- a/services/core/java/com/android/server/display/WifiDisplayController.java
+++ b/services/core/java/com/android/server/display/WifiDisplayController.java
@@ -1062,8 +1062,10 @@
     }
 
     private static WifiDisplay createWifiDisplay(WifiP2pDevice device) {
+        WifiP2pWfdInfo wfdInfo = device.getWfdInfo();
+        boolean isSessionAvailable = wfdInfo != null && wfdInfo.isSessionAvailable();
         return new WifiDisplay(device.deviceAddress, device.deviceName, null,
-                true, device.getWfdInfo().isSessionAvailable(), false);
+                true, isSessionAvailable, false);
     }
 
     private final BroadcastReceiver mWifiP2pReceiver = new BroadcastReceiver() {
diff --git a/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
index 025ccd1..8d4eff9 100644
--- a/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
+++ b/services/core/java/com/android/server/integrity/AppIntegrityManagerServiceImpl.java
@@ -725,7 +725,7 @@
     }
 
     private String getCallingRulePusherPackageName(int callingUid) {
-        // Obtain the system apps that are whitelisted in config_integrityRuleProviderPackages.
+        // Obtain the system apps that are allowlisted in config_integrityRuleProviderPackages.
         List<String> allowedRuleProviders = getAllowedRuleProviderSystemApps();
         if (DEBUG_INTEGRITY_COMPONENT) {
             Slog.i(
diff --git a/services/core/java/com/android/server/location/gnss/GnssListenerMultiplexer.java b/services/core/java/com/android/server/location/gnss/GnssListenerMultiplexer.java
index a540476..ac762f5 100644
--- a/services/core/java/com/android/server/location/gnss/GnssListenerMultiplexer.java
+++ b/services/core/java/com/android/server/location/gnss/GnssListenerMultiplexer.java
@@ -189,10 +189,10 @@
             this::onProviderEnabledChanged;
     private final SettingsHelper.GlobalSettingChangedListener
             mBackgroundThrottlePackageWhitelistChangedListener =
-            this::onBackgroundThrottlePackageWhitelistChanged;
+            this::onBackgroundThrottlePackageAllowlistChanged;
     private final SettingsHelper.UserSettingChangedListener
             mLocationPackageBlacklistChangedListener =
-            this::onLocationPackageBlacklistChanged;
+            this::onLocationPackageDenylistChanged;
     private final LocationPermissionsHelper.LocationPermissionsListener
             mLocationPermissionsListener =
             new LocationPermissionsHelper.LocationPermissionsListener() {
@@ -382,11 +382,11 @@
         updateRegistrations(registration -> registration.getIdentity().getUserId() == userId);
     }
 
-    private void onBackgroundThrottlePackageWhitelistChanged() {
+    private void onBackgroundThrottlePackageAllowlistChanged() {
         updateRegistrations(registration -> true);
     }
 
-    private void onLocationPackageBlacklistChanged(int userId) {
+    private void onLocationPackageDenylistChanged(int userId) {
         updateRegistrations(registration -> registration.getIdentity().getUserId() == userId);
     }
 
diff --git a/services/core/java/com/android/server/location/injector/SettingsHelper.java b/services/core/java/com/android/server/location/injector/SettingsHelper.java
index 490bfe1..32cbff8 100644
--- a/services/core/java/com/android/server/location/injector/SettingsHelper.java
+++ b/services/core/java/com/android/server/location/injector/SettingsHelper.java
@@ -93,37 +93,37 @@
             GlobalSettingChangedListener listener);
 
     /**
-     * Check if the given package is blacklisted for location access.
+     * Check if the given package is denylisted for location access.
      */
     public abstract boolean isLocationPackageBlacklisted(int userId, String packageName);
 
     /**
-     * Add a listener for changes to the location package blacklist. Callbacks occur on an
+     * Add a listener for changes to the location package denylist. Callbacks occur on an
      * unspecified thread.
      */
     public abstract void addOnLocationPackageBlacklistChangedListener(
             UserSettingChangedListener listener);
 
     /**
-     * Remove a listener for changes to the location package blacklist.
+     * Remove a listener for changes to the location package denylist.
      */
     public abstract void removeOnLocationPackageBlacklistChangedListener(
             UserSettingChangedListener listener);
 
     /**
-     * Retrieve the background throttle package whitelist.
+     * Retrieve the background throttle package allowlist.
      */
     public abstract Set<String> getBackgroundThrottlePackageWhitelist();
 
     /**
-     * Add a listener for changes to the background throttle package whitelist. Callbacks occur on
+     * Add a listener for changes to the background throttle package allowlist. Callbacks occur on
      * an unspecified thread.
      */
     public abstract void addOnBackgroundThrottlePackageWhitelistChangedListener(
             GlobalSettingChangedListener listener);
 
     /**
-     * Remove a listener for changes to the background throttle package whitelist.
+     * Remove a listener for changes to the background throttle package allowlist.
      */
     public abstract void removeOnBackgroundThrottlePackageWhitelistChangedListener(
             GlobalSettingChangedListener listener);
@@ -134,14 +134,14 @@
     public abstract boolean isGnssMeasurementsFullTrackingEnabled();
 
     /**
-     * Add a listener for changes to the background throttle package whitelist. Callbacks occur on
+     * Add a listener for changes to the background throttle package allowlist. Callbacks occur on
      * an unspecified thread.
      */
     public abstract void addOnGnssMeasurementsFullTrackingEnabledChangedListener(
             GlobalSettingChangedListener listener);
 
     /**
-     * Remove a listener for changes to the background throttle package whitelist.
+     * Remove a listener for changes to the background throttle package allowlist.
      */
     public abstract void removeOnGnssMeasurementsFullTrackingEnabledChangedListener(
             GlobalSettingChangedListener listener);
@@ -166,14 +166,14 @@
     public abstract PackageTagsList getIgnoreSettingsAllowlist();
 
     /**
-     * Add a listener for changes to the ignore settings package whitelist. Callbacks occur on an
+     * Add a listener for changes to the ignore settings package allowlist. Callbacks occur on an
      * unspecified thread.
      */
     public abstract void addIgnoreSettingsAllowlistChangedListener(
             GlobalSettingChangedListener listener);
 
     /**
-     * Remove a listener for changes to the ignore settings package whitelist.
+     * Remove a listener for changes to the ignore settings package allowlist.
      */
     public abstract void removeIgnoreSettingsAllowlistChangedListener(
             GlobalSettingChangedListener listener);
diff --git a/services/core/java/com/android/server/location/injector/SystemSettingsHelper.java b/services/core/java/com/android/server/location/injector/SystemSettingsHelper.java
index 777683e..8bb184c 100644
--- a/services/core/java/com/android/server/location/injector/SystemSettingsHelper.java
+++ b/services/core/java/com/android/server/location/injector/SystemSettingsHelper.java
@@ -65,8 +65,8 @@
  */
 public class SystemSettingsHelper extends SettingsHelper {
 
-    private static final String LOCATION_PACKAGE_BLACKLIST = "locationPackagePrefixBlacklist";
-    private static final String LOCATION_PACKAGE_WHITELIST = "locationPackagePrefixWhitelist";
+    private static final String LOCATION_PACKAGE_DENYLIST = "locationPackagePrefixBlacklist";
+    private static final String LOCATION_PACKAGE_ALLOWLIST = "locationPackagePrefixWhitelist";
 
     private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000;
     private static final long DEFAULT_BACKGROUND_THROTTLE_PROXIMITY_ALERT_INTERVAL_MS =
@@ -93,9 +93,9 @@
         mGnssMeasurementFullTracking = new BooleanGlobalSetting(context,
                 ENABLE_GNSS_RAW_MEAS_FULL_TRACKING, FgThread.getHandler());
         mLocationPackageBlacklist = new StringListCachedSecureSetting(context,
-                LOCATION_PACKAGE_BLACKLIST, FgThread.getHandler());
+                LOCATION_PACKAGE_DENYLIST, FgThread.getHandler());
         mLocationPackageWhitelist = new StringListCachedSecureSetting(context,
-                LOCATION_PACKAGE_WHITELIST, FgThread.getHandler());
+                LOCATION_PACKAGE_ALLOWLIST, FgThread.getHandler());
         mBackgroundThrottlePackageWhitelist = new StringSetCachedGlobalSetting(context,
                 LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST,
                 () -> SystemConfig.getInstance().getAllowUnthrottledLocation(),
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index 489044f..af66bef 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -195,9 +195,40 @@
 import javax.crypto.spec.GCMParameterSpec;
 
 /**
- * Keeps the lock pattern/password data and related settings for each user. Used by
- * LockPatternUtils. Needs to be a service because Settings app also needs to be able to save
- * lockscreen information for secondary users.
+ * LockSettingsService (LSS) mainly has the following responsibilities:
+ * <p>
+ * <ul>
+ *   <li>Provide APIs to verify and change the Lock Screen Knowledge Factor (LSKF) ("lockscreen
+ *   credential") of each user.  Unlock users when their correct LSKF is given.</li>
+ *
+ *   <li>Store other lockscreen related settings, such as some Keyguard (UI) settings.</li>
+ *
+ *   <li>Manage each user's synthetic password (SP), which is their main cryptographic secret.
+ *   See {@link SyntheticPasswordManager}.</li>
+ *
+ *   <li>Protect each user's SP using their LSKF.  Use the Gatekeeper or Weaver HAL to ensure that
+ *   guesses of the LSKF are ratelimited by the TEE or secure element.</li>
+ *
+ *   <li>Protect each user's data using their SP.  For example, use the SP to encrypt/decrypt the
+ *   user's credential-encrypted (CE) key for file-based encryption (FBE).</li>
+ *
+ *   <li>Generate, protect, and use profile passwords for managed profiles.</li>
+ *
+ *   <li>Support unlocking the SP by alternative means: resume-on-reboot (reboot escrow) for easier
+ *   OTA updates, and escrow tokens when set up by the Device Policy Controller (DPC).</li>
+ *
+ *   <li>Implement part of the Factory Reset Protection (FRP) and Repair Mode features by storing
+ *   the information needed to verify a user's LSKF on the persist or metadata partition.</li>
+ *
+ *   <li>Support insider attack resistance using the AuthSecret HAL.</li>
+ *
+ *   <li>Implement "recoverable keystore", a feature that enables end-to-end encrypted backups.
+ *   See {@link android.security.keystore.recovery.RecoveryController}.</li>
+ * </ul>
+ * <p>
+ * The main clients of LockSettingsService are Keyguard (i.e. the lockscreen UI, which is part of
+ * System UI), the Settings app (com.android.settings), and other parts of system_server.  Most
+ * methods are protected by ACCESS_KEYGUARD_SECURE_STORAGE which only system processes can have.
  *
  * @hide
  */
@@ -1317,7 +1348,6 @@
         return getCredentialTypeInternal(userId);
     }
 
-    // TODO: this is a hot path, can we optimize it?
     /**
      * Returns the credential type of the user, can be one of {@link #CREDENTIAL_TYPE_NONE},
      * {@link #CREDENTIAL_TYPE_PATTERN}, {@link #CREDENTIAL_TYPE_PIN} and
diff --git a/services/core/java/com/android/server/locksettings/OWNERS b/services/core/java/com/android/server/locksettings/OWNERS
index 55b0cff..5d49863 100644
--- a/services/core/java/com/android/server/locksettings/OWNERS
+++ b/services/core/java/com/android/server/locksettings/OWNERS
@@ -1,3 +1,4 @@
+# Bug component: 1333694
 ebiggers@google.com
 jaggies@google.com
 rubinxu@google.com
diff --git a/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java b/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java
index 3f66fee..f27b913 100644
--- a/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java
+++ b/services/core/java/com/android/server/locksettings/SyntheticPasswordManager.java
@@ -1327,8 +1327,10 @@
             }
             return result;
         } else if (responseCode == GateKeeperResponse.RESPONSE_RETRY) {
+            Slog.e(TAG, "Gatekeeper verification of synthetic password failed with RESPONSE_RETRY");
             return VerifyCredentialResponse.fromTimeout(response.getTimeout());
         } else {
+            Slog.e(TAG, "Gatekeeper verification of synthetic password failed with RESPONSE_ERROR");
             return VerifyCredentialResponse.ERROR;
         }
     }
diff --git a/services/core/java/com/android/server/logcat/LogcatManagerService.java b/services/core/java/com/android/server/logcat/LogcatManagerService.java
index 43732d4..25c939e 100644
--- a/services/core/java/com/android/server/logcat/LogcatManagerService.java
+++ b/services/core/java/com/android/server/logcat/LogcatManagerService.java
@@ -27,6 +27,7 @@
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.os.Build;
+import android.os.DeadObjectException;
 import android.os.Handler;
 import android.os.ILogd;
 import android.os.Looper;
@@ -514,7 +515,15 @@
             Slog.d(TAG, "Approving log access: " + request);
         }
         try {
-            getLogdService().approve(request.mUid, request.mGid, request.mPid, request.mFd);
+            try {
+                getLogdService().approve(request.mUid, request.mGid, request.mPid, request.mFd);
+            } catch (DeadObjectException e) {
+                // This can happen if logd restarts, so force getting a new connection
+                // to logd and try once more.
+                Slog.w(TAG, "Logd connection no longer valid while approving, trying once more.");
+                mLogdService = null;
+                getLogdService().approve(request.mUid, request.mGid, request.mPid, request.mFd);
+            }
             Integer activeCount = mActiveLogAccessCount.getOrDefault(client, 0);
             mActiveLogAccessCount.put(client, activeCount + 1);
         } catch (RemoteException e) {
@@ -527,7 +536,15 @@
             Slog.d(TAG, "Declining log access: " + request);
         }
         try {
-            getLogdService().decline(request.mUid, request.mGid, request.mPid, request.mFd);
+            try {
+                getLogdService().decline(request.mUid, request.mGid, request.mPid, request.mFd);
+            } catch (DeadObjectException e) {
+                // This can happen if logd restarts, so force getting a new connection
+                // to logd and try once more.
+                Slog.w(TAG, "Logd connection no longer valid while declining, trying once more.");
+                mLogdService = null;
+                getLogdService().decline(request.mUid, request.mGid, request.mPid, request.mFd);
+            }
         } catch (RemoteException e) {
             Slog.e(TAG, "Fails to call remote functions", e);
         }
diff --git a/services/core/java/com/android/server/net/NetworkPolicyLogger.java b/services/core/java/com/android/server/net/NetworkPolicyLogger.java
index dc8fcb0..85731651 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyLogger.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyLogger.java
@@ -338,8 +338,8 @@
         return "App idle state of uid " + uid + ": " + idle;
     }
 
-    private static String getAppIdleWlChangedLog(int uid, boolean isWhitelisted) {
-        return "App idle whitelist state of uid " + uid + ": " + isWhitelisted;
+    private static String getAppIdleWlChangedLog(int uid, boolean isAllowlisted) {
+        return "App idle whitelist state of uid " + uid + ": " + isAllowlisted;
     }
 
     private static String getParoleStateChanged(boolean paroleOn) {
@@ -519,14 +519,14 @@
             data.timeStamp = System.currentTimeMillis();
         }
 
-        public void appIdleWlChanged(int uid, boolean isWhitelisted) {
+        public void appIdleWlChanged(int uid, boolean isAllowlisted) {
             final Data data = getNextSlot();
             if (data == null) return;
 
             data.reset();
             data.type = EVENT_APP_IDLE_WL_CHANGED;
             data.ifield1 = uid;
-            data.bfield1 = isWhitelisted;
+            data.bfield1 = isAllowlisted;
             data.timeStamp = System.currentTimeMillis();
         }
 
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
index d285337..6eaf24a 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -362,7 +362,7 @@
     private static final String TAG_NETWORK_POLICY = "network-policy";
     private static final String TAG_UID_POLICY = "uid-policy";
     private static final String TAG_APP_POLICY = "app-policy";
-    private static final String TAG_WHITELIST = "whitelist";
+    private static final String TAG_ALLOWLIST = "whitelist";
     private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
     private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
     private static final String TAG_XML_UTILS_INT_ARRAY = "int-array";
@@ -856,7 +856,7 @@
     }
 
     @GuardedBy("mUidRulesFirstLock")
-    private void updatePowerSaveWhitelistUL() {
+    private void updatePowerSaveAllowlistUL() {
         int[] whitelist = mPowerWhitelistManager.getWhitelistedAppIds(/* includingIdle */ false);
         mPowerSaveWhitelistExceptIdleAppIds.clear();
         for (int uid : whitelist) {
@@ -947,7 +947,7 @@
 
             synchronized (mUidRulesFirstLock) {
                 synchronized (mNetworkPoliciesSecondLock) {
-                    updatePowerSaveWhitelistUL();
+                    updatePowerSaveAllowlistUL();
                     mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
                     mPowerManagerInternal.registerLowPowerModeObserver(
                             new PowerManagerInternal.LowPowerModeListener() {
@@ -1189,7 +1189,7 @@
         public void onReceive(Context context, Intent intent) {
             // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
             synchronized (mUidRulesFirstLock) {
-                updatePowerSaveWhitelistUL();
+                updatePowerSaveAllowlistUL();
                 updateRulesForRestrictPowerUL();
                 updateRulesForAppIdleUL();
             }
@@ -2679,7 +2679,7 @@
                         } else {
                             Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
                         }
-                    } else if (TAG_WHITELIST.equals(tag)) {
+                    } else if (TAG_ALLOWLIST.equals(tag)) {
                         insideAllowlist = true;
                     } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideAllowlist) {
                         final int uid = readIntAttribute(in, ATTR_UID);
@@ -2689,7 +2689,7 @@
                         mRestrictBackgroundAllowlistRevokedUids.put(uid, true);
                     }
                 } else if (type == END_TAG) {
-                    if (TAG_WHITELIST.equals(tag)) {
+                    if (TAG_ALLOWLIST.equals(tag)) {
                         insideAllowlist = false;
                     }
 
@@ -2865,7 +2865,7 @@
             out.endTag(null, TAG_POLICY_LIST);
 
             // write all allowlists
-            out.startTag(null, TAG_WHITELIST);
+            out.startTag(null, TAG_ALLOWLIST);
 
             // revoked restrict background allowlist
             int size = mRestrictBackgroundAllowlistRevokedUids.size();
@@ -2876,7 +2876,7 @@
                 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
             }
 
-            out.endTag(null, TAG_WHITELIST);
+            out.endTag(null, TAG_ALLOWLIST);
 
             out.endDocument();
 
@@ -4356,7 +4356,7 @@
     void updateRulesForPowerSaveUL() {
         Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
         try {
-            updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
+            updateRulesForAllowlistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
                     mUidFirewallPowerSaveRules);
         } finally {
             Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
@@ -4365,14 +4365,14 @@
 
     @GuardedBy("mUidRulesFirstLock")
     void updateRuleForRestrictPowerUL(int uid) {
-        updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
+        updateRulesForAllowlistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
     }
 
     @GuardedBy("mUidRulesFirstLock")
     void updateRulesForDeviceIdleUL() {
         Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
         try {
-            updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
+            updateRulesForAllowlistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
                     mUidFirewallDozableRules);
         } finally {
             Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
@@ -4381,26 +4381,26 @@
 
     @GuardedBy("mUidRulesFirstLock")
     void updateRuleForDeviceIdleUL(int uid) {
-        updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
+        updateRulesForAllowlistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
     }
 
     // NOTE: since both fw_dozable and fw_powersave uses the same map
     // (mPowerSaveTempWhitelistAppIds) for allowlisting, we can reuse their logic in this method.
     @GuardedBy("mUidRulesFirstLock")
-    private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
+    private void updateRulesForAllowlistedPowerSaveUL(boolean enabled, int chain,
             SparseIntArray rules) {
         if (enabled) {
-            // Sync the whitelists before enabling the chain.  We don't care about the rules if
+            // Sync the allowlists before enabling the chain.  We don't care about the rules if
             // we are disabling the chain.
             final SparseIntArray uidRules = rules;
             uidRules.clear();
             final List<UserInfo> users = mUserManager.getUsers();
             for (int ui = users.size() - 1; ui >= 0; ui--) {
                 UserInfo user = users.get(ui);
-                updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
-                updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
+                updateRulesForAllowlistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
+                updateRulesForAllowlistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
                 if (chain == FIREWALL_CHAIN_POWERSAVE) {
-                    updateRulesForWhitelistedAppIds(uidRules,
+                    updateRulesForAllowlistedAppIds(uidRules,
                             mPowerSaveWhitelistExceptIdleAppIds, user.id);
                 }
             }
@@ -4415,7 +4415,7 @@
         }
     }
 
-    private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
+    private void updateRulesForAllowlistedAppIds(final SparseIntArray uidRules,
             final SparseBooleanArray whitelistedAppIds, int userId) {
         for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
             if (whitelistedAppIds.valueAt(i)) {
@@ -4476,12 +4476,12 @@
      *        allowlisted.
      */
     @GuardedBy("mUidRulesFirstLock")
-    private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
+    private boolean isAllowlistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
         final int appId = UserHandle.getAppId(uid);
         boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
                 || mPowerSaveWhitelistAppIds.get(appId);
         if (!deviceIdleMode) {
-            isWhitelisted = isWhitelisted || isWhitelistedFromPowerSaveExceptIdleUL(uid);
+            isWhitelisted = isWhitelisted || isAllowlistedFromPowerSaveExceptIdleUL(uid);
         }
         return isWhitelisted;
     }
@@ -4491,7 +4491,7 @@
      * (eg: Battery Saver and app idle).
      */
     @GuardedBy("mUidRulesFirstLock")
-    private boolean isWhitelistedFromPowerSaveExceptIdleUL(int uid) {
+    private boolean isAllowlistedFromPowerSaveExceptIdleUL(int uid) {
         final int appId = UserHandle.getAppId(uid);
         return mPowerSaveWhitelistExceptIdleAppIds.get(appId);
     }
@@ -4507,9 +4507,9 @@
     // NOTE: since both fw_dozable and fw_powersave uses the same map
     // (mPowerSaveTempWhitelistAppIds) for allowlisting, we can reuse their logic in this method.
     @GuardedBy("mUidRulesFirstLock")
-    private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
+    private void updateRulesForAllowlistedPowerSaveUL(int uid, boolean enabled, int chain) {
         if (enabled) {
-            final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
+            final boolean isWhitelisted = isAllowlistedFromPowerSaveUL(uid,
                     chain == FIREWALL_CHAIN_DOZABLE);
             if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
                 setUidFirewallRuleUL(chain, uid, FIREWALL_RULE_ALLOW);
@@ -4767,7 +4767,7 @@
     }
 
     @GuardedBy("mUidRulesFirstLock")
-    private void updateRulesForTempWhitelistChangeUL(int appId) {
+    private void updateRulesForTempAllowlistChangeUL(int appId) {
         final List<UserInfo> users = mUserManager.getUsers();
         final int numUsers = users.size();
         for (int i = 0; i < numUsers; i++) {
@@ -5158,7 +5158,7 @@
         final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
         final boolean isTop = isUidTop(uid);
 
-        final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
+        final boolean isWhitelisted = isAllowlistedFromPowerSaveUL(uid, mDeviceIdleMode);
 
         final int oldEffectiveBlockedReasons;
         final int newEffectiveBlockedReasons;
@@ -5181,9 +5181,9 @@
             newAllowedReasons |= (isSystem(uid) ? ALLOWED_REASON_SYSTEM : 0);
             newAllowedReasons |= (isForeground ? ALLOWED_REASON_FOREGROUND : 0);
             newAllowedReasons |= (isTop ? ALLOWED_REASON_TOP : 0);
-            newAllowedReasons |= (isWhitelistedFromPowerSaveUL(uid, true)
+            newAllowedReasons |= (isAllowlistedFromPowerSaveUL(uid, true)
                     ? ALLOWED_REASON_POWER_SAVE_ALLOWLIST : 0);
-            newAllowedReasons |= (isWhitelistedFromPowerSaveExceptIdleUL(uid)
+            newAllowedReasons |= (isAllowlistedFromPowerSaveExceptIdleUL(uid)
                     ? ALLOWED_REASON_POWER_SAVE_EXCEPT_IDLE_ALLOWLIST : 0);
             newAllowedReasons |= (uidBlockedState.allowedReasons
                     & ALLOWED_REASON_RESTRICTED_MODE_PERMISSIONS);
@@ -6095,7 +6095,7 @@
                 } else {
                     mPowerSaveTempWhitelistAppIds.delete(appId);
                 }
-                updateRulesForTempWhitelistChangeUL(appId);
+                updateRulesForTempAllowlistChangeUL(appId);
             }
         }
 
diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerShellCommand.java b/services/core/java/com/android/server/net/NetworkPolicyManagerShellCommand.java
index 47bb8f0..34c8a0d 100644
--- a/services/core/java/com/android/server/net/NetworkPolicyManagerShellCommand.java
+++ b/services/core/java/com/android/server/net/NetworkPolicyManagerShellCommand.java
@@ -154,13 +154,13 @@
         }
         switch(type) {
             case "app-idle-whitelist":
-                return listAppIdleWhitelist();
+                return listAppIdleAllowlist();
             case "wifi-networks":
                 return listWifiNetworks();
             case "restrict-background-whitelist":
-                return listRestrictBackgroundWhitelist();
+                return listRestrictBackgroundAllowlist();
             case "restrict-background-blacklist":
-                return listRestrictBackgroundBlacklist();
+                return listRestrictBackgroundDenylist();
         }
         pw.println("Error: unknown list type '" + type + "'");
         return -1;
@@ -175,11 +175,11 @@
         }
         switch(type) {
             case "restrict-background-whitelist":
-                return addRestrictBackgroundWhitelist();
+                return addRestrictBackgroundAllowlist();
             case "restrict-background-blacklist":
-                return addRestrictBackgroundBlacklist();
+                return addRestrictBackgroundDenylist();
             case "app-idle-whitelist":
-                return addAppIdleWhitelist();
+                return addAppIdleAllowlist();
         }
         pw.println("Error: unknown add type '" + type + "'");
         return -1;
@@ -194,11 +194,11 @@
         }
         switch(type) {
             case "restrict-background-whitelist":
-                return removeRestrictBackgroundWhitelist();
+                return removeRestrictBackgroundAllowlist();
             case "restrict-background-blacklist":
-                return removeRestrictBackgroundBlacklist();
+                return removeRestrictBackgroundDenylist();
             case "app-idle-whitelist":
-                return removeAppIdleWhitelist();
+                return removeAppIdleAllowlist();
         }
         pw.println("Error: unknown remove type '" + type + "'");
         return -1;
@@ -241,17 +241,17 @@
         return 0;
     }
 
-    private int listRestrictBackgroundWhitelist() throws RemoteException {
+    private int listRestrictBackgroundAllowlist() throws RemoteException {
         return listUidPolicies("Restrict background whitelisted UIDs",
                 POLICY_ALLOW_METERED_BACKGROUND);
     }
 
-    private int listRestrictBackgroundBlacklist() throws RemoteException {
+    private int listRestrictBackgroundDenylist() throws RemoteException {
         return listUidPolicies("Restrict background blacklisted UIDs",
                 POLICY_REJECT_METERED_BACKGROUND);
     }
 
-    private int listAppIdleWhitelist() throws RemoteException {
+    private int listAppIdleAllowlist() throws RemoteException {
         final PrintWriter pw = getOutPrintWriter();
         final int[] uids = mInterface.getAppIdleWhitelist();
         return listUidList("App Idle whitelisted UIDs", uids);
@@ -311,23 +311,23 @@
         return 0;
     }
 
-    private int addRestrictBackgroundWhitelist() throws RemoteException {
+    private int addRestrictBackgroundAllowlist() throws RemoteException {
         return setUidPolicy(POLICY_ALLOW_METERED_BACKGROUND);
     }
 
-    private int removeRestrictBackgroundWhitelist() throws RemoteException {
+    private int removeRestrictBackgroundAllowlist() throws RemoteException {
         return resetUidPolicy("not whitelisted", POLICY_ALLOW_METERED_BACKGROUND);
     }
 
-    private int addRestrictBackgroundBlacklist() throws RemoteException {
+    private int addRestrictBackgroundDenylist() throws RemoteException {
         return setUidPolicy(POLICY_REJECT_METERED_BACKGROUND);
     }
 
-    private int removeRestrictBackgroundBlacklist() throws RemoteException {
+    private int removeRestrictBackgroundDenylist() throws RemoteException {
         return resetUidPolicy("not blacklisted", POLICY_REJECT_METERED_BACKGROUND);
     }
 
-    private int setAppIdleWhitelist(boolean isWhitelisted) {
+    private int setAppIdleAllowlist(boolean isWhitelisted) {
         final int uid = getUidFromNextArg();
         if (uid < 0) {
             return uid;
@@ -336,12 +336,12 @@
         return 0;
     }
 
-    private int addAppIdleWhitelist() throws RemoteException {
-        return setAppIdleWhitelist(true);
+    private int addAppIdleAllowlist() throws RemoteException {
+        return setAppIdleAllowlist(true);
     }
 
-    private int removeAppIdleWhitelist() throws RemoteException {
-        return setAppIdleWhitelist(false);
+    private int removeAppIdleAllowlist() throws RemoteException {
+        return setAppIdleAllowlist(false);
     }
 
     private int listWifiNetworks() {
diff --git a/services/core/java/com/android/server/net/OWNERS b/services/core/java/com/android/server/net/OWNERS
index 9c96d46f..d0e95dd 100644
--- a/services/core/java/com/android/server/net/OWNERS
+++ b/services/core/java/com/android/server/net/OWNERS
@@ -1,5 +1,5 @@
 set noparent
-file:platform/packages/modules/Connectivity:master:/OWNERS_core_networking
+file:platform/packages/modules/Connectivity:main:/OWNERS_core_networking
 
 jsharkey@android.com
 sudheersai@google.com
diff --git a/services/core/java/com/android/server/net/watchlist/OWNERS b/services/core/java/com/android/server/net/watchlist/OWNERS
index a3d4b85..d0c4e55 100644
--- a/services/core/java/com/android/server/net/watchlist/OWNERS
+++ b/services/core/java/com/android/server/net/watchlist/OWNERS
@@ -1,3 +1,2 @@
-rickywai@google.com
 alanstokes@google.com
 simonjw@google.com
diff --git a/services/core/java/com/android/server/om/OverlayManagerService.java b/services/core/java/com/android/server/om/OverlayManagerService.java
index 362b26e..bdab341 100644
--- a/services/core/java/com/android/server/om/OverlayManagerService.java
+++ b/services/core/java/com/android/server/om/OverlayManagerService.java
@@ -1109,6 +1109,21 @@
             int callingUid = Binder.getCallingUid();
             mActorEnforcer.enforceActor(overlayInfo, methodName, callingUid, realUserId);
         }
+
+        /**
+         * @hide
+         */
+        public String getPartitionOrder() {
+            return mImpl.getOverlayConfig().getPartitionOrder();
+        }
+
+        /**
+         * @hide
+         */
+        public boolean isDefaultPartitionOrder() {
+            return mImpl.getOverlayConfig().isDefaultPartitionOrder();
+        }
+
     };
 
     private static final class PackageManagerHelperImpl implements PackageManagerHelper {
diff --git a/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java b/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
index 38781fa..bd0f657 100644
--- a/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
+++ b/services/core/java/com/android/server/om/OverlayManagerServiceImpl.java
@@ -876,4 +876,8 @@
             super(message, cause);
         }
     }
+
+    OverlayConfig getOverlayConfig() {
+        return mOverlayConfig;
+    }
 }
diff --git a/services/core/java/com/android/server/om/OverlayManagerShellCommand.java b/services/core/java/com/android/server/om/OverlayManagerShellCommand.java
index 89939a3..4beb391 100644
--- a/services/core/java/com/android/server/om/OverlayManagerShellCommand.java
+++ b/services/core/java/com/android/server/om/OverlayManagerShellCommand.java
@@ -16,6 +16,8 @@
 
 package com.android.server.om;
 
+import static com.android.internal.content.om.OverlayConfig.PARTITION_ORDER_FILE_PATH;
+
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.content.Context;
@@ -79,6 +81,8 @@
                     return runLookup();
                 case "fabricate":
                     return runFabricate();
+                case "partition-order":
+                    return runPartitionOrder();
                 default:
                     return handleDefaultCommands(cmd);
             }
@@ -130,6 +134,9 @@
         out.println("    Create an overlay from a single resource. Caller must be root. Example:");
         out.println("      fabricate --target android --name LighterGray \\");
         out.println("                android:color/lighter_gray 0x1c 0xffeeeeee");
+        out.println("  partition-order");
+        out.println("    Print the partition order from overlay config and how this order");
+        out.println("    got established, by default or by " + PARTITION_ORDER_FILE_PATH);
     }
 
     private int runList() throws RemoteException {
@@ -230,6 +237,14 @@
         return 0;
     }
 
+    private int runPartitionOrder() throws RemoteException {
+        final PrintWriter out = getOutPrintWriter();
+        out.println("Partition order (low to high priority): " + mInterface.getPartitionOrder());
+        out.println("Established by " + (mInterface.isDefaultPartitionOrder() ? "default"
+                : PARTITION_ORDER_FILE_PATH));
+        return 0;
+    }
+
     private int runFabricate() throws RemoteException {
         final PrintWriter err = getErrPrintWriter();
         if (Binder.getCallingUid() != Process.ROOT_UID) {
diff --git a/services/core/java/com/android/server/os/NativeTombstoneManager.java b/services/core/java/com/android/server/os/NativeTombstoneManager.java
index 45192b7..88f70cf 100644
--- a/services/core/java/com/android/server/os/NativeTombstoneManager.java
+++ b/services/core/java/com/android/server/os/NativeTombstoneManager.java
@@ -363,7 +363,7 @@
                 return false;
             }
 
-            if (Math.abs(exitInfo.getTimestamp() - mTimestampMs) > 5000) {
+            if (Math.abs(exitInfo.getTimestamp() - mTimestampMs) > 10000) {
                 return false;
             }
 
diff --git a/services/core/java/com/android/server/pm/ApexManager.java b/services/core/java/com/android/server/pm/ApexManager.java
index 1a6155b..a085b95 100644
--- a/services/core/java/com/android/server/pm/ApexManager.java
+++ b/services/core/java/com/android/server/pm/ApexManager.java
@@ -424,7 +424,7 @@
     /**
      * Performs a non-staged install of the given {@code apexFile}.
      */
-    abstract void installPackage(File apexFile, PackageParser2 packageParser)
+    abstract void installPackage(File apexFile, PackageParser2 packageParser, boolean force)
             throws PackageManagerException;
 
     /**
@@ -1136,7 +1136,7 @@
         }
 
         @Override
-        void installPackage(File apexFile, PackageParser2 packageParser)
+        void installPackage(File apexFile, PackageParser2 packageParser, boolean force)
                 throws PackageManagerException {
             try {
                 final int flags = PackageManager.GET_META_DATA
@@ -1159,7 +1159,7 @@
                 }
                 checkApexSignature(existingApexPkg, newApexPkg);
                 ApexInfo apexInfo = waitForApexService().installAndActivatePackage(
-                        apexFile.getAbsolutePath());
+                        apexFile.getAbsolutePath(), force);
                 final ParsedPackage parsedPackage2 = packageParser.parsePackage(
                         new File(apexInfo.modulePath), flags, /* useCaches= */ false);
                 final PackageInfo finalApexPkg = PackageInfoWithoutStateUtils.generate(
@@ -1505,7 +1505,7 @@
         }
 
         @Override
-        void installPackage(File apexFile, PackageParser2 packageParser) {
+        void installPackage(File apexFile, PackageParser2 packageParser, boolean force) {
             throw new UnsupportedOperationException("APEX updates are not supported");
         }
 
diff --git a/services/core/java/com/android/server/pm/InstallPackageHelper.java b/services/core/java/com/android/server/pm/InstallPackageHelper.java
index 3dac305..703ae11 100644
--- a/services/core/java/com/android/server/pm/InstallPackageHelper.java
+++ b/services/core/java/com/android/server/pm/InstallPackageHelper.java
@@ -872,8 +872,10 @@
                         "Expected exactly one .apex file under " + dir.getAbsolutePath()
                                 + " got: " + apexes.length);
             }
+            boolean force = (request.mArgs.mInstallFlags
+                    & PackageManager.INSTALL_FORCE_NON_STAGED_APEX_UPDATE) != 0;
             try (PackageParser2 packageParser = mPm.mInjector.getScanningPackageParser()) {
-                mApexManager.installPackage(apexes[0], packageParser);
+                mApexManager.installPackage(apexes[0], packageParser, force);
             }
         } catch (PackageManagerException e) {
             request.mInstallResult.setError("APEX installation failed", e);
@@ -2093,9 +2095,25 @@
                     // The caller explicitly specified INSTALL_ALL_USERS flag.
                     // Thus, updating the settings to install the app for all users.
                     for (int currentUserId : allUsers) {
-                        ps.setInstalled(true, currentUserId);
-                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId,
-                                installerPackageName);
+                        // If the app is already installed for the currentUser,
+                        // keep it as installed as we might be updating the app at this place.
+                        // If not currently installed, check if the currentUser is restricted by
+                        // DISALLOW_INSTALL_APPS or DISALLOW_DEBUGGING_FEATURES device policy.
+                        // Install / update the app if the user isn't restricted. Skip otherwise.
+                        final boolean installedForCurrentUser = ArrayUtils.contains(
+                                installedForUsers, currentUserId);
+                        final boolean restrictedByPolicy =
+                                mPm.isUserRestricted(currentUserId,
+                                        UserManager.DISALLOW_INSTALL_APPS)
+                                || mPm.isUserRestricted(currentUserId,
+                                        UserManager.DISALLOW_DEBUGGING_FEATURES);
+                        if (installedForCurrentUser || !restrictedByPolicy) {
+                            ps.setInstalled(true, currentUserId);
+                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
+                                    installerPackageName);
+                        } else {
+                            ps.setInstalled(false, currentUserId);
+                        }
                     }
                 }
 
diff --git a/services/core/java/com/android/server/pm/MovePackageHelper.java b/services/core/java/com/android/server/pm/MovePackageHelper.java
index 1f96205..139d9cf 100644
--- a/services/core/java/com/android/server/pm/MovePackageHelper.java
+++ b/services/core/java/com/android/server/pm/MovePackageHelper.java
@@ -48,8 +48,8 @@
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.os.storage.StorageManager;
+import android.os.storage.StorageManagerInternal;
 import android.os.storage.VolumeInfo;
-import android.text.TextUtils;
 import android.util.MathUtils;
 import android.util.Slog;
 import android.util.SparseIntArray;
@@ -63,6 +63,7 @@
 import com.android.server.pm.pkg.PackageStateUtils;
 
 import java.io.File;
+import java.util.ArrayList;
 import java.util.Objects;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
@@ -223,9 +224,7 @@
         }
 
         try {
-            for (int index = 0; index < installedUserIds.length; index++) {
-                prepareUserDataForVolumeIfRequired(volumeUuid, installedUserIds[index], storage);
-            }
+            prepareUserStorageForMove(currentVolumeUuid, volumeUuid, installedUserIds);
         } catch (RuntimeException e) {
             freezer.close();
             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
@@ -380,27 +379,20 @@
         return true;
     }
 
-    private void prepareUserDataForVolumeIfRequired(String volumeUuid, int userId,
-            StorageManager storageManager) {
-        if (TextUtils.isEmpty(volumeUuid)
-                || doesDataDirectoryExistForUser(volumeUuid, userId)) {
-            return;
-        }
+    private void prepareUserStorageForMove(String fromVolumeUuid, String toVolumeUuid,
+            int[] userIds) {
         if (DEBUG_INSTALL) {
-            Slog.d(TAG, "Preparing user directories for user u" + userId + " for UUID "
-                    + volumeUuid);
+            Slog.d(TAG, "Preparing user directories before moving app, from UUID " + fromVolumeUuid
+                    + " to UUID " + toVolumeUuid);
         }
-        final UserInfo user = mPm.mUserManager.getUserInfo(userId);
-        if (user == null) return;
-        // This call is same as StorageEventHelper#loadPrivatePackagesInner which prepares
-        // the storage before reconciling apps
-        storageManager.prepareUserStorage(volumeUuid, user.id, user.serialNumber,
-                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
-    }
-
-    private boolean doesDataDirectoryExistForUser(String uuid, int userId) {
-        final File userDirectoryFile = Environment.getDataUserCeDirectory(uuid, userId);
-        return userDirectoryFile != null && userDirectoryFile.exists();
+        final StorageManagerInternal smInternal =
+                mPm.mInjector.getLocalService(StorageManagerInternal.class);
+        final ArrayList<UserInfo> users = new ArrayList<>();
+        for (int userId : userIds) {
+            final UserInfo user = mPm.mUserManager.getUserInfo(userId);
+            users.add(user);
+        }
+        smInternal.prepareUserStorageForMove(fromVolumeUuid, toVolumeUuid, users);
     }
 
     public static class MoveCallbacks extends Handler {
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index 02cf433..3036e0b 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -482,7 +482,7 @@
             }
         } catch (FileNotFoundException e) {
             // Missing sessions are okay, probably first boot
-        } catch (IOException | XmlPullParserException e) {
+        } catch (IOException | XmlPullParserException | ArrayIndexOutOfBoundsException e) {
             Slog.wtf(TAG, "Failed reading install sessions", e);
         } finally {
             IoUtils.closeQuietly(fis);
diff --git a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
index be842b9..38b79e5 100644
--- a/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
+++ b/services/core/java/com/android/server/pm/PackageManagerShellCommand.java
@@ -86,7 +86,6 @@
 import android.os.ServiceSpecificException;
 import android.os.ShellCommand;
 import android.os.SystemClock;
-import android.os.SystemProperties;
 import android.os.Trace;
 import android.os.UserHandle;
 import android.os.UserManager;
@@ -3053,6 +3052,13 @@
         // Set package source to other by default
         sessionParams.setPackageSource(PackageInstaller.PACKAGE_SOURCE_OTHER);
 
+        // Encodes one of the states:
+        //  1. Install request explicitly specified --staged, then value will be true.
+        //  2. Install request explicitly specified --non-staged, then value will be false.
+        //  3. Install request did not specify either --staged or --non-staged, then for APEX
+        //      installs the value will be true, and for apk installs it will be false.
+        Boolean staged = null;
+
         String opt;
         boolean replaceExisting = true;
         boolean forceNonStaged = false;
@@ -3151,7 +3157,6 @@
                     break;
                 case "--apex":
                     sessionParams.setInstallAsApex();
-                    sessionParams.setStaged();
                     break;
                 case "--force-non-staged":
                     forceNonStaged = true;
@@ -3160,7 +3165,10 @@
                     sessionParams.setMultiPackage();
                     break;
                 case "--staged":
-                    sessionParams.setStaged();
+                    staged = true;
+                    break;
+                case "--non-staged":
+                    staged = false;
                     break;
                 case "--force-queryable":
                     sessionParams.setForceQueryable();
@@ -3192,11 +3200,17 @@
                     throw new IllegalArgumentException("Unknown option " + opt);
             }
         }
+        if (staged == null) {
+            staged = (sessionParams.installFlags & PackageManager.INSTALL_APEX) != 0;
+        }
         if (replaceExisting) {
             sessionParams.installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
         }
         if (forceNonStaged) {
             sessionParams.isStaged = false;
+            sessionParams.installFlags |= PackageManager.INSTALL_FORCE_NON_STAGED_APEX_UPDATE;
+        } else if (staged) {
+            sessionParams.setStaged();
         }
         return params;
     }
@@ -3978,7 +3992,8 @@
         pw.println("       [--preload] [--instant] [--full] [--dont-kill]");
         pw.println("       [--enable-rollback]");
         pw.println("       [--force-uuid internal|UUID] [--pkg PACKAGE] [-S BYTES]");
-        pw.println("       [--apex] [--force-non-staged] [--staged-ready-timeout TIMEOUT]");
+        pw.println("       [--apex] [--non-staged] [--force-non-staged]");
+        pw.println("       [--staged-ready-timeout TIMEOUT]");
         pw.println("       [PATH [SPLIT...]|-]");
         pw.println("    Install an application.  Must provide the apk data to install, either as");
         pw.println("    file path(s) or '-' to read from stdin.  Options are:");
@@ -4006,6 +4021,9 @@
         pw.println("          3=device setup, 4=user request");
         pw.println("      --force-uuid: force install on to disk volume with given UUID");
         pw.println("      --apex: install an .apex file, not an .apk");
+        pw.println("      --non-staged: explicitly set this installation to be non-staged.");
+        pw.println("          This flag is only useful for APEX installs that are implicitly");
+        pw.println("          assumed to be staged.");
         pw.println("      --force-non-staged: force the installation to run under a non-staged");
         pw.println("          session, which may complete without requiring a reboot");
         pw.println("      --staged-ready-timeout: By default, staged sessions wait "
diff --git a/services/core/java/com/android/server/pm/SELinuxMMAC.java b/services/core/java/com/android/server/pm/SELinuxMMAC.java
index c0e191f..5a941fe 100644
--- a/services/core/java/com/android/server/pm/SELinuxMMAC.java
+++ b/services/core/java/com/android/server/pm/SELinuxMMAC.java
@@ -80,6 +80,8 @@
     // Append targetSdkVersion=n to existing seinfo label where n is the app's targetSdkVersion
     private static final String TARGETSDKVERSION_STR = ":targetSdkVersion=";
 
+    private static final String PARTITION_STR = ":partition=";
+
     /**
      * Allows opt-in to the latest targetSdkVersion enforced changes without changing target SDK.
      * Turning this change on for an app targeting the latest SDK or higher is a no-op.
@@ -370,6 +372,23 @@
         return pkg.getTargetSdkVersion();
     }
 
+    private static String getPartition(AndroidPackage pkg) {
+        if (pkg.isSystemExt()) {
+            return "system_ext";
+        } else if (pkg.isProduct()) {
+            return "product";
+        } else if (pkg.isVendor()) {
+            return "vendor";
+        } else if (pkg.isOem()) {
+            return "oem";
+        } else if (pkg.isOdm()) {
+            return "odm";
+        } else if (pkg.isSystem()) {
+            return "system";
+        }
+        return "";
+    }
+
     /**
      * Selects a security label to a package based on input parameters and the seinfo tag taken
      * from a matched policy. All signature based policy stanzas are consulted and, if no match
@@ -433,6 +452,11 @@
 
         seInfo += TARGETSDKVERSION_STR + targetSdkVersion;
 
+        String partition = getPartition(pkg);
+        if (!partition.isEmpty()) {
+            seInfo += PARTITION_STR + partition;
+        }
+
         if (DEBUG_POLICY_INSTALL) {
             Slog.i(TAG, "package (" + pkg.getPackageName() + ") labeled with "
                     + "seinfo=" + seInfo);
diff --git a/services/core/java/com/android/server/pm/UserRestrictionsUtils.java b/services/core/java/com/android/server/pm/UserRestrictionsUtils.java
index 4849e0f..3562ab5 100644
--- a/services/core/java/com/android/server/pm/UserRestrictionsUtils.java
+++ b/services/core/java/com/android/server/pm/UserRestrictionsUtils.java
@@ -149,7 +149,8 @@
             UserManager.DISALLOW_WIFI_DIRECT,
             UserManager.DISALLOW_ADD_WIFI_CONFIG,
             UserManager.DISALLOW_CELLULAR_2G,
-            UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO
+            UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO,
+            UserManager.DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO
     });
 
     public static final Set<String> DEPRECATED_USER_RESTRICTIONS = Sets.newArraySet(
@@ -199,7 +200,8 @@
             UserManager.DISALLOW_WIFI_DIRECT,
             UserManager.DISALLOW_ADD_WIFI_CONFIG,
             UserManager.DISALLOW_CELLULAR_2G,
-            UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO
+            UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO,
+            UserManager.DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO
     );
 
     /**
@@ -240,7 +242,8 @@
                     UserManager.DISALLOW_WIFI_DIRECT,
                     UserManager.DISALLOW_ADD_WIFI_CONFIG,
                     UserManager.DISALLOW_CELLULAR_2G,
-                    UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO
+                    UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO,
+                    UserManager.DISALLOW_NEAR_FIELD_COMMUNICATION_RADIO
     );
 
     /**
diff --git a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
index 10e72f5..13b4f7f 100644
--- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
@@ -1480,12 +1480,9 @@
         if (dir.isDirectory() && dir.canRead()) {
             Collections.addAll(ret, dir.listFiles());
         }
-        // For IoT devices, we check the oem partition for default permissions for each app.
-        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED, 0)) {
-            dir = new File(Environment.getOemDirectory(), "etc/default-permissions");
-            if (dir.isDirectory() && dir.canRead()) {
-                Collections.addAll(ret, dir.listFiles());
-            }
+        dir = new File(Environment.getOemDirectory(), "etc/default-permissions");
+        if (dir.isDirectory() && dir.canRead()) {
+            Collections.addAll(ret, dir.listFiles());
         }
         return ret.isEmpty() ? null : ret.toArray(new File[0]);
     }
diff --git a/services/core/java/com/android/server/pm/permission/OneTimePermissionUserManager.java b/services/core/java/com/android/server/pm/permission/OneTimePermissionUserManager.java
index 881f870..d28048c 100644
--- a/services/core/java/com/android/server/pm/permission/OneTimePermissionUserManager.java
+++ b/services/core/java/com/android/server/pm/permission/OneTimePermissionUserManager.java
@@ -16,23 +16,26 @@
 
 package com.android.server.pm.permission;
 
-import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED;
-
 import android.annotation.NonNull;
 import android.app.ActivityManager;
+import android.app.ActivityManagerInternal;
 import android.app.AlarmManager;
+import android.app.IActivityManager;
+import android.app.IUidObserver;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.os.Handler;
+import android.os.RemoteException;
 import android.permission.PermissionControllerManager;
 import android.provider.DeviceConfig;
 import android.util.Log;
 import android.util.SparseArray;
 
 import com.android.internal.annotations.GuardedBy;
+import com.android.server.LocalServices;
 
 /**
  * Class that handles one-time permissions for a user
@@ -47,7 +50,8 @@
             "one_time_permissions_killed_delay_millis";
 
     private final @NonNull Context mContext;
-    private final @NonNull ActivityManager mActivityManager;
+    private final @NonNull IActivityManager mIActivityManager;
+    private final @NonNull ActivityManagerInternal mActivityManagerInternal;
     private final @NonNull AlarmManager mAlarmManager;
     private final @NonNull PermissionControllerManager mPermissionControllerManager;
 
@@ -77,49 +81,15 @@
 
     OneTimePermissionUserManager(@NonNull Context context) {
         mContext = context;
-        mActivityManager = context.getSystemService(ActivityManager.class);
+        mIActivityManager = ActivityManager.getService();
+        mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
         mAlarmManager = context.getSystemService(AlarmManager.class);
         mPermissionControllerManager = context.getSystemService(PermissionControllerManager.class);
         mHandler = context.getMainThreadHandler();
     }
 
-    /**
-     * Starts a one-time permission session for a given package. A one-time permission session is
-     * ended if app becomes inactive. Inactivity is defined as the package's uid importance level
-     * staying > importanceToResetTimer for timeoutMillis milliseconds. If the package's uid
-     * importance level goes <= importanceToResetTimer then the timer is reset and doesn't start
-     * until going > importanceToResetTimer.
-     * <p>
-     * When this timeoutMillis is reached if the importance level is <= importanceToKeepSessionAlive
-     * then the session is extended until either the importance goes above
-     * importanceToKeepSessionAlive which will end the session or <= importanceToResetTimer which
-     * will continue the session and reset the timer.
-     * </p>
-     * <p>
-     * Importance levels are defined in {@link android.app.ActivityManager.RunningAppProcessInfo}.
-     * </p>
-     * <p>
-     * Once the session ends PermissionControllerService#onNotifyOneTimePermissionSessionTimeout
-     * is invoked.
-     * </p>
-     * <p>
-     * Note that if there is currently an active session for a package a new one isn't created and
-     * the existing one isn't changed.
-     * </p>
-     * @param packageName The package to start a one-time permission session for
-     * @param timeoutMillis Number of milliseconds for an app to be in an inactive state
-     * @param revokeAfterKilledDelayMillis Number of milliseconds to wait after the process dies
-     *                                     before ending the session. Set to -1 to use default value
-     *                                     for the device.
-     * @param importanceToResetTimer The least important level to uid must be to reset the timer
-     * @param importanceToKeepSessionAlive The least important level the uid must be to keep the
-     *                                     session alive
-     *
-     * @hide
-     */
     void startPackageOneTimeSession(@NonNull String packageName, long timeoutMillis,
-            long revokeAfterKilledDelayMillis, int importanceToResetTimer,
-            int importanceToKeepSessionAlive) {
+            long revokeAfterKilledDelayMillis) {
         int uid;
         try {
             uid = mContext.getPackageManager().getPackageUid(packageName, 0);
@@ -131,13 +101,11 @@
         synchronized (mLock) {
             PackageInactivityListener listener = mListeners.get(uid);
             if (listener != null) {
-                listener.updateSessionParameters(timeoutMillis, revokeAfterKilledDelayMillis,
-                        importanceToResetTimer, importanceToKeepSessionAlive);
+                listener.updateSessionParameters(timeoutMillis, revokeAfterKilledDelayMillis);
                 return;
             }
             listener = new PackageInactivityListener(uid, packageName, timeoutMillis,
-                    revokeAfterKilledDelayMillis, importanceToResetTimer,
-                    importanceToKeepSessionAlive);
+                    revokeAfterKilledDelayMillis);
             mListeners.put(uid, listener);
         }
     }
@@ -182,34 +150,58 @@
 
         private static final long TIMER_INACTIVE = -1;
 
+        private static final int STATE_GONE = 0;
+        private static final int STATE_TIMER = 1;
+        private static final int STATE_ACTIVE = 2;
+
         private final int mUid;
         private final @NonNull String mPackageName;
         private long mTimeout;
         private long mRevokeAfterKilledDelay;
-        private int mImportanceToResetTimer;
-        private int mImportanceToKeepSessionAlive;
 
         private boolean mIsAlarmSet;
         private boolean mIsFinished;
 
         private long mTimerStart = TIMER_INACTIVE;
 
-        private final ActivityManager.OnUidImportanceListener mStartTimerListener;
-        private final ActivityManager.OnUidImportanceListener mSessionKillableListener;
-        private final ActivityManager.OnUidImportanceListener mGoneListener;
-
         private final Object mInnerLock = new Object();
         private final Object mToken = new Object();
+        private final IUidObserver.Stub mObserver = new IUidObserver.Stub() {
+            @Override
+            public void onUidGone(int uid, boolean disabled) {
+                if (uid == mUid) {
+                    PackageInactivityListener.this.updateUidState(STATE_GONE);
+                }
+            }
+
+            @Override
+            public void onUidStateChanged(int uid, int procState, long procStateSeq,
+                    int capability) {
+                if (uid == mUid) {
+                    if (procState > ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
+                            && procState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
+                        PackageInactivityListener.this.updateUidState(STATE_TIMER);
+                    } else {
+                        PackageInactivityListener.this.updateUidState(STATE_ACTIVE);
+                    }
+                }
+            }
+
+            public void onUidActive(int uid) {
+            }
+            public void onUidIdle(int uid, boolean disabled) {
+            }
+            public void onUidProcAdjChanged(int uid) {
+            }
+            public void onUidCachedChanged(int uid, boolean cached) {
+            }
+        };
 
         private PackageInactivityListener(int uid, @NonNull String packageName, long timeout,
-                long revokeAfterkilledDelay, int importanceToResetTimer,
-                int importanceToKeepSessionAlive) {
-
+                long revokeAfterkilledDelay) {
             Log.i(LOG_TAG,
                     "Start tracking " + packageName + ". uid=" + uid + " timeout=" + timeout
-                            + " killedDelay=" + revokeAfterkilledDelay
-                            + " importanceToResetTimer=" + importanceToResetTimer
-                            + " importanceToKeepSessionAlive=" + importanceToKeepSessionAlive);
+                            + " killedDelay=" + revokeAfterkilledDelay);
 
             mUid = uid;
             mPackageName = packageName;
@@ -219,27 +211,24 @@
                             DeviceConfig.NAMESPACE_PERMISSIONS, PROPERTY_KILLED_DELAY_CONFIG_KEY,
                             DEFAULT_KILLED_DELAY_MILLIS)
                     : revokeAfterkilledDelay;
-            mImportanceToResetTimer = importanceToResetTimer;
-            mImportanceToKeepSessionAlive = importanceToKeepSessionAlive;
 
-            mStartTimerListener =
-                    (changingUid, importance) -> onImportanceChanged(changingUid, importance);
-            mSessionKillableListener =
-                    (changingUid, importance) -> onImportanceChanged(changingUid, importance);
-            mGoneListener =
-                    (changingUid, importance) -> onImportanceChanged(changingUid, importance);
+            try {
+                mIActivityManager.registerUidObserver(mObserver,
+                        ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_PROCSTATE,
+                        ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE,
+                        null);
+            } catch (RemoteException e) {
+                Log.e(LOG_TAG, "Couldn't check uid proc state", e);
+                // Can't register uid observer, just revoke immediately
+                synchronized (mInnerLock) {
+                    onPackageInactiveLocked();
+                }
+            }
 
-            mActivityManager.addOnUidImportanceListener(mStartTimerListener,
-                    importanceToResetTimer);
-            mActivityManager.addOnUidImportanceListener(mSessionKillableListener,
-                    importanceToKeepSessionAlive);
-            mActivityManager.addOnUidImportanceListener(mGoneListener, IMPORTANCE_CACHED);
-
-            onImportanceChanged(mUid, mActivityManager.getPackageImportance(packageName));
+            updateUidState();
         }
 
-        public void updateSessionParameters(long timeoutMillis, long revokeAfterKilledDelayMillis,
-                int importanceToResetTimer, int importanceToKeepSessionAlive) {
+        public void updateSessionParameters(long timeoutMillis, long revokeAfterKilledDelayMillis) {
             synchronized (mInnerLock) {
                 mTimeout = Math.min(mTimeout, timeoutMillis);
                 mRevokeAfterKilledDelay = Math.min(mRevokeAfterKilledDelay,
@@ -248,63 +237,74 @@
                                 DeviceConfig.NAMESPACE_PERMISSIONS,
                                 PROPERTY_KILLED_DELAY_CONFIG_KEY, DEFAULT_KILLED_DELAY_MILLIS)
                                 : revokeAfterKilledDelayMillis);
-                mImportanceToResetTimer = Math.min(importanceToResetTimer, mImportanceToResetTimer);
-                mImportanceToKeepSessionAlive = Math.min(importanceToKeepSessionAlive,
-                        mImportanceToKeepSessionAlive);
                 Log.v(LOG_TAG,
                         "Updated params for " + mPackageName + ". timeout=" + mTimeout
-                                + " killedDelay=" + mRevokeAfterKilledDelay
-                                + " importanceToResetTimer=" + mImportanceToResetTimer
-                                + " importanceToKeepSessionAlive=" + mImportanceToKeepSessionAlive);
-                onImportanceChanged(mUid, mActivityManager.getPackageImportance(mPackageName));
+                                + " killedDelay=" + mRevokeAfterKilledDelay);
+                updateUidState();
             }
         }
 
-        private void onImportanceChanged(int uid, int importance) {
-            if (uid != mUid) {
-                return;
-            }
+        private int getCurrentState() {
+            return getStateFromProcState(mActivityManagerInternal.getUidProcessState(mUid));
+        }
 
-            Log.v(LOG_TAG, "Importance changed for " + mPackageName + " (" + mUid + ")."
-                    + " importance=" + importance);
+        private int getStateFromProcState(int procState) {
+            if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
+                return STATE_GONE;
+            } else {
+                if (procState > ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
+                    return STATE_TIMER;
+                } else {
+                    return STATE_ACTIVE;
+                }
+            }
+        }
+
+        private void updateUidState() {
+            updateUidState(getCurrentState());
+        }
+
+        private void updateUidState(int state) {
+            Log.v(LOG_TAG, "Updating state for " + mPackageName + " (" + mUid + ")."
+                    + " state=" + state);
             synchronized (mInnerLock) {
                 // Remove any pending inactivity callback
                 mHandler.removeCallbacksAndMessages(mToken);
 
-                if (importance > IMPORTANCE_CACHED) {
+                if (state == STATE_GONE) {
                     if (mRevokeAfterKilledDelay == 0) {
                         onPackageInactiveLocked();
                         return;
                     }
                     // Delay revocation in case app is restarting
                     mHandler.postDelayed(() -> {
-                        int imp = mActivityManager.getUidImportance(mUid);
-                        if (imp > IMPORTANCE_CACHED) {
-                            onPackageInactiveLocked();
-                        } else {
-                            if (DEBUG) {
-                                Log.d(LOG_TAG, "No longer gone after delayed revocation. "
-                                        + "Rechecking for " + mPackageName + " (" + mUid + ").");
+                        int currentState;
+                        synchronized (mInnerLock) {
+                            currentState = getCurrentState();
+                            if (currentState == STATE_GONE) {
+                                onPackageInactiveLocked();
+                                return;
                             }
-                            onImportanceChanged(mUid, imp);
                         }
+                        if (DEBUG) {
+                            Log.d(LOG_TAG, "No longer gone after delayed revocation. "
+                                    + "Rechecking for " + mPackageName + " (" + mUid
+                                    + ").");
+                        }
+                        updateUidState(currentState);
                     }, mToken, mRevokeAfterKilledDelay);
                     return;
-                }
-                if (importance > mImportanceToResetTimer) {
+                } else if (state == STATE_TIMER) {
                     if (mTimerStart == TIMER_INACTIVE) {
                         if (DEBUG) {
                             Log.d(LOG_TAG, "Start the timer for "
                                     + mPackageName + " (" + mUid + ").");
                         }
                         mTimerStart = System.currentTimeMillis();
+                        setAlarmLocked();
                     }
-                } else {
+                } else if (state == STATE_ACTIVE) {
                     mTimerStart = TIMER_INACTIVE;
-                }
-                if (importance > mImportanceToKeepSessionAlive) {
-                    setAlarmLocked();
-                } else {
                     cancelAlarmLocked();
                 }
             }
@@ -318,19 +318,9 @@
                 mIsFinished = true;
                 cancelAlarmLocked();
                 try {
-                    mActivityManager.removeOnUidImportanceListener(mStartTimerListener);
-                } catch (IllegalArgumentException e) {
-                    Log.e(LOG_TAG, "Could not remove start timer listener", e);
-                }
-                try {
-                    mActivityManager.removeOnUidImportanceListener(mSessionKillableListener);
-                } catch (IllegalArgumentException e) {
-                    Log.e(LOG_TAG, "Could not remove session killable listener", e);
-                }
-                try {
-                    mActivityManager.removeOnUidImportanceListener(mGoneListener);
-                } catch (IllegalArgumentException e) {
-                    Log.e(LOG_TAG, "Could not remove gone listener", e);
+                    mIActivityManager.unregisterUidObserver(mObserver);
+                } catch (RemoteException e) {
+                    Log.e(LOG_TAG, "Unable to unregister uid observer.", e);
                 }
             }
         }
@@ -394,9 +384,11 @@
                         mPermissionControllerManager.notifyOneTimePermissionSessionTimeout(
                                 mPackageName);
                     });
-            mActivityManager.removeOnUidImportanceListener(mStartTimerListener);
-            mActivityManager.removeOnUidImportanceListener(mSessionKillableListener);
-            mActivityManager.removeOnUidImportanceListener(mGoneListener);
+            try {
+                mIActivityManager.unregisterUidObserver(mObserver);
+            } catch (RemoteException e) {
+                Log.e(LOG_TAG, "Unable to unregister uid observer.", e);
+            }
             synchronized (mLock) {
                 mListeners.remove(mUid);
             }
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
index 1c2603c..9ebe6b4 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -386,8 +386,7 @@
 
     @Override
     public void startOneTimePermissionSession(String packageName, @UserIdInt int userId,
-            long timeoutMillis, long revokeAfterKilledDelayMillis, int importanceToResetTimer,
-            int importanceToKeepSessionAlive) {
+            long timeoutMillis, long revokeAfterKilledDelayMillis) {
         mContext.enforceCallingOrSelfPermission(
                 Manifest.permission.MANAGE_ONE_TIME_PERMISSION_SESSIONS,
                 "Must hold " + Manifest.permission.MANAGE_ONE_TIME_PERMISSION_SESSIONS
@@ -397,8 +396,7 @@
         final long token = Binder.clearCallingIdentity();
         try {
             getOneTimePermissionUserManager(userId).startPackageOneTimeSession(packageName,
-                    timeoutMillis, revokeAfterKilledDelayMillis, importanceToResetTimer,
-                    importanceToKeepSessionAlive);
+                    timeoutMillis, revokeAfterKilledDelayMillis);
         } finally {
             Binder.restoreCallingIdentity(token);
         }
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
index 9ed5aa7..5221cfa 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
@@ -2116,6 +2116,12 @@
                 if (!isStorageOrMedia) {
                     continue;
                 }
+                boolean isSystemOrPolicyFixed = (getPermissionFlags(newPackage.getPackageName(),
+                        permInfo.name, userId) & (FLAG_PERMISSION_SYSTEM_FIXED
+                        | FLAG_PERMISSION_POLICY_FIXED)) != 0;
+                if (isSystemOrPolicyFixed) {
+                    continue;
+                }
 
                 EventLog.writeEvent(0x534e4554, "171430330", newPackage.getUid(),
                         "Revoking permission " + permInfo.name + " from package "
diff --git a/services/core/java/com/android/server/pm/pkg/parsing/ParsingPackageUtils.java b/services/core/java/com/android/server/pm/pkg/parsing/ParsingPackageUtils.java
index 810fa5f..debdc55 100644
--- a/services/core/java/com/android/server/pm/pkg/parsing/ParsingPackageUtils.java
+++ b/services/core/java/com/android/server/pm/pkg/parsing/ParsingPackageUtils.java
@@ -1546,6 +1546,7 @@
     private static ParseResult<ParsingPackage> parseUsesSdk(ParseInput input,
             ParsingPackage pkg, Resources res, XmlResourceParser parser, int flags)
             throws IOException, XmlPullParserException {
+        String pkgName = (pkg != null) ? pkg.getPackageName() : "<unknown>";
         if (SDK_VERSION > 0) {
             final boolean isApkInApex = (flags & PARSE_APK_IN_APEX) != 0;
             TypedArray sa = res.obtainAttributes(parser, R.styleable.AndroidManifestUsesSdk);
@@ -1595,7 +1596,7 @@
 
                 ParseResult<Integer> targetSdkVersionResult = FrameworkParsingPackageUtils
                         .computeTargetSdkVersion(targetVers, targetCode, SDK_CODENAMES, input,
-                                isApkInApex);
+                                isApkInApex, pkgName);
                 if (targetSdkVersionResult.isError()) {
                     return input.error(targetSdkVersionResult);
                 }
@@ -1609,7 +1610,8 @@
                 }
 
                 ParseResult<Integer> minSdkVersionResult = FrameworkParsingPackageUtils
-                        .computeMinSdkVersion(minVers, minCode, SDK_VERSION, SDK_CODENAMES, input);
+                        .computeMinSdkVersion(minVers, minCode, SDK_VERSION, SDK_CODENAMES,
+                                input, pkgName);
                 if (minSdkVersionResult.isError()) {
                     return input.error(minSdkVersionResult);
                 }
@@ -3069,7 +3071,7 @@
      *
      * TODO(b/155513789): Remove this in favor of collecting certificates during the original parse
      *  call if requested. Leaving this as an optional method for the caller means we have to
-     *  construct a dummy ParseInput.
+     *  construct a placeholder ParseInput.
      */
     @CheckResult
     public static ParseResult<SigningDetails> getSigningDetails(ParseInput input,
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 95ab464..fe31bf0 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -5857,10 +5857,10 @@
                 pw.println(endcallBehaviorToString(mEndcallBehavior));
         pw.print(prefix);
         // TODO(b/117479243): handle it in InputPolicy
-        pw.print("mDisplayHomeButtonHandlers=");
+        pw.println("mDisplayHomeButtonHandlers=");
         for (int i = 0; i < mDisplayHomeButtonHandlers.size(); i++) {
             final int key = mDisplayHomeButtonHandlers.keyAt(i);
-            pw.println(mDisplayHomeButtonHandlers.get(key));
+            pw.print(prefix); pw.print("  "); pw.println(mDisplayHomeButtonHandlers.get(key));
         }
         pw.print(prefix); pw.print("mKeyguardOccluded="); pw.print(isKeyguardOccluded());
                 pw.print(" mKeyguardOccludedChanged="); pw.print(mKeyguardOccludedChanged);
@@ -6131,6 +6131,7 @@
 
     private class HdmiVideoExtconUEventObserver extends ExtconStateObserver<Boolean> {
         private static final String HDMI_EXIST = "HDMI=1";
+        private static final String DP_EXIST = "DP=1";
         private static final String NAME = "hdmi";
 
         private boolean init(ExtconInfo hdmi) {
@@ -6161,7 +6162,8 @@
         public Boolean parseState(ExtconInfo extconIfno, String state) {
             // extcon event state changes from kernel4.9
             // new state will be like STATE=HDMI=1
-            return state.contains(HDMI_EXIST);
+            // or like STATE=DP=1 for newer kernel
+            return state.contains(HDMI_EXIST) || state.contains(DP_EXIST);
         }
     }
 
diff --git a/services/core/java/com/android/server/policy/SoftRestrictedPermissionPolicy.java b/services/core/java/com/android/server/policy/SoftRestrictedPermissionPolicy.java
index ab71355..ed8cf4f 100644
--- a/services/core/java/com/android/server/policy/SoftRestrictedPermissionPolicy.java
+++ b/services/core/java/com/android/server/policy/SoftRestrictedPermissionPolicy.java
@@ -215,7 +215,7 @@
                             return true;
                         }
 
-                        // The package is now a part of the forced scoped storage whitelist
+                        // The package is now a part of the forced scoped storage allowlist
                         if (isForcedScopedStorage) {
                             return true;
                         }
diff --git a/services/core/java/com/android/server/power/hint/OWNERS b/services/core/java/com/android/server/power/hint/OWNERS
new file mode 100644
index 0000000..c28c07a
--- /dev/null
+++ b/services/core/java/com/android/server/power/hint/OWNERS
@@ -0,0 +1,2 @@
+include /ADPF_OWNERS
+
diff --git a/services/core/java/com/android/server/recoverysystem/OWNERS b/services/core/java/com/android/server/recoverysystem/OWNERS
index e3e7fdf..e098053 100644
--- a/services/core/java/com/android/server/recoverysystem/OWNERS
+++ b/services/core/java/com/android/server/recoverysystem/OWNERS
@@ -1,3 +1,2 @@
+aveena@google.com
 ejyzhang@google.com
-rvrolyk@google.com
-xunchang@google.com
diff --git a/services/core/java/com/android/server/recoverysystem/hal/BootControlHIDL.java b/services/core/java/com/android/server/recoverysystem/hal/BootControlHIDL.java
index 65325c2..7c4d787 100644
--- a/services/core/java/com/android/server/recoverysystem/hal/BootControlHIDL.java
+++ b/services/core/java/com/android/server/recoverysystem/hal/BootControlHIDL.java
@@ -22,6 +22,8 @@
 import android.os.RemoteException;
 import android.util.Slog;
 
+import java.util.NoSuchElementException;
+
 public class BootControlHIDL implements IBootControl {
     private static final String TAG = "BootControlHIDL";
 
@@ -32,7 +34,7 @@
     public static boolean isServicePresent() {
         try {
             android.hardware.boot.V1_0.IBootControl.getService(true);
-        } catch (RemoteException e) {
+        } catch (RemoteException | NoSuchElementException e) {
             return false;
         }
         return true;
@@ -41,7 +43,7 @@
     public static boolean isV1_2ServicePresent() {
         try {
             android.hardware.boot.V1_2.IBootControl.getService(true);
-        } catch (RemoteException e) {
+        } catch (RemoteException | NoSuchElementException e) {
             return false;
         }
         return true;
diff --git a/services/core/java/com/android/server/security/FileIntegrityService.java b/services/core/java/com/android/server/security/FileIntegrityService.java
index 466ac74..bdeb9a8 100644
--- a/services/core/java/com/android/server/security/FileIntegrityService.java
+++ b/services/core/java/com/android/server/security/FileIntegrityService.java
@@ -125,13 +125,7 @@
     }
 
     private void loadAllCertificates() {
-        // A better alternative to load certificates would be to read from .fs-verity kernel
-        // keyring, which fsverity_init loads to during earlier boot time from the same sources
-        // below. But since the read operation from keyring is not provided in kernel, we need to
-        // duplicate the same loading logic here.
-
         // Load certificates trusted by the device manufacturer.
-        // NB: Directories need to be synced with system/security/fsverity_init/fsverity_init.cpp.
         final String relativeDir = "etc/security/fsverity";
         loadCertificatesFromDirectory(Environment.getRootDirectory().toPath()
                 .resolve(relativeDir));
diff --git a/services/core/java/com/android/server/security/KeyChainSystemService.java b/services/core/java/com/android/server/security/KeyChainSystemService.java
index edd4a3d..1eb2839 100644
--- a/services/core/java/com/android/server/security/KeyChainSystemService.java
+++ b/services/core/java/com/android/server/security/KeyChainSystemService.java
@@ -53,7 +53,7 @@
     /**
      * Maximum time limit for the KeyChain app to deal with packages being removed.
      */
-    private static final int KEYCHAIN_IDLE_WHITELIST_DURATION_MS = 30 * 1000;
+    private static final int KEYCHAIN_IDLE_ALLOWLIST_DURATION_MS = 30 * 1000;
 
     public KeyChainSystemService(final Context context) {
         super(context);
@@ -104,7 +104,7 @@
         final DeviceIdleInternal idleController =
                 LocalServices.getService(DeviceIdleInternal.class);
         idleController.addPowerSaveTempWhitelistApp(Process.myUid(), packageName,
-                KEYCHAIN_IDLE_WHITELIST_DURATION_MS, user.getIdentifier(), false,
+                KEYCHAIN_IDLE_ALLOWLIST_DURATION_MS, user.getIdentifier(), false,
                 REASON_KEY_CHAIN, "keychain");
 
         getContext().startServiceAsUser(intent, user);
diff --git a/services/core/java/com/android/server/security/OWNERS b/services/core/java/com/android/server/security/OWNERS
index 5bcc98b6..fa4bf22 100644
--- a/services/core/java/com/android/server/security/OWNERS
+++ b/services/core/java/com/android/server/security/OWNERS
@@ -1,4 +1,7 @@
 # Bug component: 36824
 
+include /core/java/android/security/OWNERS
+
 per-file *AttestationVerification* = file:/core/java/android/security/attestationverification/OWNERS
 per-file FileIntegrity*.java = victorhsieh@google.com
+per-file KeyChainSystemService.java = file:platform/packages/apps/KeyChain:/OWNERS
diff --git a/services/core/java/com/android/server/security/rkp/OWNERS b/services/core/java/com/android/server/security/rkp/OWNERS
index 348f940..ea6dc72 100644
--- a/services/core/java/com/android/server/security/rkp/OWNERS
+++ b/services/core/java/com/android/server/security/rkp/OWNERS
@@ -1 +1 @@
-file:platform/frameworks/base:master:/core/java/android/security/rkp/OWNERS
+file:platform/frameworks/base:main:/core/java/android/security/rkp/OWNERS
diff --git a/services/core/java/com/android/server/security/rkp/RemoteProvisioningService.java b/services/core/java/com/android/server/security/rkp/RemoteProvisioningService.java
index 2bd7383..1c5838c 100644
--- a/services/core/java/com/android/server/security/rkp/RemoteProvisioningService.java
+++ b/services/core/java/com/android/server/security/rkp/RemoteProvisioningService.java
@@ -105,14 +105,27 @@
         @Override
         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
             if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
-            new RemoteProvisioningShellCommand().dump(pw);
+            final int callerUid = Binder.getCallingUidOrThrow();
+            final long callingIdentity = Binder.clearCallingIdentity();
+            try {
+                new RemoteProvisioningShellCommand(getContext(), callerUid).dump(pw);
+            } finally {
+                Binder.restoreCallingIdentity(callingIdentity);
+            }
         }
 
         @Override
         public int handleShellCommand(ParcelFileDescriptor in, ParcelFileDescriptor out,
                 ParcelFileDescriptor err, String[] args) {
-            return new RemoteProvisioningShellCommand().exec(this, in.getFileDescriptor(),
-                    out.getFileDescriptor(), err.getFileDescriptor(), args);
+            final int callerUid = Binder.getCallingUidOrThrow();
+            final long callingIdentity = Binder.clearCallingIdentity();
+            try {
+                return new RemoteProvisioningShellCommand(getContext(), callerUid).exec(this,
+                        in.getFileDescriptor(), out.getFileDescriptor(), err.getFileDescriptor(),
+                        args);
+            } finally {
+                Binder.restoreCallingIdentity(callingIdentity);
+            }
         }
     }
 }
diff --git a/services/core/java/com/android/server/security/rkp/RemoteProvisioningShellCommand.java b/services/core/java/com/android/server/security/rkp/RemoteProvisioningShellCommand.java
index bc39084..4a6d746 100644
--- a/services/core/java/com/android/server/security/rkp/RemoteProvisioningShellCommand.java
+++ b/services/core/java/com/android/server/security/rkp/RemoteProvisioningShellCommand.java
@@ -16,22 +16,30 @@
 
 package com.android.server.security.rkp;
 
+import android.content.Context;
 import android.hardware.security.keymint.DeviceInfo;
 import android.hardware.security.keymint.IRemotelyProvisionedComponent;
 import android.hardware.security.keymint.MacedPublicKey;
 import android.hardware.security.keymint.ProtectedData;
 import android.hardware.security.keymint.RpcHardwareInfo;
+import android.os.CancellationSignal;
+import android.os.OutcomeReceiver;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.ShellCommand;
+import android.security.rkp.service.RegistrationProxy;
+import android.security.rkp.service.RemotelyProvisionedKey;
 import android.util.IndentingPrintWriter;
 
-import com.android.internal.annotations.VisibleForTesting;
-
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.PrintWriter;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.time.Duration;
 import java.util.Base64;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
 
 import co.nstant.in.cbor.CborDecoder;
 import co.nstant.in.cbor.CborEncoder;
@@ -49,21 +57,22 @@
             + "  Show this message.\n"
             + "dump\n"
             + "  Dump service diagnostics.\n"
-            + "list [--min-version MIN_VERSION]\n"
+            + "list\n"
             + "  List the names of the IRemotelyProvisionedComponent instances.\n"
             + "csr [--challenge CHALLENGE] NAME\n"
             + "  Generate and print a base64-encoded CSR from the named\n"
             + "  IRemotelyProvisionedComponent. A base64-encoded challenge can be provided,\n"
-            + "  or else it defaults to an empty challenge.\n";
+            + "  or else it defaults to an empty challenge.\n"
+            + "certify NAME\n"
+            + "  Output the PEM-encoded certificate chain provisioned for the named\n"
+            + "  IRemotelyProvisionedComponent.\n";
 
-    @VisibleForTesting
     static final String EEK_ED25519_BASE64 = "goRDoQEnoFgqpAEBAycgBiFYIJm57t1e5FL2hcZMYtw+YatXSH11N"
             + "ymtdoAy0rPLY1jZWEAeIghLpLekyNdOAw7+uK8UTKc7b6XN3Np5xitk/pk5r3bngPpmAIUNB5gqrJFcpyUUS"
             + "QY0dcqKJ3rZ41pJ6wIDhEOhASegWE6lAQECWCDQrsEVyirPc65rzMvRlh1l6LHd10oaN7lDOpfVmd+YCAM4G"
             + "CAEIVggvoXnRsSjQlpA2TY6phXQLFh+PdwzAjLS/F4ehyVfcmBYQJvPkOIuS6vRGLEOjl0gJ0uEWP78MpB+c"
             + "gWDvNeCvvpkeC1UEEvAMb9r6B414vAtzmwvT/L1T6XUg62WovGHWAQ=";
 
-    @VisibleForTesting
     static final String EEK_P256_BASE64 = "goRDoQEmoFhNpQECAyYgASFYIPcUituX9MxT79JkEcTjdR9mH6RxDGzP"
             + "+glGgHSHVPKtIlggXn9b9uzk9hnM/xM3/Q+hyJPbGAZ2xF3m12p3hsMtr49YQC+XjkL7vgctlUeFR5NAsB/U"
             + "m0ekxESp8qEHhxDHn8sR9L+f6Dvg5zRMFfx7w34zBfTRNDztAgRgehXgedOK/ySEQ6EBJqBYcaYBAgJYIDVz"
@@ -74,14 +83,20 @@
     private static final int ERROR = -1;
     private static final int SUCCESS = 0;
 
+    private static final Duration BIND_TIMEOUT = Duration.ofSeconds(10);
+    private static final int KEY_ID = 452436;
+
+    private final Context mContext;
+    private final int mCallerUid;
     private final Injector mInjector;
 
-    RemoteProvisioningShellCommand() {
-        this(new Injector());
+    RemoteProvisioningShellCommand(Context context, int callerUid) {
+        this(context, callerUid, new Injector());
     }
 
-    @VisibleForTesting
-    RemoteProvisioningShellCommand(Injector injector) {
+    RemoteProvisioningShellCommand(Context context, int callerUid, Injector injector) {
+        mContext = context;
+        mCallerUid = callerUid;
         mInjector = injector;
     }
 
@@ -102,6 +117,8 @@
                     return list();
                 case "csr":
                     return csr();
+                case "certify":
+                    return certify();
                 default:
                     return handleDefaultCommands(cmd);
             }
@@ -232,7 +249,45 @@
         return new CborDecoder(bais).decodeNext();
     }
 
-    @VisibleForTesting
+    private int certify() throws Exception {
+        String name = getNextArgRequired();
+
+        Executor executor = mContext.getMainExecutor();
+        CancellationSignal cancellationSignal = new CancellationSignal();
+        OutcomeFuture<RemotelyProvisionedKey> key = new OutcomeFuture<>();
+        mInjector.getRegistrationProxy(mContext, mCallerUid, name, executor)
+                .getKeyAsync(KEY_ID, cancellationSignal, executor, key);
+        byte[] encodedCertChain = key.join().getEncodedCertChain();
+        ByteArrayInputStream is = new ByteArrayInputStream(encodedCertChain);
+        PrintWriter pw = getOutPrintWriter();
+        for (Certificate cert : CertificateFactory.getInstance("X.509").generateCertificates(is)) {
+            String encoded = Base64.getEncoder().encodeToString(cert.getEncoded());
+            pw.println("-----BEGIN CERTIFICATE-----");
+            pw.println(encoded.replaceAll("(.{64})", "$1\n").stripTrailing());
+            pw.println("-----END CERTIFICATE-----");
+        }
+        return SUCCESS;
+    }
+
+    /** Treat an OutcomeReceiver as a future for use in synchronous code. */
+    private static class OutcomeFuture<T> implements OutcomeReceiver<T, Exception> {
+        private CompletableFuture<T> mFuture = new CompletableFuture<>();
+
+        @Override
+          public void onResult(T result) {
+            mFuture.complete(result);
+        }
+
+        @Override
+        public void onError(Exception e) {
+            mFuture.completeExceptionally(e);
+        }
+
+        public T join() {
+            return mFuture.join();
+        }
+    }
+
     static class Injector {
         String[] getIrpcNames() {
             return ServiceManager.getDeclaredInstances(IRemotelyProvisionedComponent.DESCRIPTOR);
@@ -248,5 +303,14 @@
             }
             return binder;
         }
+
+        RegistrationProxy getRegistrationProxy(
+                Context context, int callerUid, String name, Executor executor) {
+            String irpc = IRemotelyProvisionedComponent.DESCRIPTOR + "/" + name;
+            OutcomeFuture<RegistrationProxy> registration = new OutcomeFuture<>();
+            RegistrationProxy.createAsync(
+                    context, callerUid, irpc, BIND_TIMEOUT, executor, registration);
+            return registration.join();
+        }
     }
 }
diff --git a/services/core/java/com/android/server/trust/TrustAgentWrapper.java b/services/core/java/com/android/server/trust/TrustAgentWrapper.java
index 36293d5..23cb91d 100644
--- a/services/core/java/com/android/server/trust/TrustAgentWrapper.java
+++ b/services/core/java/com/android/server/trust/TrustAgentWrapper.java
@@ -49,6 +49,7 @@
 import android.util.Slog;
 
 import com.android.internal.infra.AndroidFuture;
+import com.android.server.utils.Slogf;
 
 import java.util.Collections;
 import java.util.List;
@@ -120,9 +121,6 @@
     private final BroadcastReceiver mTrustableDowngradeReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
-            if (!TrustManagerService.ENABLE_ACTIVE_UNLOCK_FLAG) {
-                return;
-            }
             // are these the broadcasts we want to listen to
             if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
                 downgradeToTrustable();
@@ -321,8 +319,8 @@
                 int flags,
                 AndroidFuture resultCallback) {
             if (DEBUG) {
-                Slog.d(TAG, "enableTrust(" + message + ", durationMs = " + durationMs
-                        + ", flags = " + flags + ")");
+                Slogf.d(TAG, "grantTrust(message=\"%s\", durationMs=%d, flags=0x%x)",
+                        message, durationMs, flags);
             }
 
             Message msg = mHandler.obtainMessage(
@@ -339,30 +337,32 @@
 
         @Override
         public void lockUser() {
+            if (DEBUG) Slog.d(TAG, "lockUser()");
             mHandler.sendEmptyMessage(MSG_LOCK_USER);
         }
 
         @Override
         public void setManagingTrust(boolean managingTrust) {
-            if (DEBUG) Slog.d(TAG, "managingTrust()");
+            if (DEBUG) Slogf.d(TAG, "setManagingTrust(%s)", managingTrust);
             mHandler.obtainMessage(MSG_MANAGING_TRUST, managingTrust ? 1 : 0, 0).sendToTarget();
         }
 
         @Override
         public void onConfigureCompleted(boolean result, IBinder token) {
-            if (DEBUG) Slog.d(TAG, "onSetTrustAgentFeaturesEnabledCompleted(result=" + result);
+            if (DEBUG) Slogf.d(TAG, "onConfigureCompleted(result=%s)", result);
             mHandler.obtainMessage(MSG_SET_TRUST_AGENT_FEATURES_COMPLETED,
                     result ? 1 : 0, 0, token).sendToTarget();
         }
 
         @Override
         public void addEscrowToken(byte[] token, int userId) {
+            // 'token' is secret; never log it.
+            if (DEBUG) Slogf.d(TAG, "addEscrowToken(userId=%d)", userId);
+
             if (mContext.getResources()
                     .getBoolean(com.android.internal.R.bool.config_allowEscrowTokenForTrustAgent)) {
-                throw  new SecurityException("Escrow token API is not allowed.");
+                throw new SecurityException("Escrow token API is not allowed.");
             }
-
-            if (DEBUG) Slog.d(TAG, "adding escrow token for user " + userId);
             Message msg = mHandler.obtainMessage(MSG_ADD_ESCROW_TOKEN);
             msg.getData().putByteArray(DATA_ESCROW_TOKEN, token);
             msg.getData().putInt(DATA_USER_ID, userId);
@@ -371,12 +371,12 @@
 
         @Override
         public void isEscrowTokenActive(long handle, int userId) {
+            if (DEBUG) Slogf.d(TAG, "isEscrowTokenActive(handle=%016x, userId=%d)", handle, userId);
+
             if (mContext.getResources()
                     .getBoolean(com.android.internal.R.bool.config_allowEscrowTokenForTrustAgent)) {
                 throw new SecurityException("Escrow token API is not allowed.");
             }
-
-            if (DEBUG) Slog.d(TAG, "checking the state of escrow token on user " + userId);
             Message msg = mHandler.obtainMessage(MSG_ESCROW_TOKEN_STATE);
             msg.getData().putLong(DATA_HANDLE, handle);
             msg.getData().putInt(DATA_USER_ID, userId);
@@ -385,12 +385,12 @@
 
         @Override
         public void removeEscrowToken(long handle, int userId) {
+            if (DEBUG) Slogf.d(TAG, "removeEscrowToken(handle=%016x, userId=%d)", handle, userId);
+
             if (mContext.getResources()
                     .getBoolean(com.android.internal.R.bool.config_allowEscrowTokenForTrustAgent)) {
                 throw new SecurityException("Escrow token API is not allowed.");
             }
-
-            if (DEBUG) Slog.d(TAG, "removing escrow token on user " + userId);
             Message msg = mHandler.obtainMessage(MSG_REMOVE_ESCROW_TOKEN);
             msg.getData().putLong(DATA_HANDLE, handle);
             msg.getData().putInt(DATA_USER_ID, userId);
@@ -399,12 +399,13 @@
 
         @Override
         public void unlockUserWithToken(long handle, byte[] token, int userId) {
+            // 'token' is secret; never log it.
+            if (DEBUG) Slogf.d(TAG, "unlockUserWithToken(handle=%016x, userId=%d)", handle, userId);
+
             if (mContext.getResources()
                     .getBoolean(com.android.internal.R.bool.config_allowEscrowTokenForTrustAgent)) {
                 throw new SecurityException("Escrow token API is not allowed.");
             }
-
-            if (DEBUG) Slog.d(TAG, "unlocking user " + userId);
             Message msg = mHandler.obtainMessage(MSG_UNLOCK_USER);
             msg.getData().putInt(DATA_USER_ID, userId);
             msg.getData().putLong(DATA_HANDLE, handle);
@@ -414,7 +415,7 @@
 
         @Override
         public void showKeyguardErrorMessage(CharSequence message) {
-            if (DEBUG) Slog.d(TAG, "Showing keyguard error message: " + message);
+            if (DEBUG) Slogf.d(TAG, "showKeyguardErrorMessage(\"%s\")", message);
             Message msg = mHandler.obtainMessage(MSG_SHOW_KEYGUARD_ERROR_MESSAGE);
             msg.getData().putCharSequence(DATA_MESSAGE, message);
             msg.sendToTarget();
diff --git a/services/core/java/com/android/server/trust/TrustManagerService.java b/services/core/java/com/android/server/trust/TrustManagerService.java
index afe8d3e..e3abf0c 100644
--- a/services/core/java/com/android/server/trust/TrustManagerService.java
+++ b/services/core/java/com/android/server/trust/TrustManagerService.java
@@ -53,11 +53,11 @@
 import android.os.DeadObjectException;
 import android.os.Handler;
 import android.os.IBinder;
+import android.os.Looper;
 import android.os.Message;
 import android.os.PersistableBundle;
 import android.os.RemoteException;
 import android.os.SystemClock;
-import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.provider.Settings;
@@ -151,6 +151,8 @@
     private final ArrayList<ITrustListener> mTrustListeners = new ArrayList<>();
     private final Receiver mReceiver = new Receiver();
 
+    private final Handler mHandler;
+
     /* package */ final TrustArchive mArchive = new TrustArchive();
     private final Context mContext;
     private final LockPatternUtils mLockPatternUtils;
@@ -158,18 +160,27 @@
     private final ActivityManager mActivityManager;
     private VirtualDeviceManagerInternal mVirtualDeviceManager;
 
-    @GuardedBy("mUserIsTrusted")
-    private final SparseBooleanArray mUserIsTrusted = new SparseBooleanArray();
-
-    //TODO(b/215724686): remove flag
-    public static final boolean ENABLE_ACTIVE_UNLOCK_FLAG = SystemProperties.getBoolean(
-            "fw.enable_active_unlock_flag", true);
-
     private enum TrustState {
-        UNTRUSTED, // the phone is not unlocked by any trustagents
-        TRUSTABLE, // the phone is in a semi-locked state that can be unlocked if
-        // FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE is passed and a trustagent is trusted
-        TRUSTED // the phone is unlocked
+        // UNTRUSTED means that TrustManagerService is currently *not* giving permission for the
+        // user's Keyguard to be dismissed, and grants of trust by trust agents are remembered in
+        // the corresponding TrustAgentWrapper but are not recognized until the device is unlocked
+        // for the user.  I.e., if the device is locked and the state is UNTRUSTED, it cannot be
+        // unlocked by a trust agent.  Automotive devices are an exception; grants of trust are
+        // always recognized on them.
+        UNTRUSTED,
+
+        // TRUSTABLE is the same as UNTRUSTED except that new grants of trust using
+        // FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE are recognized for moving to TRUSTED.  I.e., if
+        // the device is locked and the state is TRUSTABLE, it can be unlocked by a trust agent,
+        // provided that the trust agent chooses to use Active Unlock.  The TRUSTABLE state is only
+        // possible as a result of a downgrade from TRUSTED, after a trust agent used
+        // FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE in its most recent grant.
+        TRUSTABLE,
+
+        // TRUSTED means that TrustManagerService is currently giving permission for the user's
+        // Keyguard to be dismissed.  This implies that the device is unlocked for the user (where
+        // the case of Keyguard showing but dismissible just with swipe counts as "unlocked").
+        TRUSTED
     };
 
     @GuardedBy("mUserTrustState")
@@ -232,13 +243,40 @@
     private boolean mTrustAgentsCanRun = false;
     private int mCurrentUser = UserHandle.USER_SYSTEM;
 
+    /**
+     * A class for providing dependencies to {@link TrustManagerService} in both production and test
+     * cases.
+     */
+    protected static class Injector {
+        private final LockPatternUtils mLockPatternUtils;
+        private final Looper mLooper;
+
+        public Injector(LockPatternUtils lockPatternUtils, Looper looper) {
+            mLockPatternUtils = lockPatternUtils;
+            mLooper = looper;
+        }
+
+        LockPatternUtils getLockPatternUtils() {
+            return mLockPatternUtils;
+        }
+
+        Looper getLooper() {
+            return mLooper;
+        }
+    }
+
     public TrustManagerService(Context context) {
+        this(context, new Injector(new LockPatternUtils(context), Looper.myLooper()));
+    }
+
+    protected TrustManagerService(Context context, Injector injector) {
         super(context);
         mContext = context;
+        mHandler = createHandler(injector.getLooper());
         mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
         mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
-        mLockPatternUtils = new LockPatternUtils(context);
-        mStrongAuthTracker = new StrongAuthTracker(context);
+        mLockPatternUtils = injector.getLockPatternUtils();
+        mStrongAuthTracker = new StrongAuthTracker(context, injector.getLooper());
         mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
         mSettingsObserver = new SettingsObserver(mHandler);
     }
@@ -393,6 +431,23 @@
                 true /* overrideHardTimeout */);
     }
 
+    private void cancelBothTrustableAlarms(int userId) {
+        TrustableTimeoutAlarmListener idleTimeout =
+                mIdleTrustableTimeoutAlarmListenerForUser.get(
+                        userId);
+        TrustableTimeoutAlarmListener trustableTimeout =
+                mTrustableTimeoutAlarmListenerForUser.get(
+                        userId);
+        if (idleTimeout != null && idleTimeout.isQueued()) {
+            idleTimeout.setQueued(false);
+            mAlarmManager.cancel(idleTimeout);
+        }
+        if (trustableTimeout != null && trustableTimeout.isQueued()) {
+            trustableTimeout.setQueued(false);
+            mAlarmManager.cancel(trustableTimeout);
+        }
+    }
+
     private void handleScheduleTrustedTimeout(int userId, boolean shouldOverride) {
         long when = SystemClock.elapsedRealtime() + TRUST_TIMEOUT_IN_MILLIS;
         TrustedTimeoutAlarmListener alarm = mTrustTimeoutAlarmListenerForUser.get(userId);
@@ -521,69 +576,6 @@
             int flags,
             boolean isFromUnlock,
             @Nullable AndroidFuture<GrantTrustResult> resultCallback) {
-        if (ENABLE_ACTIVE_UNLOCK_FLAG) {
-            updateTrustWithRenewableUnlock(userId, flags, isFromUnlock, resultCallback);
-        } else {
-            updateTrustWithNonrenewableTrust(userId, flags, isFromUnlock);
-        }
-    }
-
-    private void updateTrustWithNonrenewableTrust(int userId, int flags, boolean isFromUnlock) {
-        boolean managed = aggregateIsTrustManaged(userId);
-        dispatchOnTrustManagedChanged(managed, userId);
-        if (mStrongAuthTracker.isTrustAllowedForUser(userId)
-                && isTrustUsuallyManagedInternal(userId) != managed) {
-            updateTrustUsuallyManaged(userId, managed);
-        }
-
-        boolean trusted = aggregateIsTrusted(userId);
-        IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
-        boolean showingKeyguard = true;
-        try {
-            showingKeyguard = wm.isKeyguardLocked();
-        } catch (RemoteException e) {
-        }
-
-        boolean changed;
-        synchronized (mUserIsTrusted) {
-            if (mSettingsObserver.getTrustAgentsNonrenewableTrust()) {
-                // For non-renewable trust agents can only set the device to trusted if it already
-                // trusted or the device is unlocked. Attempting to set the device as trusted
-                // when the device is locked will be ignored.
-                changed = mUserIsTrusted.get(userId) != trusted;
-                trusted = trusted
-                        && (!showingKeyguard || isFromUnlock || !changed)
-                        && userId == mCurrentUser;
-                if (DEBUG) {
-                    Slog.d(TAG, "Extend unlock setting trusted as " + Boolean.toString(trusted)
-                            + " && " + Boolean.toString(!showingKeyguard)
-                            + " && " + Boolean.toString(userId == mCurrentUser));
-                }
-            }
-            changed = mUserIsTrusted.get(userId) != trusted;
-            mUserIsTrusted.put(userId, trusted);
-        }
-        dispatchOnTrustChanged(
-                trusted,
-                false /* newlyUnlocked */,
-                userId,
-                flags,
-                getTrustGrantedMessages(userId));
-        if (changed) {
-            refreshDeviceLockedForUser(userId);
-            if (!trusted) {
-                maybeLockScreen(userId);
-            } else {
-                scheduleTrustTimeout(false /* override */, false /* isTrustableTimeout*/);
-            }
-        }
-    }
-
-    private void updateTrustWithRenewableUnlock(
-            int userId,
-            int flags,
-            boolean isFromUnlock,
-            @Nullable AndroidFuture<GrantTrustResult> resultCallback) {
         boolean managed = aggregateIsTrustManaged(userId);
         dispatchOnTrustManagedChanged(managed, userId);
         if (mStrongAuthTracker.isTrustAllowedForUser(userId)
@@ -657,6 +649,11 @@
                 resultCallback.complete(new GrantTrustResult(STATUS_UNLOCKED_BY_GRANT));
             }
         }
+
+        if ((wasTrusted || wasTrustable) && pendingTrustState == TrustState.UNTRUSTED) {
+            if (DEBUG) Slog.d(TAG, "Trust was revoked, destroy trustable alarms");
+            cancelBothTrustableAlarms(userId);
+        }
     }
 
     private void updateTrustUsuallyManaged(int userId, boolean managed) {
@@ -863,6 +860,12 @@
         }
     }
 
+    private TrustState getUserTrustStateInner(int userId) {
+        synchronized (mUserTrustState) {
+            return mUserTrustState.get(userId, TrustState.UNTRUSTED);
+        }
+    }
+
     boolean isDeviceLockedInner(int userId) {
         synchronized (mDeviceLockedForUser) {
             return mDeviceLockedForUser.get(userId, true);
@@ -913,7 +916,12 @@
                 continue;
             }
 
-            boolean trusted = aggregateIsTrusted(id);
+            final boolean trusted;
+            if (android.security.Flags.fixUnlockedDeviceRequiredKeys()) {
+                trusted = getUserTrustStateInner(id) == TrustState.TRUSTED;
+            } else {
+                trusted = aggregateIsTrusted(id);
+            }
             boolean showingKeyguard = true;
             boolean biometricAuthenticated = false;
             boolean currentUserIsUnlocked = false;
@@ -1414,6 +1422,23 @@
         }
     }
 
+    private void dispatchOnEnabledTrustAgentsChanged(int userId) {
+        if (DEBUG) {
+            Log.i(TAG, "onEnabledTrustAgentsChanged(" + userId + ")");
+        }
+        for (int i = 0; i < mTrustListeners.size(); i++) {
+            try {
+                mTrustListeners.get(i).onEnabledTrustAgentsChanged(userId);
+            } catch (DeadObjectException e) {
+                Slog.d(TAG, "Removing dead TrustListener.");
+                mTrustListeners.remove(i);
+                i--;
+            } catch (RemoteException e) {
+                Slog.e(TAG, "Exception while notifying TrustListener.", e);
+            }
+        }
+    }
+
     private void dispatchOnTrustManagedChanged(boolean managed, int userId) {
         if (DEBUG) {
             Log.i(TAG, "onTrustManagedChanged(" + managed + ", " + userId + ")");
@@ -1517,9 +1542,7 @@
         @Override
         public void reportEnabledTrustAgentsChanged(int userId) throws RemoteException {
             enforceReportPermission();
-            // coalesce refresh messages.
-            mHandler.removeMessages(MSG_ENABLED_AGENTS_CHANGED);
-            mHandler.sendEmptyMessage(MSG_ENABLED_AGENTS_CHANGED);
+            mHandler.obtainMessage(MSG_ENABLED_AGENTS_CHANGED, userId, 0).sendToTarget();
         }
 
         @Override
@@ -1677,7 +1700,7 @@
             if (isCurrent) {
                 fout.print(" (current)");
             }
-            fout.print(": trusted=" + dumpBool(aggregateIsTrusted(user.id)));
+            fout.print(": trustState=" + getUserTrustStateInner(user.id));
             fout.print(", trustManaged=" + dumpBool(aggregateIsTrustManaged(user.id)));
             fout.print(", deviceLocked=" + dumpBool(isDeviceLockedInner(user.id)));
             fout.print(", strongAuthRequired=" + dumpHex(
@@ -1830,84 +1853,91 @@
         }
     }
 
-    private final Handler mHandler = new Handler() {
-        @Override
-        public void handleMessage(Message msg) {
-            switch (msg.what) {
-                case MSG_REGISTER_LISTENER:
-                    addListener((ITrustListener) msg.obj);
-                    break;
-                case MSG_UNREGISTER_LISTENER:
-                    removeListener((ITrustListener) msg.obj);
-                    break;
-                case MSG_DISPATCH_UNLOCK_ATTEMPT:
-                    dispatchUnlockAttempt(msg.arg1 != 0, msg.arg2);
-                    break;
-                case MSG_USER_REQUESTED_UNLOCK:
-                    dispatchUserRequestedUnlock(msg.arg1, msg.arg2 != 0);
-                    break;
-                case MSG_USER_MAY_REQUEST_UNLOCK:
-                    dispatchUserMayRequestUnlock(msg.arg1);
-                    break;
-                case MSG_DISPATCH_UNLOCK_LOCKOUT:
-                    dispatchUnlockLockout(msg.arg1, msg.arg2);
-                    break;
-                case MSG_ENABLED_AGENTS_CHANGED:
-                    refreshAgentList(UserHandle.USER_ALL);
-                    // This is also called when the security mode of a user changes.
-                    refreshDeviceLockedForUser(UserHandle.USER_ALL);
-                    break;
-                case MSG_KEYGUARD_SHOWING_CHANGED:
-                    dispatchTrustableDowngrade();
-                    refreshDeviceLockedForUser(mCurrentUser);
-                    break;
-                case MSG_START_USER:
-                case MSG_CLEANUP_USER:
-                case MSG_UNLOCK_USER:
-                    refreshAgentList(msg.arg1);
-                    break;
-                case MSG_SWITCH_USER:
-                    mCurrentUser = msg.arg1;
-                    mSettingsObserver.updateContentObserver();
-                    refreshDeviceLockedForUser(UserHandle.USER_ALL);
-                    break;
-                case MSG_STOP_USER:
-                    setDeviceLockedForUser(msg.arg1, true);
-                    break;
-                case MSG_FLUSH_TRUST_USUALLY_MANAGED:
-                    SparseBooleanArray usuallyManaged;
-                    synchronized (mTrustUsuallyManagedForUser) {
-                        usuallyManaged = mTrustUsuallyManagedForUser.clone();
-                    }
-
-                    for (int i = 0; i < usuallyManaged.size(); i++) {
-                        int userId = usuallyManaged.keyAt(i);
-                        boolean value = usuallyManaged.valueAt(i);
-                        if (value != mLockPatternUtils.isTrustUsuallyManaged(userId)) {
-                            mLockPatternUtils.setTrustUsuallyManaged(value, userId);
+    private Handler createHandler(Looper looper) {
+        return new Handler(looper) {
+            @Override
+            public void handleMessage(Message msg) {
+                switch (msg.what) {
+                    case MSG_REGISTER_LISTENER:
+                        addListener((ITrustListener) msg.obj);
+                        break;
+                    case MSG_UNREGISTER_LISTENER:
+                        removeListener((ITrustListener) msg.obj);
+                        break;
+                    case MSG_DISPATCH_UNLOCK_ATTEMPT:
+                        dispatchUnlockAttempt(msg.arg1 != 0, msg.arg2);
+                        break;
+                    case MSG_USER_REQUESTED_UNLOCK:
+                        dispatchUserRequestedUnlock(msg.arg1, msg.arg2 != 0);
+                        break;
+                    case MSG_USER_MAY_REQUEST_UNLOCK:
+                        dispatchUserMayRequestUnlock(msg.arg1);
+                        break;
+                    case MSG_DISPATCH_UNLOCK_LOCKOUT:
+                        dispatchUnlockLockout(msg.arg1, msg.arg2);
+                        break;
+                    case MSG_ENABLED_AGENTS_CHANGED:
+                        refreshAgentList(UserHandle.USER_ALL);
+                        // This is also called when the security mode of a user changes.
+                        refreshDeviceLockedForUser(UserHandle.USER_ALL);
+                        dispatchOnEnabledTrustAgentsChanged(msg.arg1);
+                        break;
+                    case MSG_KEYGUARD_SHOWING_CHANGED:
+                        dispatchTrustableDowngrade();
+                        refreshDeviceLockedForUser(mCurrentUser);
+                        break;
+                    case MSG_START_USER:
+                    case MSG_CLEANUP_USER:
+                    case MSG_UNLOCK_USER:
+                        refreshAgentList(msg.arg1);
+                        break;
+                    case MSG_SWITCH_USER:
+                        mCurrentUser = msg.arg1;
+                        mSettingsObserver.updateContentObserver();
+                        refreshDeviceLockedForUser(UserHandle.USER_ALL);
+                        break;
+                    case MSG_STOP_USER:
+                        setDeviceLockedForUser(msg.arg1, true);
+                        break;
+                    case MSG_FLUSH_TRUST_USUALLY_MANAGED:
+                        SparseBooleanArray usuallyManaged;
+                        synchronized (mTrustUsuallyManagedForUser) {
+                            usuallyManaged = mTrustUsuallyManagedForUser.clone();
                         }
-                    }
-                    break;
-                case MSG_REFRESH_DEVICE_LOCKED_FOR_USER:
-                    if (msg.arg2 == 1) {
-                        updateTrust(msg.arg1, 0 /* flags */, true /* isFromUnlock */, null);
-                    }
-                    final int unlockedUser = msg.getData().getInt(
-                            REFRESH_DEVICE_LOCKED_EXCEPT_USER, UserHandle.USER_NULL);
-                    refreshDeviceLockedForUser(msg.arg1, unlockedUser);
-                    break;
-                case MSG_SCHEDULE_TRUST_TIMEOUT:
-                    boolean shouldOverride = msg.arg1 == 1 ? true : false;
-                    TimeoutType timeoutType =
-                            msg.arg2 == 1 ? TimeoutType.TRUSTABLE : TimeoutType.TRUSTED;
-                    handleScheduleTrustTimeout(shouldOverride, timeoutType);
-                    break;
-                case MSG_REFRESH_TRUSTABLE_TIMERS_AFTER_AUTH:
-                    refreshTrustableTimers(msg.arg1);
-                    break;
+
+                        for (int i = 0; i < usuallyManaged.size(); i++) {
+                            int userId = usuallyManaged.keyAt(i);
+                            boolean value = usuallyManaged.valueAt(i);
+                            if (value != mLockPatternUtils.isTrustUsuallyManaged(userId)) {
+                                mLockPatternUtils.setTrustUsuallyManaged(value, userId);
+                            }
+                        }
+                        break;
+                    case MSG_REFRESH_DEVICE_LOCKED_FOR_USER:
+                        if (msg.arg2 == 1) {
+                            updateTrust(msg.arg1, 0 /* flags */, true /* isFromUnlock */, null);
+                        }
+                        final int unlockedUser = msg.getData().getInt(
+                                REFRESH_DEVICE_LOCKED_EXCEPT_USER, UserHandle.USER_NULL);
+                        refreshDeviceLockedForUser(msg.arg1, unlockedUser);
+                        break;
+                    case MSG_SCHEDULE_TRUST_TIMEOUT:
+                        boolean shouldOverride = msg.arg1 == 1 ? true : false;
+                        TimeoutType timeoutType =
+                                msg.arg2 == 1 ? TimeoutType.TRUSTABLE : TimeoutType.TRUSTED;
+                        handleScheduleTrustTimeout(shouldOverride, timeoutType);
+                        break;
+                    case MSG_REFRESH_TRUSTABLE_TIMERS_AFTER_AUTH:
+                        TrustableTimeoutAlarmListener trustableAlarm =
+                                mTrustableTimeoutAlarmListenerForUser.get(msg.arg1);
+                        if (trustableAlarm != null && trustableAlarm.isQueued()) {
+                            refreshTrustableTimers(msg.arg1);
+                        }
+                        break;
+                }
             }
-        }
-    };
+        };
+    }
 
     private final PackageMonitor mPackageMonitor = new PackageMonitor() {
         @Override
@@ -1962,9 +1992,6 @@
             } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
                 int userId = getUserId(intent);
                 if (userId > 0) {
-                    synchronized (mUserIsTrusted) {
-                        mUserIsTrusted.delete(userId);
-                    }
                     synchronized (mDeviceLockedForUser) {
                         mDeviceLockedForUser.delete(userId);
                     }
@@ -2008,8 +2035,8 @@
 
         SparseBooleanArray mStartFromSuccessfulUnlock = new SparseBooleanArray();
 
-        public StrongAuthTracker(Context context) {
-            super(context);
+        StrongAuthTracker(Context context, Looper looper) {
+            super(context, looper);
         }
 
         @Override
@@ -2118,16 +2145,11 @@
 
         @Override
         public void handleAlarm() {
-            TrustableTimeoutAlarmListener otherAlarm;
-            boolean otherAlarmPresent;
-            if (ENABLE_ACTIVE_UNLOCK_FLAG) {
-                otherAlarm = mTrustableTimeoutAlarmListenerForUser.get(mUserId);
-                otherAlarmPresent = (otherAlarm != null) && otherAlarm.isQueued();
-                if (otherAlarmPresent) {
-                    synchronized (mAlarmLock) {
-                        disableNonrenewableTrustWhileRenewableTrustIsPresent();
-                    }
-                    return;
+            TrustableTimeoutAlarmListener otherAlarm =
+                    mTrustableTimeoutAlarmListenerForUser.get(mUserId);
+            if (otherAlarm != null && otherAlarm.isQueued()) {
+                synchronized (mAlarmLock) {
+                    disableNonrenewableTrustWhileRenewableTrustIsPresent();
                 }
             }
         }
@@ -2152,38 +2174,15 @@
 
         @Override
         public void handleAlarm() {
-            TrustedTimeoutAlarmListener otherAlarm;
-            boolean otherAlarmPresent;
-            if (ENABLE_ACTIVE_UNLOCK_FLAG) {
-                cancelBothTrustableAlarms();
-                otherAlarm = mTrustTimeoutAlarmListenerForUser.get(mUserId);
-                otherAlarmPresent = (otherAlarm != null) && otherAlarm.isQueued();
-                if (otherAlarmPresent) {
-                    synchronized (mAlarmLock) {
-                        disableRenewableTrustWhileNonrenewableTrustIsPresent();
-                    }
-                    return;
+            cancelBothTrustableAlarms(mUserId);
+            TrustedTimeoutAlarmListener otherAlarm = mTrustTimeoutAlarmListenerForUser.get(mUserId);
+            if (otherAlarm != null && otherAlarm.isQueued()) {
+                synchronized (mAlarmLock) {
+                    disableRenewableTrustWhileNonrenewableTrustIsPresent();
                 }
             }
         }
 
-        private void cancelBothTrustableAlarms() {
-            TrustableTimeoutAlarmListener idleTimeout =
-                    mIdleTrustableTimeoutAlarmListenerForUser.get(
-                            mUserId);
-            TrustableTimeoutAlarmListener trustableTimeout =
-                    mTrustableTimeoutAlarmListenerForUser.get(
-                            mUserId);
-            if (idleTimeout != null && idleTimeout.isQueued()) {
-                idleTimeout.setQueued(false);
-                mAlarmManager.cancel(idleTimeout);
-            }
-            if (trustableTimeout != null && trustableTimeout.isQueued()) {
-                trustableTimeout.setQueued(false);
-                mAlarmManager.cancel(trustableTimeout);
-            }
-        }
-
         private void disableRenewableTrustWhileNonrenewableTrustIsPresent() {
             // if non-renewable trust is running, we need to temporarily prevent
             // renewable trust from being used
diff --git a/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java b/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java
index ca4a32f..099c9ae 100644
--- a/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java
+++ b/services/core/java/com/android/server/vcn/TelephonySubscriptionTracker.java
@@ -16,9 +16,6 @@
 
 package com.android.server.vcn;
 
-import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
-import static android.telephony.CarrierConfigManager.EXTRA_SLOT_INDEX;
-import static android.telephony.CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX;
 import static android.telephony.SubscriptionManager.INVALID_SIM_SLOT_INDEX;
 import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
 import static android.telephony.TelephonyManager.ACTION_MULTI_SIM_CONFIG_CHANGED;
@@ -48,7 +45,6 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.annotations.VisibleForTesting.Visibility;
 import com.android.internal.util.IndentingPrintWriter;
-import com.android.server.vcn.util.PersistableBundleUtils;
 import com.android.server.vcn.util.PersistableBundleUtils.PersistableBundleWrapper;
 
 import java.util.ArrayList;
@@ -109,6 +105,12 @@
 
     @NonNull private TelephonySubscriptionSnapshot mCurrentSnapshot;
 
+    @NonNull
+    private final CarrierConfigManager.CarrierConfigChangeListener mCarrierConfigChangeListener =
+            (int logicalSlotIndex, int subscriptionId, int carrierId, int specificCarrierId) ->
+                    handleActionCarrierConfigChanged(logicalSlotIndex, subscriptionId);
+
+
     public TelephonySubscriptionTracker(
             @NonNull Context context,
             @NonNull Handler handler,
@@ -149,13 +151,14 @@
     public void register() {
         final HandlerExecutor executor = new HandlerExecutor(mHandler);
         final IntentFilter filter = new IntentFilter();
-        filter.addAction(ACTION_CARRIER_CONFIG_CHANGED);
         filter.addAction(ACTION_MULTI_SIM_CONFIG_CHANGED);
 
         mContext.registerReceiver(this, filter, null, mHandler);
         mSubscriptionManager.addOnSubscriptionsChangedListener(
                 executor, mSubscriptionChangedListener);
         mTelephonyManager.registerTelephonyCallback(executor, mActiveDataSubIdListener);
+        mCarrierConfigManager.registerCarrierConfigChangeListener(executor,
+                mCarrierConfigChangeListener);
 
         registerCarrierPrivilegesCallbacks();
     }
@@ -197,6 +200,7 @@
         mContext.unregisterReceiver(this);
         mSubscriptionManager.removeOnSubscriptionsChangedListener(mSubscriptionChangedListener);
         mTelephonyManager.unregisterTelephonyCallback(mActiveDataSubIdListener);
+        mCarrierConfigManager.unregisterCarrierConfigChangeListener(mCarrierConfigChangeListener);
 
         unregisterCarrierPrivilegesCallbacks();
     }
@@ -273,7 +277,7 @@
     }
 
     /**
-     * Broadcast receiver for ACTION_CARRIER_CONFIG_CHANGED
+     * Broadcast receiver for ACTION_MULTI_SIM_CONFIG_CHANGED
      *
      * <p>The broadcast receiver is registered with mHandler, so callbacks & broadcasts are all
      * serialized on mHandler, avoiding the need for locking.
@@ -281,9 +285,6 @@
     @Override
     public void onReceive(Context context, Intent intent) {
         switch (intent.getAction()) {
-            case ACTION_CARRIER_CONFIG_CHANGED:
-                handleActionCarrierConfigChanged(context, intent);
-                break;
             case ACTION_MULTI_SIM_CONFIG_CHANGED:
                 handleActionMultiSimConfigChanged(context, intent);
                 break;
@@ -310,26 +311,21 @@
         handleSubscriptionsChanged();
     }
 
-    private void handleActionCarrierConfigChanged(Context context, Intent intent) {
-        // Accept sticky broadcasts; if CARRIER_CONFIG_CHANGED was previously broadcast and it
-        // already was for an identified carrier, we can stop waiting for initial load to complete
-        final int subId = intent.getIntExtra(EXTRA_SUBSCRIPTION_INDEX, INVALID_SUBSCRIPTION_ID);
-        final int slotId = intent.getIntExtra(EXTRA_SLOT_INDEX, INVALID_SIM_SLOT_INDEX);
-
+    private void handleActionCarrierConfigChanged(int slotId, int subId) {
         if (slotId == INVALID_SIM_SLOT_INDEX) {
             return;
         }
 
         if (SubscriptionManager.isValidSubscriptionId(subId)) {
-            final PersistableBundle carrierConfig = mCarrierConfigManager.getConfigForSubId(subId);
+            // Get only configs as needed to save memory.
+            final PersistableBundle carrierConfig = mCarrierConfigManager.getConfigForSubId(subId,
+                    VcnManager.VCN_RELATED_CARRIER_CONFIG_KEYS);
             if (mDeps.isConfigForIdentifiedCarrier(carrierConfig)) {
                 mReadySubIdsBySlotId.put(slotId, subId);
 
-                final PersistableBundle minimized =
-                        PersistableBundleUtils.minimizeBundle(
-                                carrierConfig, VcnManager.VCN_RELATED_CARRIER_CONFIG_KEYS);
-                if (minimized != null) {
-                    mSubIdToCarrierConfigMap.put(subId, new PersistableBundleWrapper(minimized));
+                if (!carrierConfig.isEmpty()) {
+                    mSubIdToCarrierConfigMap.put(subId,
+                            new PersistableBundleWrapper(carrierConfig));
                 }
                 handleSubscriptionsChanged();
             }
diff --git a/services/core/java/com/android/server/vibrator/SetAmplitudeVibratorStep.java b/services/core/java/com/android/server/vibrator/SetAmplitudeVibratorStep.java
index 6fb9111..959b94b 100644
--- a/services/core/java/com/android/server/vibrator/SetAmplitudeVibratorStep.java
+++ b/services/core/java/com/android/server/vibrator/SetAmplitudeVibratorStep.java
@@ -167,7 +167,9 @@
         while (i < segmentCount) {
             VibrationEffectSegment segment = segments.get(i);
             if (!(segment instanceof StepSegment)
-                    || ((StepSegment) segment).getAmplitude() == 0) {
+                    // play() will ignore segments with zero duration, so it's important that
+                    // zero-duration segments don't affect this method.
+                    || (segment.getDuration() > 0 && ((StepSegment) segment).getAmplitude() == 0)) {
                 break;
             }
             timing += segment.getDuration();
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index f5a41c9..b12d8bd 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -6302,9 +6302,9 @@
             // Don't do recursive work.
             return;
         }
-        mInEnsureActivitiesVisible = true;
         mAtmService.mTaskSupervisor.beginActivityVisibilityUpdate();
         try {
+            mInEnsureActivitiesVisible = true;
             forAllRootTasks(rootTask -> {
                 rootTask.ensureActivitiesVisible(starting, configChanges, preserveWindows,
                         notifyClients);
diff --git a/services/core/java/com/android/server/wm/LetterboxUiController.java b/services/core/java/com/android/server/wm/LetterboxUiController.java
index 4b2cb7d..684e787 100644
--- a/services/core/java/com/android/server/wm/LetterboxUiController.java
+++ b/services/core/java/com/android/server/wm/LetterboxUiController.java
@@ -48,9 +48,9 @@
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ALLOW_REFRESH;
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ENABLE_REFRESH_VIA_PAUSE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_DISPLAY_ORIENTATION_OVERRIDE;
+import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_IGNORING_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED;
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ENABLE_FAKE_FOCUS;
-import static android.view.WindowManager.PROPERTY_COMPAT_IGNORE_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED;
 import static android.view.WindowManager.PROPERTY_COMPAT_IGNORE_REQUESTED_ORIENTATION;
 
 import static com.android.internal.util.FrameworkStatsLog.APP_COMPAT_STATE_CHANGED__LETTERBOX_POSITION__BOTTOM;
@@ -241,7 +241,7 @@
     private final Boolean mBooleanPropertyIgnoreRequestedOrientation;
 
     @Nullable
-    private final Boolean mBooleanPropertyIgnoreOrientationRequestWhenLoopDetected;
+    private final Boolean mBooleanPropertyAllowIgnoringOrientationRequestWhenLoopDetected;
 
     @Nullable
     private final Boolean mBooleanPropertyFakeFocus;
@@ -264,10 +264,10 @@
                 readComponentProperty(packageManager, mActivityRecord.packageName,
                         mLetterboxConfiguration::isPolicyForIgnoringRequestedOrientationEnabled,
                         PROPERTY_COMPAT_IGNORE_REQUESTED_ORIENTATION);
-        mBooleanPropertyIgnoreOrientationRequestWhenLoopDetected =
+        mBooleanPropertyAllowIgnoringOrientationRequestWhenLoopDetected =
                 readComponentProperty(packageManager, mActivityRecord.packageName,
                         mLetterboxConfiguration::isPolicyForIgnoringRequestedOrientationEnabled,
-                        PROPERTY_COMPAT_IGNORE_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED);
+                        PROPERTY_COMPAT_ALLOW_IGNORING_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED);
         mBooleanPropertyFakeFocus =
                 readComponentProperty(packageManager, mActivityRecord.packageName,
                         mLetterboxConfiguration::isCompatFakeFocusEnabled,
@@ -453,7 +453,7 @@
                 /* gatingCondition */ mLetterboxConfiguration
                     ::isPolicyForIgnoringRequestedOrientationEnabled,
                 mIsOverrideEnableCompatIgnoreOrientationRequestWhenLoopDetectedEnabled,
-                mBooleanPropertyIgnoreOrientationRequestWhenLoopDetected)) {
+                mBooleanPropertyAllowIgnoringOrientationRequestWhenLoopDetected)) {
             return false;
         }
 
diff --git a/services/core/java/com/android/server/wm/OWNERS b/services/core/java/com/android/server/wm/OWNERS
index 0af9fe9..26abe51 100644
--- a/services/core/java/com/android/server/wm/OWNERS
+++ b/services/core/java/com/android/server/wm/OWNERS
@@ -18,4 +18,4 @@
 yunfanc@google.com
 
 per-file BackgroundActivityStartController.java = set noparent
-per-file BackgroundActivityStartController.java = brufino@google.com, ogunwale@google.com, louischang@google.com, lus@google.com, rickywai@google.com
+per-file BackgroundActivityStartController.java = brufino@google.com, ogunwale@google.com, louischang@google.com, lus@google.com
diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java
index 10673a3..23ea6d7 100644
--- a/services/core/java/com/android/server/wm/RootWindowContainer.java
+++ b/services/core/java/com/android/server/wm/RootWindowContainer.java
@@ -1833,9 +1833,8 @@
             // Don't do recursive work.
             return;
         }
-
+        mTaskSupervisor.beginActivityVisibilityUpdate();
         try {
-            mTaskSupervisor.beginActivityVisibilityUpdate();
             // First the front root tasks. In case any are not fullscreen and are in front of home.
             for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
                 final DisplayContent display = getChildAt(displayNdx);
diff --git a/services/core/java/com/android/server/wm/SurfaceAnimationRunner.java b/services/core/java/com/android/server/wm/SurfaceAnimationRunner.java
index 1ae7816..b93dbce 100644
--- a/services/core/java/com/android/server/wm/SurfaceAnimationRunner.java
+++ b/services/core/java/com/android/server/wm/SurfaceAnimationRunner.java
@@ -62,6 +62,8 @@
  */
 class SurfaceAnimationRunner {
 
+    private static final String TAG = SurfaceAnimationRunner.class.getSimpleName();
+
     private final Object mLock = new Object();
 
     /**
@@ -185,6 +187,16 @@
                 // We must wait for t to be committed since otherwise the leash doesn't have the
                 // windows we want to screenshot and extend as children.
                 t.addTransactionCommittedListener(mEdgeExtensionExecutor, () -> {
+                    if (!animationLeash.isValid()) {
+                        Log.e(TAG, "Animation leash is not valid");
+                        synchronized (mEdgeExtensionLock) {
+                            mEdgeExtensions.remove(animationLeash);
+                        }
+                        synchronized (mLock) {
+                            mPreProcessingAnimations.remove(animationLeash);
+                        }
+                        return;
+                    }
                     final WindowAnimationSpec animationSpec = a.asWindowAnimationSpec();
 
                     final Transaction edgeExtensionCreationTransaction = new Transaction();
@@ -449,8 +461,7 @@
             // The leash we are trying to screenshot may have been removed by this point, which is
             // likely the reason for ending up with a null edgeBuffer, in which case we just want to
             // return and do nothing.
-            Log.e("SurfaceAnimationRunner", "Failed to create edge extension - "
-                    + "edge buffer is null");
+            Log.e(TAG, "Failed to create edge extension - edge buffer is null");
             return;
         }
 
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 91c0c69..bda0a0f 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -5748,7 +5748,7 @@
                 false /* deferResume */);
 
         ActivityRecord topActivity = getDisplayArea().topRunningActivity();
-        Task topRootTask = topActivity.getRootTask();
+        Task topRootTask = topActivity == null ? null : topActivity.getRootTask();
         if (topRootTask != null && topRootTask != this && topActivity.isState(RESUMED)) {
             // Usually resuming a top activity triggers the next app transition, but nothing's got
             // resumed in this case, so we need to execute it explicitly.
diff --git a/services/core/java/com/android/server/wm/TaskFragment.java b/services/core/java/com/android/server/wm/TaskFragment.java
index d947168..15bc60c 100644
--- a/services/core/java/com/android/server/wm/TaskFragment.java
+++ b/services/core/java/com/android/server/wm/TaskFragment.java
@@ -1089,21 +1089,13 @@
             }
 
             final int otherWindowingMode = other.getWindowingMode();
-            if (otherWindowingMode == WINDOWING_MODE_FULLSCREEN) {
-                if (isTranslucent(other, starting)) {
-                    // Can be visible behind a translucent fullscreen TaskFragment.
-                    gotTranslucentFullscreen = true;
-                    continue;
-                }
-                return TASK_FRAGMENT_VISIBILITY_INVISIBLE;
-            } else if (otherWindowingMode == WINDOWING_MODE_MULTI_WINDOW
-                    && other.matchParentBounds()) {
+            if (otherWindowingMode == WINDOWING_MODE_FULLSCREEN
+                    || (otherWindowingMode != WINDOWING_MODE_PINNED && other.matchParentBounds())) {
                 if (isTranslucent(other, starting)) {
                     // Can be visible behind a translucent TaskFragment.
                     gotTranslucentFullscreen = true;
                     continue;
                 }
-                // Multi-window TaskFragment that matches parent bounds would occlude other children
                 return TASK_FRAGMENT_VISIBILITY_INVISIBLE;
             }
 
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 2d21e71..95fea0e 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -2053,19 +2053,16 @@
 
     /**
      * Like isOnScreen(), but we don't return true if the window is part
-     * of a transition but has not yet started animating.
+     * of a transition that has not yet been started.
      */
     boolean isReadyForDisplay() {
-        if (!mHasSurface || mDestroying || !isVisibleByPolicy()) {
-            return false;
-        }
-        if (mToken.waitingToShow && getDisplayContent().mAppTransition.isTransitionSet()
-                && !isAnimating(TRANSITION | PARENTS, ANIMATION_TYPE_APP_TRANSITION)) {
+        if (mToken.waitingToShow && getDisplayContent().mAppTransition.isTransitionSet()) {
             return false;
         }
         final boolean parentAndClientVisible = !isParentWindowHidden()
                 && mViewVisibility == View.VISIBLE && mToken.isVisible();
-        return parentAndClientVisible || isAnimating(TRANSITION | PARENTS, ANIMATION_TYPE_ALL);
+        return mHasSurface && isVisibleByPolicy() && !mDestroying
+                && (parentAndClientVisible || isAnimating(TRANSITION | PARENTS));
     }
 
     boolean isFullyTransparent() {
diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp
index 075991e..10f1db1 100644
--- a/services/core/jni/Android.bp
+++ b/services/core/jni/Android.bp
@@ -160,7 +160,6 @@
         "android.hardware.graphics.bufferqueue@1.0",
         "android.hardware.graphics.bufferqueue@2.0",
         "android.hardware.graphics.common@1.2",
-        "android.hardware.graphics.mapper@4.0",
         "android.hardware.input.processor-V1-ndk",
         "android.hardware.ir@1.0",
         "android.hardware.light@2.0",
diff --git a/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp b/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
index af5718f..37b1047 100644
--- a/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
+++ b/services/core/jni/com_android_server_am_CachedAppOptimizer.cpp
@@ -51,6 +51,9 @@
 using android::meminfo::ProcMemInfo;
 using namespace android::meminfo;
 
+static const size_t kPageSize = getpagesize();
+static const size_t kPageMask = ~(kPageSize - 1);
+
 #define COMPACT_ACTION_FILE_FLAG 1
 #define COMPACT_ACTION_ANON_FLAG 2
 
@@ -61,7 +64,7 @@
 #define ASYNC_RECEIVED_WHILE_FROZEN (2)
 #define TXNS_PENDING_WHILE_FROZEN (4)
 
-#define MAX_RW_COUNT (INT_MAX & PAGE_MASK)
+#define MAX_RW_COUNT (INT_MAX & kPageMask)
 
 // Defines the maximum amount of VMAs we can send per process_madvise syscall.
 // Currently this is set to UIO_MAXIOV which is the maximum segments allowed by
@@ -249,7 +252,7 @@
     } else if (bytesProcessedInSend < batch.totalBytes) {
         // Partially processed the bytes requested
         // skip last page which is where it failed.
-        bytesProcessedInSend += PAGE_SIZE;
+        bytesProcessedInSend += kPageSize;
     }
     bytesProcessedInSend = consumeBytes(batch, bytesProcessedInSend);
 
diff --git a/services/core/jni/gnss/GnssVisibilityControlCallback.cpp b/services/core/jni/gnss/GnssVisibilityControlCallback.cpp
index ec215f1..bc57c1d 100644
--- a/services/core/jni/gnss/GnssVisibilityControlCallback.cpp
+++ b/services/core/jni/gnss/GnssVisibilityControlCallback.cpp
@@ -73,7 +73,7 @@
 
 template <>
 jstring ToJstring(JNIEnv* env, const String16& value) {
-    const char16_t* str = value.string();
+    const char16_t* str = value.c_str();
     size_t len = value.size();
     return env->NewString(reinterpret_cast<const jchar*>(str), len);
 }
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyVersionUpgrader.java b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyVersionUpgrader.java
index 253851c..29b80e6 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/PolicyVersionUpgrader.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/PolicyVersionUpgrader.java
@@ -29,6 +29,7 @@
 import java.io.IOException;
 import java.nio.charset.Charset;
 import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -251,6 +252,8 @@
             String versionString = Files.readAllLines(
                     file.toPath(), Charset.defaultCharset()).get(0);
             return Integer.parseInt(versionString);
+        } catch (NoSuchFileException e) {
+            return 0; // expected on first boot
         } catch (IOException | NumberFormatException | IndexOutOfBoundsException e) {
             Slog.e(LOG_TAG, "Error reading version", e);
             return 0;
diff --git a/services/foldables/devicestateprovider/OWNERS b/services/foldables/devicestateprovider/OWNERS
new file mode 100644
index 0000000..5732844
--- /dev/null
+++ b/services/foldables/devicestateprovider/OWNERS
@@ -0,0 +1,6 @@
+akulian@google.com
+jiamingliu@google.com
+kchyn@google.com
+kennethford@google.com
+nickchameyev@google.com
+nicomazz@google.com
\ No newline at end of file
diff --git a/services/net/OWNERS b/services/net/OWNERS
index 62c5737..c24680e9 100644
--- a/services/net/OWNERS
+++ b/services/net/OWNERS
@@ -1,2 +1,2 @@
 set noparent
-file:platform/packages/modules/Connectivity:master:/OWNERS_core_networking
+file:platform/packages/modules/Connectivity:main:/OWNERS_core_networking
diff --git a/services/net/java/android/net/util/NetworkConstants.java b/services/net/java/android/net/util/NetworkConstants.java
index ea5ce65..49962ea 100644
--- a/services/net/java/android/net/util/NetworkConstants.java
+++ b/services/net/java/android/net/util/NetworkConstants.java
@@ -52,7 +52,6 @@
     public static final int IPV6_ADDR_BITS = 128;
     public static final int IPV6_ADDR_LEN = 16;
     public static final int IPV6_MIN_MTU = 1280;
-    public static final int RFC7421_PREFIX_LENGTH = 64;
 
     /**
      * ICMP common (v4/v6) constants.
diff --git a/services/tests/PackageManagerServiceTests/server/src/com/android/server/parsing/PackageParserLegacyCoreTest.java b/services/tests/PackageManagerServiceTests/server/src/com/android/server/parsing/PackageParserLegacyCoreTest.java
index c6a6340..8961072d 100644
--- a/services/tests/PackageManagerServiceTests/server/src/com/android/server/parsing/PackageParserLegacyCoreTest.java
+++ b/services/tests/PackageManagerServiceTests/server/src/com/android/server/parsing/PackageParserLegacyCoreTest.java
@@ -111,7 +111,8 @@
                 minSdkCodename,
                 PLATFORM_VERSION,
                 isPlatformReleased ? CODENAMES_RELEASED : CODENAMES_PRE_RELEASE,
-                input);
+                input,
+                null);
 
         if (expectedMinSdk == -1) {
             assertTrue(result.isError());
@@ -206,7 +207,7 @@
                 targetSdkCodename,
                 isPlatformReleased ? CODENAMES_RELEASED : CODENAMES_PRE_RELEASE,
                 input,
-                allowUnknownCodenames);
+                allowUnknownCodenames, null);
 
         if (expectedTargetSdk == -1) {
             assertTrue(result.isError());
diff --git a/services/tests/RemoteProvisioningServiceTests/OWNERS b/services/tests/RemoteProvisioningServiceTests/OWNERS
index 348f940..ea6dc72 100644
--- a/services/tests/RemoteProvisioningServiceTests/OWNERS
+++ b/services/tests/RemoteProvisioningServiceTests/OWNERS
@@ -1 +1 @@
-file:platform/frameworks/base:master:/core/java/android/security/rkp/OWNERS
+file:platform/frameworks/base:main:/core/java/android/security/rkp/OWNERS
diff --git a/services/tests/RemoteProvisioningServiceTests/src/com/android/server/security/rkp/RemoteProvisioningShellCommandTest.java b/services/tests/RemoteProvisioningServiceTests/src/com/android/server/security/rkp/RemoteProvisioningShellCommandTest.java
index 2d93120..007c0db 100644
--- a/services/tests/RemoteProvisioningServiceTests/src/com/android/server/security/rkp/RemoteProvisioningShellCommandTest.java
+++ b/services/tests/RemoteProvisioningServiceTests/src/com/android/server/security/rkp/RemoteProvisioningShellCommandTest.java
@@ -21,12 +21,14 @@
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import android.content.Context;
 import android.hardware.security.keymint.DeviceInfo;
 import android.hardware.security.keymint.IRemotelyProvisionedComponent;
 import android.hardware.security.keymint.MacedPublicKey;
@@ -34,28 +36,35 @@
 import android.hardware.security.keymint.RpcHardwareInfo;
 import android.os.Binder;
 import android.os.FileUtils;
+import android.os.OutcomeReceiver;
+import android.os.Process;
+import android.security.rkp.service.RegistrationProxy;
+import android.security.rkp.service.RemotelyProvisionedKey;
 
+import androidx.test.core.app.ApplicationProvider;
 import androidx.test.runner.AndroidJUnit4;
 
+import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
+import java.util.Arrays;
 import java.util.Base64;
 import java.util.Map;
+import java.util.concurrent.Executor;
 
 @RunWith(AndroidJUnit4.class)
 public class RemoteProvisioningShellCommandTest {
 
+    private Context mContext;
+
     private static class Injector extends RemoteProvisioningShellCommand.Injector {
 
-        private final Map<String, IRemotelyProvisionedComponent> mIrpcs;
-
-        Injector(Map irpcs) {
-            mIrpcs = irpcs;
-        }
+        Map<String, IRemotelyProvisionedComponent> mIrpcs;
+        Map<String, RegistrationProxy> mRegistrationProxies;
 
         @Override
         String[] getIrpcNames() {
@@ -70,6 +79,12 @@
             }
             return irpc;
         }
+
+        @Override
+        RegistrationProxy getRegistrationProxy(
+                Context context, int callerUid, String name, Executor executor) {
+            return mRegistrationProxies.get(name);
+        }
     }
 
     private static class CommandResult {
@@ -111,10 +126,17 @@
                 code, FileUtils.readTextFile(out, 0, null), FileUtils.readTextFile(err, 0, null));
     }
 
+    @Before
+    public void setUp() {
+        mContext = ApplicationProvider.getApplicationContext();
+    }
+
     @Test
     public void list_zeroInstances() throws Exception {
+        Injector injector = new Injector();
+        injector.mIrpcs = Map.of();
         RemoteProvisioningShellCommand cmd = new RemoteProvisioningShellCommand(
-                new Injector(Map.of()));
+                mContext, Process.SHELL_UID, injector);
         CommandResult res = exec(cmd, new String[] {"list"});
         assertThat(res.getErr()).isEmpty();
         assertThat(res.getCode()).isEqualTo(0);
@@ -124,8 +146,10 @@
 
     @Test
     public void list_oneInstances() throws Exception {
+        Injector injector = new Injector();
+        injector.mIrpcs = Map.of("default", mock(IRemotelyProvisionedComponent.class));
         RemoteProvisioningShellCommand cmd = new RemoteProvisioningShellCommand(
-                new Injector(Map.of("default", mock(IRemotelyProvisionedComponent.class))));
+                mContext, Process.SHELL_UID, injector);
         CommandResult res = exec(cmd, new String[] {"list"});
         assertThat(res.getErr()).isEmpty();
         assertThat(res.getCode()).isEqualTo(0);
@@ -134,10 +158,12 @@
 
     @Test
     public void list_twoInstances() throws Exception {
+        Injector injector = new Injector();
+        injector.mIrpcs = Map.of(
+                "default", mock(IRemotelyProvisionedComponent.class),
+                "strongbox", mock(IRemotelyProvisionedComponent.class));
         RemoteProvisioningShellCommand cmd = new RemoteProvisioningShellCommand(
-                new Injector(Map.of(
-                       "default", mock(IRemotelyProvisionedComponent.class),
-                       "strongbox", mock(IRemotelyProvisionedComponent.class))));
+                mContext, Process.SHELL_UID, injector);
         CommandResult res = exec(cmd, new String[] {"list"});
         assertThat(res.getErr()).isEmpty();
         assertThat(res.getCode()).isEqualTo(0);
@@ -158,8 +184,10 @@
         }).when(defaultMock).generateCertificateRequest(
                 anyBoolean(), any(), any(), any(), any(), any());
 
+        Injector injector = new Injector();
+        injector.mIrpcs = Map.of("default", defaultMock);
         RemoteProvisioningShellCommand cmd = new RemoteProvisioningShellCommand(
-                new Injector(Map.of("default", defaultMock)));
+                mContext, Process.SHELL_UID, injector);
         CommandResult res = exec(cmd, new String[] {
                 "csr", "--challenge", "dGVzdHRlc3R0ZXN0dGVzdA==", "default"});
         verify(defaultMock).generateCertificateRequest(
@@ -189,8 +217,10 @@
         }).when(defaultMock).generateCertificateRequest(
                 anyBoolean(), any(), any(), any(), any(), any());
 
+        Injector injector = new Injector();
+        injector.mIrpcs = Map.of("default", defaultMock);
         RemoteProvisioningShellCommand cmd = new RemoteProvisioningShellCommand(
-                new Injector(Map.of("default", defaultMock)));
+                mContext, Process.SHELL_UID, injector);
         CommandResult res = exec(cmd, new String[] {
                 "csr", "--challenge", "dGVzdHRlc3R0ZXN0dGVzdA==", "default"});
         verify(defaultMock).generateCertificateRequest(
@@ -215,8 +245,10 @@
         when(defaultMock.generateCertificateRequestV2(any(), any()))
             .thenReturn(new byte[] {0x68, 0x65, 0x6c, 0x6c, 0x6f});
 
+        Injector injector = new Injector();
+        injector.mIrpcs = Map.of("default", defaultMock);
         RemoteProvisioningShellCommand cmd = new RemoteProvisioningShellCommand(
-                new Injector(Map.of("default", defaultMock)));
+                mContext, Process.SHELL_UID, injector);
         CommandResult res = exec(cmd, new String[] {"csr", "default"});
         verify(defaultMock).generateCertificateRequestV2(new MacedPublicKey[0], new byte[0]);
         assertThat(res.getErr()).isEmpty();
@@ -233,8 +265,10 @@
         when(defaultMock.generateCertificateRequestV2(any(), any()))
             .thenReturn(new byte[] {0x68, 0x69});
 
+        Injector injector = new Injector();
+        injector.mIrpcs = Map.of("default", defaultMock);
         RemoteProvisioningShellCommand cmd = new RemoteProvisioningShellCommand(
-                new Injector(Map.of("default", defaultMock)));
+                mContext, Process.SHELL_UID, injector);
         CommandResult res = exec(cmd, new String[] {"csr", "--challenge", "dHJpYWw=", "default"});
         verify(defaultMock).generateCertificateRequestV2(
                 new MacedPublicKey[0], new byte[] {0x74, 0x72, 0x69, 0x61, 0x6c});
@@ -242,4 +276,82 @@
         assertThat(res.getCode()).isEqualTo(0);
         assertThat(res.getOut()).isEqualTo("aGk=\n");
     }
+
+    @Test
+    public void certify_sameOrderAsReceived() throws Exception {
+        String cert1 = "MIIBqDCCAU2gAwIBAgIUI3FFU7xZno/2Xf/wZzKKquP0ov0wCgYIKoZIzj0EAwIw\n"
+                + "KTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQ0wCwYDVQQKDARUZXN0MB4XDTIz\n"
+                + "MDgyMjE5MzgxMFoXDTMzMDgxOTE5MzgxMFowKTELMAkGA1UEBhMCVVMxCzAJBgNV\n"
+                + "BAgMAkNBMQ0wCwYDVQQKDARUZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE\n"
+                + "czOpG6NKOdDjV/yrKjuy0q0jEJvsVLGgTeY+vyKRBJS59OhyRWG6n3aza21bNg5d\n"
+                + "WE9ruz+bcT0IP4kDbiS0y6NTMFEwHQYDVR0OBBYEFHYfJxCUipNI7qRqvczcWsOb\n"
+                + "FIDPMB8GA1UdIwQYMBaAFHYfJxCUipNI7qRqvczcWsObFIDPMA8GA1UdEwEB/wQF\n"
+                + "MAMBAf8wCgYIKoZIzj0EAwIDSQAwRgIhAKm/kpJwlnWkjoLCAddBiSnxbT4EfJIK\n"
+                + "H0j58tg5VazHAiEAnS/kRzU9AbstOZyD7el/ws3gLXkbUNey3pLFutBWsSU=\n";
+        String cert2 = "MIIBpjCCAU2gAwIBAgIUdSzfZzeGr+h70JPO7Sxwdkw99iMwCgYIKoZIzj0EAwIw\n"
+                + "KTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQ0wCwYDVQQKDARUZXN0MB4XDTIz\n"
+                + "MDgyMjIwMTcyMFoXDTMzMDgxOTIwMTcyMFowKTELMAkGA1UEBhMCVVMxCzAJBgNV\n"
+                + "BAgMAkNBMQ0wCwYDVQQKDARUZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE\n"
+                + "voGJi4DxuqH8rzPV6Eq0OVULc0xFzaM0500VBqiQEB7Qt0Ktk2d+3bUrFAb3SZV4\n"
+                + "6TIdb7SkynvaDtr0x45Ng6NTMFEwHQYDVR0OBBYEFMeGjvGV0ADPBJk5/FPoW9HQ\n"
+                + "uTc6MB8GA1UdIwQYMBaAFMeGjvGV0ADPBJk5/FPoW9HQuTc6MA8GA1UdEwEB/wQF\n"
+                + "MAMBAf8wCgYIKoZIzj0EAwIDRwAwRAIgd1gu7iiNOQXaQUn5BT3WwWR0Yk78ndWt\n"
+                + "ew7tRiTOhFcCIFURi6WcNH0oWa6IbwBSMC9aZlo98Fbg+dTwhLAAw+PW\n";
+        byte[] cert1Bytes = Base64.getDecoder().decode(cert1.replaceAll("\\s+", ""));
+        byte[] cert2Bytes = Base64.getDecoder().decode(cert2.replaceAll("\\s+", ""));
+        byte[] certChain = Arrays.copyOf(cert1Bytes, cert1Bytes.length + cert2Bytes.length);
+        System.arraycopy(cert2Bytes, 0, certChain, cert1Bytes.length, cert2Bytes.length);
+        RemotelyProvisionedKey keyMock = mock(RemotelyProvisionedKey.class);
+        when(keyMock.getEncodedCertChain()).thenReturn(certChain);
+        RegistrationProxy defaultMock = mock(RegistrationProxy.class);
+        doAnswer(invocation -> {
+            ((OutcomeReceiver<RemotelyProvisionedKey, Exception>) invocation.getArgument(3))
+                    .onResult(keyMock);
+            return null;
+        }).when(defaultMock).getKeyAsync(anyInt(), any(), any(), any());
+
+        Injector injector = new Injector();
+        injector.mRegistrationProxies = Map.of("default", defaultMock);
+        RemoteProvisioningShellCommand cmd = new RemoteProvisioningShellCommand(
+                mContext, Process.SHELL_UID, injector);
+        CommandResult res = exec(cmd, new String[] {"certify", "default"});
+        assertThat(res.getErr()).isEmpty();
+        assertThat(res.getCode()).isEqualTo(0);
+        assertThat(res.getOut()).isEqualTo(
+                "-----BEGIN CERTIFICATE-----\n" + cert1 + "-----END CERTIFICATE-----\n"
+                + "-----BEGIN CERTIFICATE-----\n" + cert2 + "-----END CERTIFICATE-----\n");
+    }
+
+    @Test
+    public void certify_noBlankLineBeforeTrailer() throws Exception {
+        String cert = "MIIB2zCCAYGgAwIBAgIRAOpN7Em1k7gaqLAB2dzXUTYwCgYIKoZIzj0EAwIwKTET\n"
+                + "MBEGA1UEChMKR29vZ2xlIExMQzESMBAGA1UEAxMJRHJvaWQgQ0EzMB4XDTIzMDgx\n"
+                + "ODIzMzI1MloXDTIzMDkyMTIzMzI1MlowOTEMMAoGA1UEChMDVEVFMSkwJwYDVQQD\n"
+                + "EyBlYTRkZWM0OWI1OTNiODFhYThiMDAxZDlkY2Q3NTEzNjBZMBMGByqGSM49AgEG\n"
+                + "CCqGSM49AwEHA0IABHM/cKZblmlw8bdGbDXnX+ZiLiGjSjaLHXYOoHDrVArAMXUi\n"
+                + "L6brhcUPaqSGcVLcfFZbaFMOxXW6TsGdQiwJ0iyjejB4MB0GA1UdDgQWBBTYzft+\n"
+                + "X32TH/Hh+ngwQF6aPhnfXDAfBgNVHSMEGDAWgBQT4JObI9mzNNW2FRsHRcw4zVn2\n"
+                + "8jAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwICBDAVBgorBgEEAdZ5AgEe\n"
+                + "BAehARoABAAAMAoGCCqGSM49BAMCA0gAMEUCIDc0OR7CzIYw0myTr0y/Brl1nZyk\n"
+                + "eGSQp615WpTwYhwxAiEApM10gSIKBIo7Z4/FNzkuiz1zZwW9+Dcqisqxkfe6icQ=\n";
+        byte[] certBytes = Base64.getDecoder().decode(cert.replaceAll("\\s+", ""));
+        RemotelyProvisionedKey keyMock = mock(RemotelyProvisionedKey.class);
+        when(keyMock.getEncodedCertChain()).thenReturn(certBytes);
+        RegistrationProxy defaultMock = mock(RegistrationProxy.class);
+        doAnswer(invocation -> {
+            ((OutcomeReceiver<RemotelyProvisionedKey, Exception>) invocation.getArgument(3))
+                    .onResult(keyMock);
+            return null;
+        }).when(defaultMock).getKeyAsync(anyInt(), any(), any(), any());
+
+        Injector injector = new Injector();
+        injector.mRegistrationProxies = Map.of("strongbox", defaultMock);
+        RemoteProvisioningShellCommand cmd = new RemoteProvisioningShellCommand(
+                mContext, Process.SHELL_UID, injector);
+        CommandResult res = exec(cmd, new String[] {"certify", "strongbox"});
+        assertThat(res.getErr()).isEmpty();
+        assertThat(res.getCode()).isEqualTo(0);
+        assertThat(res.getOut()).isEqualTo(
+                "-----BEGIN CERTIFICATE-----\n" + cert + "-----END CERTIFICATE-----\n");
+    }
 }
diff --git a/services/tests/mockingservicestests/src/com/android/server/trust/OWNERS b/services/tests/mockingservicestests/src/com/android/server/trust/OWNERS
new file mode 100644
index 0000000..e2c6ce1
--- /dev/null
+++ b/services/tests/mockingservicestests/src/com/android/server/trust/OWNERS
@@ -0,0 +1 @@
+include /core/java/android/service/trust/OWNERS
diff --git a/services/tests/mockingservicestests/src/com/android/server/trust/TrustManagerServiceTest.java b/services/tests/mockingservicestests/src/com/android/server/trust/TrustManagerServiceTest.java
index 33870f1..9851bc1 100644
--- a/services/tests/mockingservicestests/src/com/android/server/trust/TrustManagerServiceTest.java
+++ b/services/tests/mockingservicestests/src/com/android/server/trust/TrustManagerServiceTest.java
@@ -16,15 +16,26 @@
 
 package com.android.server.trust;
 
+import static android.content.pm.PackageManager.PERMISSION_GRANTED;
+
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyInt;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.argThat;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.eq;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.when;
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.mockito.ArgumentMatchers.anyBoolean;
+
+import android.Manifest;
 import android.annotation.Nullable;
+import android.app.trust.ITrustListener;
+import android.app.trust.ITrustManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -36,11 +47,16 @@
 import android.content.pm.ServiceInfo;
 import android.net.Uri;
 import android.os.Handler;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.ServiceManager;
 import android.os.UserHandle;
 import android.os.test.TestLooper;
 import android.provider.Settings;
 import android.service.trust.TrustAgentService;
 import android.testing.TestableContext;
+import android.view.IWindowManager;
+import android.view.WindowManagerGlobal;
 
 import androidx.test.core.app.ApplicationProvider;
 
@@ -55,13 +71,16 @@
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
+import org.mockito.ArgumentCaptor;
 import org.mockito.ArgumentMatcher;
 import org.mockito.Mock;
+import org.mockito.MockitoSession;
 import org.mockito.junit.MockitoJUnit;
 import org.mockito.junit.MockitoRule;
 
 import java.util.ArrayList;
 import java.util.Collections;
+import java.util.Random;
 
 public class TrustManagerServiceTest {
 
@@ -255,6 +274,43 @@
                 systemTrustAgent1);
     }
 
+    @Test
+    public void reportEnabledTrustAgentsChangedInformsListener() throws RemoteException {
+        final LockPatternUtils utils = mock(LockPatternUtils.class);
+        final TrustManagerService service = new TrustManagerService(mMockContext,
+                new TrustManagerService.Injector(utils, mLooper.getLooper()));
+        final ITrustListener trustListener = mock(ITrustListener.class);
+        final IWindowManager windowManager = mock(IWindowManager.class);
+        final int userId = new Random().nextInt();
+
+        mMockContext.getTestablePermissions().setPermission(Manifest.permission.TRUST_LISTENER,
+                PERMISSION_GRANTED);
+
+        when(utils.getKnownTrustAgents(anyInt())).thenReturn(new ArrayList<>());
+
+        MockitoSession mockSession = mockitoSession()
+                .initMocks(this)
+                .mockStatic(ServiceManager.class)
+                .mockStatic(WindowManagerGlobal.class)
+                .startMocking();
+
+        doReturn(windowManager).when(() -> {
+            WindowManagerGlobal.getWindowManagerService();
+        });
+
+        service.onStart();
+        ArgumentCaptor<IBinder> binderArgumentCaptor = ArgumentCaptor.forClass(IBinder.class);
+        verify(() -> ServiceManager.addService(eq(Context.TRUST_SERVICE),
+                binderArgumentCaptor.capture(), anyBoolean(), anyInt()));
+        ITrustManager manager = ITrustManager.Stub.asInterface(binderArgumentCaptor.getValue());
+        manager.registerTrustListener(trustListener);
+        mLooper.dispatchAll();
+        manager.reportEnabledTrustAgentsChanged(userId);
+        mLooper.dispatchAll();
+        verify(trustListener).onEnabledTrustAgentsChanged(eq(userId));
+        mockSession.finishMocking();
+    }
+
     private void addTrustAgent(ComponentName agentComponentName, boolean isSystemApp) {
         ApplicationInfo applicationInfo = new ApplicationInfo();
         if (isSystemApp) {
diff --git a/services/tests/servicestests/src/com/android/server/CertBlacklisterTest.java b/services/tests/servicestests/src/com/android/server/CertBlacklisterTest.java
index 90df786..45e7f35 100644
--- a/services/tests/servicestests/src/com/android/server/CertBlacklisterTest.java
+++ b/services/tests/servicestests/src/com/android/server/CertBlacklisterTest.java
@@ -34,10 +34,10 @@
  */
 public class CertBlacklisterTest extends AndroidTestCase {
 
-    private static final String BLACKLIST_ROOT = System.getenv("ANDROID_DATA") + "/misc/keychain/";
+    private static final String DENYLIST_ROOT = System.getenv("ANDROID_DATA") + "/misc/keychain/";
 
-    public static final String PUBKEY_PATH = BLACKLIST_ROOT + "pubkey_blacklist.txt";
-    public static final String SERIAL_PATH = BLACKLIST_ROOT + "serial_blacklist.txt";
+    public static final String PUBKEY_PATH = DENYLIST_ROOT + "pubkey_blacklist.txt";
+    public static final String SERIAL_PATH = DENYLIST_ROOT + "serial_blacklist.txt";
 
     public static final String PUBKEY_KEY = "pubkey_blacklist";
     public static final String SERIAL_KEY = "serial_blacklist";
diff --git a/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateManagerServiceTest.java
index 94f88ab..5674101 100644
--- a/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/devicestate/DeviceStateManagerServiceTest.java
@@ -18,6 +18,8 @@
 
 import static android.hardware.devicestate.DeviceStateManager.INVALID_DEVICE_STATE;
 
+import static com.android.compatibility.common.util.PollingCheck.waitFor;
+
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.mockito.Mockito.mock;
@@ -40,6 +42,7 @@
 import androidx.test.filters.FlakyTest;
 import androidx.test.runner.AndroidJUnit4;
 
+import com.android.compatibility.common.util.PollingCheck;
 import com.android.server.wm.ActivityTaskManagerInternal;
 import com.android.server.wm.WindowProcessController;
 
@@ -73,6 +76,8 @@
 
     private static final int FAKE_PROCESS_ID = 100;
 
+    private static final int TIMEOUT = 2000;
+
     private TestDeviceStatePolicy mPolicy;
     private TestDeviceStateProvider mProvider;
     private DeviceStateManagerService mService;
@@ -106,6 +111,10 @@
         }
     }
 
+    private void waitAndAssert(PollingCheck.PollingCheckCondition condition) {
+        waitFor(TIMEOUT, condition);
+    }
+
     @Test
     public void baseStateChanged() {
         assertEquals(mService.getCommittedState(), Optional.of(DEFAULT_DEVICE_STATE));
@@ -272,37 +281,34 @@
         mService.getBinderService().registerCallback(callback);
 
         mProvider.setState(OTHER_DEVICE_STATE.getIdentifier());
-        flushHandler();
-        assertEquals(callback.getLastNotifiedInfo().baseState,
-                OTHER_DEVICE_STATE.getIdentifier());
-        assertEquals(callback.getLastNotifiedInfo().currentState,
-                OTHER_DEVICE_STATE.getIdentifier());
+        waitAndAssert(() -> callback.getLastNotifiedInfo().baseState
+                == OTHER_DEVICE_STATE.getIdentifier());
+        waitAndAssert(() -> callback.getLastNotifiedInfo().currentState
+                == OTHER_DEVICE_STATE.getIdentifier());
 
         mProvider.setState(DEFAULT_DEVICE_STATE.getIdentifier());
-        flushHandler();
-        assertEquals(callback.getLastNotifiedInfo().baseState,
-                DEFAULT_DEVICE_STATE.getIdentifier());
-        assertEquals(callback.getLastNotifiedInfo().currentState,
-                DEFAULT_DEVICE_STATE.getIdentifier());
+        waitAndAssert(() -> callback.getLastNotifiedInfo().baseState
+                == DEFAULT_DEVICE_STATE.getIdentifier());
+
+        waitAndAssert(() -> callback.getLastNotifiedInfo().currentState
+                == DEFAULT_DEVICE_STATE.getIdentifier());
 
         mPolicy.blockConfigure();
         mProvider.setState(OTHER_DEVICE_STATE.getIdentifier());
-        flushHandler();
         // The callback should not have been notified of the state change as the policy is still
         // pending callback.
-        assertEquals(callback.getLastNotifiedInfo().baseState,
-                DEFAULT_DEVICE_STATE.getIdentifier());
-        assertEquals(callback.getLastNotifiedInfo().currentState,
-                DEFAULT_DEVICE_STATE.getIdentifier());
+        waitAndAssert(() -> callback.getLastNotifiedInfo().baseState
+                == DEFAULT_DEVICE_STATE.getIdentifier());
+        waitAndAssert(() -> callback.getLastNotifiedInfo().currentState
+                == DEFAULT_DEVICE_STATE.getIdentifier());
 
         mPolicy.resumeConfigure();
-        flushHandler();
         // Now that the policy is finished processing the callback should be notified of the state
         // change.
-        assertEquals(callback.getLastNotifiedInfo().baseState,
-                OTHER_DEVICE_STATE.getIdentifier());
-        assertEquals(callback.getLastNotifiedInfo().currentState,
-                OTHER_DEVICE_STATE.getIdentifier());
+        waitAndAssert(() -> callback.getLastNotifiedInfo().baseState
+                == OTHER_DEVICE_STATE.getIdentifier());
+        waitAndAssert(() -> callback.getLastNotifiedInfo().currentState
+                == OTHER_DEVICE_STATE.getIdentifier());
     }
 
     @Test
@@ -329,13 +335,9 @@
 
         mService.getBinderService().requestState(token, OTHER_DEVICE_STATE.getIdentifier(),
                 0 /* flags */);
-        // Flush the handler twice. The first flush ensures the request is added and the policy is
-        // notified, while the second flush ensures the callback is notified once the change is
-        // committed.
-        flushHandler(2 /* count */);
 
-        assertEquals(callback.getLastNotifiedStatus(token),
-                TestDeviceStateManagerCallback.STATUS_ACTIVE);
+        waitAndAssert(() -> callback.getLastNotifiedStatus(token)
+                == TestDeviceStateManagerCallback.STATUS_ACTIVE);
         // Committed state changes as there is a requested override.
         assertEquals(mService.getCommittedState(), Optional.of(OTHER_DEVICE_STATE));
         assertEquals(mSysPropSetter.getValue(),
@@ -352,12 +354,11 @@
                 OTHER_DEVICE_STATE.getIdentifier());
 
         mService.getBinderService().cancelStateRequest();
-        flushHandler();
 
-        assertEquals(callback.getLastNotifiedStatus(token),
-                TestDeviceStateManagerCallback.STATUS_CANCELED);
+        waitAndAssert(() -> callback.getLastNotifiedStatus(token)
+                == TestDeviceStateManagerCallback.STATUS_CANCELED);
         // Committed state is set back to the requested state once the override is cleared.
-        assertEquals(mService.getCommittedState(), Optional.of(DEFAULT_DEVICE_STATE));
+        waitAndAssert(() -> mService.getCommittedState().equals(Optional.of(DEFAULT_DEVICE_STATE)));
         assertEquals(mSysPropSetter.getValue(),
                 DEFAULT_DEVICE_STATE.getIdentifier() + ":" + DEFAULT_DEVICE_STATE.getName());
         assertEquals(mService.getBaseState(), Optional.of(DEFAULT_DEVICE_STATE));
@@ -600,13 +601,9 @@
         mService.getBinderService().requestBaseStateOverride(token,
                 OTHER_DEVICE_STATE.getIdentifier(),
                 0 /* flags */);
-        // Flush the handler twice. The first flush ensures the request is added and the policy is
-        // notified, while the second flush ensures the callback is notified once the change is
-        // committed.
-        flushHandler(2 /* count */);
 
-        assertEquals(callback.getLastNotifiedStatus(token),
-                TestDeviceStateManagerCallback.STATUS_ACTIVE);
+        waitAndAssert(() -> callback.getLastNotifiedStatus(token)
+                == TestDeviceStateManagerCallback.STATUS_ACTIVE);
         // Committed state changes as there is a requested override.
         assertEquals(mService.getCommittedState(), Optional.of(OTHER_DEVICE_STATE));
         assertEquals(mSysPropSetter.getValue(),
@@ -624,12 +621,11 @@
                 OTHER_DEVICE_STATE.getIdentifier());
 
         mService.getBinderService().cancelBaseStateOverride();
-        flushHandler();
 
-        assertEquals(callback.getLastNotifiedStatus(token),
-                TestDeviceStateManagerCallback.STATUS_CANCELED);
+        waitAndAssert(() -> callback.getLastNotifiedStatus(token)
+                == TestDeviceStateManagerCallback.STATUS_CANCELED);
         // Committed state is set back to the requested state once the override is cleared.
-        assertEquals(mService.getCommittedState(), Optional.of(DEFAULT_DEVICE_STATE));
+        waitAndAssert(() -> mService.getCommittedState().equals(Optional.of(DEFAULT_DEVICE_STATE)));
         assertEquals(mSysPropSetter.getValue(),
                 DEFAULT_DEVICE_STATE.getIdentifier() + ":" + DEFAULT_DEVICE_STATE.getName());
         assertEquals(mService.getBaseState(), Optional.of(DEFAULT_DEVICE_STATE));
@@ -638,8 +634,8 @@
         assertEquals(mPolicy.getMostRecentRequestedStateToConfigure(),
                 DEFAULT_DEVICE_STATE.getIdentifier());
 
-        assertEquals(callback.getLastNotifiedInfo().baseState,
-                DEFAULT_DEVICE_STATE.getIdentifier());
+        waitAndAssert(() -> callback.getLastNotifiedInfo().baseState
+                == DEFAULT_DEVICE_STATE.getIdentifier());
         assertEquals(callback.getLastNotifiedInfo().currentState,
                 DEFAULT_DEVICE_STATE.getIdentifier());
     }
@@ -660,13 +656,9 @@
         mService.getBinderService().requestBaseStateOverride(token,
                 OTHER_DEVICE_STATE.getIdentifier(),
                 0 /* flags */);
-        // Flush the handler twice. The first flush ensures the request is added and the policy is
-        // notified, while the second flush ensures the callback is notified once the change is
-        // committed.
-        flushHandler(2 /* count */);
 
-        assertEquals(callback.getLastNotifiedStatus(token),
-                TestDeviceStateManagerCallback.STATUS_ACTIVE);
+        waitAndAssert(() -> callback.getLastNotifiedStatus(token)
+                == TestDeviceStateManagerCallback.STATUS_ACTIVE);
         // Committed state changes as there is a requested override.
         assertEquals(mService.getCommittedState(), Optional.of(OTHER_DEVICE_STATE));
         assertEquals(mSysPropSetter.getValue(),
@@ -684,12 +676,11 @@
                 OTHER_DEVICE_STATE.getIdentifier());
 
         mProvider.setState(testDeviceState.getIdentifier());
-        flushHandler();
 
-        assertEquals(callback.getLastNotifiedStatus(token),
-                TestDeviceStateManagerCallback.STATUS_CANCELED);
+        waitAndAssert(() -> callback.getLastNotifiedStatus(token)
+                == TestDeviceStateManagerCallback.STATUS_CANCELED);
         // Committed state is set to the new base state once the override is cleared.
-        assertEquals(mService.getCommittedState(), Optional.of(testDeviceState));
+        waitAndAssert(() -> mService.getCommittedState().equals(Optional.of(testDeviceState)));
         assertEquals(mSysPropSetter.getValue(),
                 testDeviceState.getIdentifier() + ":" + testDeviceState.getName());
         assertEquals(mService.getBaseState(), Optional.of(testDeviceState));
@@ -698,8 +689,8 @@
         assertEquals(mPolicy.getMostRecentRequestedStateToConfigure(),
                 testDeviceState.getIdentifier());
 
-        assertEquals(callback.getLastNotifiedInfo().baseState,
-                testDeviceState.getIdentifier());
+        waitAndAssert(() -> callback.getLastNotifiedInfo().baseState
+                == testDeviceState.getIdentifier());
         assertEquals(callback.getLastNotifiedInfo().currentState,
                 testDeviceState.getIdentifier());
     }
diff --git a/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java b/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java
index 68e5ebf..7bb13d7 100644
--- a/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java
+++ b/services/tests/servicestests/src/com/android/server/graphics/fonts/UpdatableFontDirTest.java
@@ -140,7 +140,9 @@
     private List<File> mPreinstalledFontDirs;
     private final Supplier<Long> mCurrentTimeSupplier = () -> CURRENT_TIME;
     private final Function<Map<String, File>, FontConfig> mConfigSupplier =
-            (map) -> SystemFonts.getSystemFontConfig(map, 0, 0);
+            // /system/etc/font_fallback.xml is not accessible from application process, so
+            // use legacy fonts.xml for testing.
+            (map) -> SystemFonts.getSystemFontConfigForTesting("/system/etc/fonts.xml", map, 0, 0);
     private FakeFontFileParser mParser;
     private FakeFsverityUtil mFakeFsverityUtil;
 
diff --git a/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java b/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
index 9ca84d3..ce15c6d 100644
--- a/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
+++ b/services/tests/servicestests/src/com/android/server/integrity/AppIntegrityManagerServiceImplTest.java
@@ -218,7 +218,7 @@
 
     @Test
     public void updateRuleSet_notSystemApp() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp(false);
         Rule rule =
                 new Rule(
@@ -237,7 +237,7 @@
 
     @Test
     public void updateRuleSet_authorized() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         Rule rule =
                 new Rule(
@@ -251,7 +251,7 @@
 
     @Test
     public void updateRuleSet_correctMethodCall() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         IntentSender mockReceiver = mock(IntentSender.class);
         List<Rule> rules =
@@ -271,7 +271,7 @@
 
     @Test
     public void updateRuleSet_fail() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         doThrow(new IOException()).when(mIntegrityFileManager).writeRules(any(), any(), any());
         IntentSender mockReceiver = mock(IntentSender.class);
@@ -292,7 +292,7 @@
 
     @Test
     public void broadcastReceiverRegistration() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         ArgumentCaptor<IntentFilter> intentFilterCaptor =
                 ArgumentCaptor.forClass(IntentFilter.class);
@@ -308,7 +308,7 @@
 
     @Test
     public void handleBroadcast_correctArgs() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
                 ArgumentCaptor.forClass(BroadcastReceiver.class);
@@ -345,7 +345,7 @@
 
     @Test
     public void handleBroadcast_correctArgs_multipleCerts() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
                 ArgumentCaptor.forClass(BroadcastReceiver.class);
@@ -368,7 +368,7 @@
 
     @Test
     public void handleBroadcast_correctArgs_sourceStamp() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
                 ArgumentCaptor.forClass(BroadcastReceiver.class);
@@ -393,7 +393,7 @@
 
     @Test
     public void handleBroadcast_allow() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
                 ArgumentCaptor.forClass(BroadcastReceiver.class);
@@ -412,7 +412,7 @@
 
     @Test
     public void handleBroadcast_reject() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
                 ArgumentCaptor.forClass(BroadcastReceiver.class);
@@ -438,7 +438,7 @@
 
     @Test
     public void handleBroadcast_notInitialized() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         when(mIntegrityFileManager.initialized()).thenReturn(false);
         ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
@@ -459,7 +459,7 @@
 
     @Test
     public void verifierAsInstaller_skipIntegrityVerification() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         setIntegrityCheckIncludesRuleProvider(false);
         ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
@@ -480,7 +480,7 @@
 
     @Test
     public void getCurrentRules() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
         Rule rule = new Rule(IntegrityFormula.Application.packageNameEquals("package"), Rule.DENY);
         when(mIntegrityFileManager.readRules(any())).thenReturn(Arrays.asList(rule));
@@ -490,7 +490,7 @@
 
     @Test
     public void getWhitelistedRuleProviders_returnsEmptyForNonSystemApps() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp(false);
 
         assertThat(mService.getWhitelistedRuleProviders()).isEmpty();
@@ -498,13 +498,13 @@
 
     @Test
     public void getWhitelistedRuleProviders() throws Exception {
-        whitelistUsAsRuleProvider();
+        allowlistUsAsRuleProvider();
         makeUsSystemApp();
 
         assertThat(mService.getWhitelistedRuleProviders()).containsExactly(TEST_FRAMEWORK_PACKAGE);
     }
 
-    private void whitelistUsAsRuleProvider() {
+    private void allowlistUsAsRuleProvider() {
         Resources mockResources = mock(Resources.class);
         when(mockResources.getStringArray(R.array.config_integrityRuleProviderPackages))
                 .thenReturn(new String[] {TEST_FRAMEWORK_PACKAGE});
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/KeySyncTaskTest.java b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/KeySyncTaskTest.java
index d9af51f..0ac6ef3 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/KeySyncTaskTest.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/KeySyncTaskTest.java
@@ -467,7 +467,7 @@
         verify(mTestOnlyInsecureCertificateHelper, atLeast(1))
                 .isTestOnlyCertificateAlias(eq(TEST_ROOT_CERT_ALIAS));
 
-        // no whitelists check
+        // no allowlists check
         verify(mTestOnlyInsecureCertificateHelper, never())
                 .doesCredentialSupportInsecureMode(anyInt(), any());
         verify(mTestOnlyInsecureCertificateHelper, never())
diff --git a/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java b/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java
index ab292ab..872e438 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ApexManagerTest.java
@@ -19,6 +19,7 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.doAnswer;
@@ -362,7 +363,7 @@
 
         File apex = extractResource("test.apex_rebootless_v1", "test.rebootless_apex_v1.apex");
         PackageManagerException e = expectThrows(PackageManagerException.class,
-                () -> mApexManager.installPackage(apex, mPackageParser2));
+                () -> mApexManager.installPackage(apex, mPackageParser2, /* force= */ false));
         assertThat(e).hasMessageThat().contains("It is forbidden to install new APEX packages");
     }
 
@@ -378,10 +379,11 @@
         File finalApex = extractResource("test.rebootles_apex_v2", "test.rebootless_apex_v2.apex");
         ApexInfo newApexInfo = createApexInfo("test.apex_rebootless", 2, /* isActive= */ true,
                 /* isFactory= */ false, finalApex);
-        when(mApexService.installAndActivatePackage(anyString())).thenReturn(newApexInfo);
+        when(mApexService.installAndActivatePackage(anyString(), anyBoolean())).thenReturn(
+                newApexInfo);
 
         File installedApex = extractResource("installed", "test.rebootless_apex_v2.apex");
-        mApexManager.installPackage(installedApex, mPackageParser2);
+        mApexManager.installPackage(installedApex, mPackageParser2, /* force= */ false);
 
         PackageInfo newInfo = mApexManager.getPackageInfo("test.apex.rebootless",
                 ApexManager.MATCH_ACTIVE_PACKAGE);
@@ -416,10 +418,11 @@
         File finalApex = extractResource("test.rebootles_apex_v2", "test.rebootless_apex_v2.apex");
         ApexInfo newApexInfo = createApexInfo("test.apex_rebootless", 2, /* isActive= */ true,
                 /* isFactory= */ false, finalApex);
-        when(mApexService.installAndActivatePackage(anyString())).thenReturn(newApexInfo);
+        when(mApexService.installAndActivatePackage(anyString(), anyBoolean())).thenReturn(
+                newApexInfo);
 
         File installedApex = extractResource("installed", "test.rebootless_apex_v2.apex");
-        mApexManager.installPackage(installedApex, mPackageParser2);
+        mApexManager.installPackage(installedApex, mPackageParser2, /* force= */ false);
 
         PackageInfo newInfo = mApexManager.getPackageInfo("test.apex.rebootless",
                 ApexManager.MATCH_ACTIVE_PACKAGE);
@@ -447,13 +450,14 @@
         mApexManager.scanApexPackagesTraced(mPackageParser2,
                 ParallelPackageParser.makeExecutorService());
 
-        when(mApexService.installAndActivatePackage(anyString())).thenThrow(
+        when(mApexService.installAndActivatePackage(anyString(), anyBoolean())).thenThrow(
                 new RuntimeException("install failed :("));
 
         File installedApex = extractResource("test.apex_rebootless_v1",
                 "test.rebootless_apex_v1.apex");
         assertThrows(PackageManagerException.class,
-                () -> mApexManager.installPackage(installedApex, mPackageParser2));
+                () -> mApexManager.installPackage(installedApex, mPackageParser2, /* force= */
+                        false));
     }
 
     @Test
@@ -468,7 +472,8 @@
         File installedApex = extractResource("shim_different_certificate",
                 "com.android.apex.cts.shim.v2_different_certificate.apex");
         PackageManagerException e = expectThrows(PackageManagerException.class,
-                () -> mApexManager.installPackage(installedApex, mPackageParser2));
+                () -> mApexManager.installPackage(installedApex, mPackageParser2, /* force= */
+                        false));
         assertThat(e).hasMessageThat().contains("APK container signature of ");
         assertThat(e).hasMessageThat().contains(
                 "is not compatible with currently installed on device");
@@ -486,7 +491,8 @@
         File installedApex = extractResource("shim_unsigned_apk_container",
                 "com.android.apex.cts.shim.v2_unsigned_apk_container.apex");
         PackageManagerException e = expectThrows(PackageManagerException.class,
-                () -> mApexManager.installPackage(installedApex, mPackageParser2));
+                () -> mApexManager.installPackage(installedApex, mPackageParser2, /* force= */
+                        false));
         assertThat(e).hasMessageThat().contains("Failed to collect certificates from ");
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest2.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest2.java
index c786784..86d4655 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest2.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest2.java
@@ -228,6 +228,15 @@
                 });
     }
 
+    public void testShortcutIdTruncated() {
+        ShortcutInfo si = new ShortcutInfo.Builder(getTestContext(),
+                "s".repeat(Short.MAX_VALUE)).build();
+
+        assertTrue(
+                "id must be truncated to MAX_ID_LENGTH",
+                si.getId().length() <= ShortcutInfo.MAX_ID_LENGTH);
+    }
+
     public void testShortcutInfoParcel() {
         setCaller(CALLING_PACKAGE_1, USER_10);
         ShortcutInfo si = parceled(new ShortcutInfo.Builder(mClientContext)
diff --git a/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java b/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java
index ba7a103..8ba4384 100644
--- a/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/UserSystemPackageInstallerTest.java
@@ -117,7 +117,7 @@
         for (int userId : mRemoveUsers) {
             um.removeUser(userId);
         }
-        setUserTypePackageWhitelistMode(mOriginalWhitelistMode);
+        setUserTypePackageAllowlistMode(mOriginalWhitelistMode);
     }
 
     /**
@@ -184,7 +184,7 @@
             }
         }
 
-        final ArrayMap<String, Long> expectedOutput = getNewPackageToWhitelistedBitSetMap();
+        final ArrayMap<String, Long> expectedOutput = getNewPackageToAllowlistedBitSetMap();
         expectedOutput.put("com.android.package1", expectedUserTypeBitSet1);
         expectedOutput.put("com.android.package2", expectedUserTypeBitSet2);
         expectedOutput.put("com.android.package3", expectedUserTypeBitSet3);
@@ -227,7 +227,7 @@
             }
         };
 
-        final ArrayMap<String, Long> expectedOutput = getNewPackageToWhitelistedBitSetMap();
+        final ArrayMap<String, Long> expectedOutput = getNewPackageToAllowlistedBitSetMap();
         expectedOutput.put("com.android.package2", 0L);
         expectedOutput.put("com.android.package3", 0L);
         expectedOutput.put("com.android.package4", 0L);
@@ -340,7 +340,7 @@
     public void testPackagesForCreateUser_full() {
         final String userTypeToCreate = USER_TYPE_FULL_SECONDARY;
         final long userTypeMask = mUserSystemPackageInstaller.getUserTypeMask(userTypeToCreate);
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
         PackageManager pm = mContext.getPackageManager();
 
         final SystemConfig sysConfig = new SystemConfigTestClass(true);
@@ -384,7 +384,7 @@
      */
     @Test
     public void testInstallOverlayPackagesExplicitMode() {
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
 
         final String[] userTypes = new String[]{"type"};
         final long maskOfType = 0b0001L;
@@ -453,49 +453,49 @@
      */
     @Test
     public void testSetWhitelistEnabledMode() {
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE);
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_DISABLE);
         assertFalse(mUserSystemPackageInstaller.isLogMode());
         assertFalse(mUserSystemPackageInstaller.isEnforceMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
         assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
 
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_LOG);
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_LOG);
         assertTrue(mUserSystemPackageInstaller.isLogMode());
         assertFalse(mUserSystemPackageInstaller.isEnforceMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
         assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
 
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
         assertFalse(mUserSystemPackageInstaller.isLogMode());
         assertTrue(mUserSystemPackageInstaller.isEnforceMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
         assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
 
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST);
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST);
         assertFalse(mUserSystemPackageInstaller.isLogMode());
         assertFalse(mUserSystemPackageInstaller.isEnforceMode());
         assertTrue(mUserSystemPackageInstaller.isImplicitWhitelistMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
         assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
 
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST_SYSTEM);
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST_SYSTEM);
         assertFalse(mUserSystemPackageInstaller.isLogMode());
         assertFalse(mUserSystemPackageInstaller.isEnforceMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
         assertTrue(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
         assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
 
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IGNORE_OTA);
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IGNORE_OTA);
         assertFalse(mUserSystemPackageInstaller.isLogMode());
         assertFalse(mUserSystemPackageInstaller.isEnforceMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistMode());
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
         assertTrue(mUserSystemPackageInstaller.isIgnoreOtaMode());
 
-        setUserTypePackageWhitelistMode(
+        setUserTypePackageAllowlistMode(
                 USER_TYPE_PACKAGE_WHITELIST_MODE_LOG | USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
         assertTrue(mUserSystemPackageInstaller.isLogMode());
         assertTrue(mUserSystemPackageInstaller.isEnforceMode());
@@ -503,7 +503,7 @@
         assertFalse(mUserSystemPackageInstaller.isImplicitWhitelistSystemMode());
         assertFalse(mUserSystemPackageInstaller.isIgnoreOtaMode());
 
-        setUserTypePackageWhitelistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST
+        setUserTypePackageAllowlistMode(USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST
                 | USER_TYPE_PACKAGE_WHITELIST_MODE_ENFORCE);
         assertFalse(mUserSystemPackageInstaller.isLogMode());
         assertTrue(mUserSystemPackageInstaller.isEnforceMode());
@@ -513,7 +513,7 @@
     }
 
     /** Sets the allowlist mode to the desired value via adb's setprop. */
-    private void setUserTypePackageWhitelistMode(int mode) {
+    private void setUserTypePackageAllowlistMode(int mode) {
         UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
         try {
             String result = uiDevice.executeShellCommand(String.format("setprop %s %d",
@@ -526,7 +526,7 @@
     }
 
     /** @see UserSystemPackageInstaller#mWhitelistedPackagesForUserTypes */
-    private ArrayMap<String, Long> getNewPackageToWhitelistedBitSetMap() {
+    private ArrayMap<String, Long> getNewPackageToAllowlistedBitSetMap() {
         final ArrayMap<String, Long> pkgBitSetMap = new ArrayMap<>();
         // "android" is always treated as allowlisted for all types, regardless of the xml file.
         pkgBitSetMap.put("android", ~0L);
diff --git a/services/tests/servicestests/src/com/android/server/power/hint/OWNERS b/services/tests/servicestests/src/com/android/server/power/hint/OWNERS
new file mode 100644
index 0000000..c28c07a
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/power/hint/OWNERS
@@ -0,0 +1,2 @@
+include /ADPF_OWNERS
+
diff --git a/services/tests/servicestests/src/com/android/server/systemconfig/SystemConfigTest.java b/services/tests/servicestests/src/com/android/server/systemconfig/SystemConfigTest.java
index 92c7871..687e8f7 100644
--- a/services/tests/servicestests/src/com/android/server/systemconfig/SystemConfigTest.java
+++ b/services/tests/servicestests/src/com/android/server/systemconfig/SystemConfigTest.java
@@ -446,14 +446,14 @@
                         + "    <library \n"
                         + "        name=\"foo\"\n"
                         + "        file=\"" + mFooJar + "\"\n"
-                        + "        on-bootclasspath-before=\"Q\"\n"
+                        + "        on-bootclasspath-before=\"A\"\n"
                         + "        on-bootclasspath-since=\"W\"\n"
                         + "     />\n\n"
                         + " </permissions>";
         parseSharedLibraries(contents);
         assertFooIsOnlySharedLibrary();
         SystemConfig.SharedLibraryEntry entry = mSysConfig.getSharedLibraries().get("foo");
-        assertThat(entry.onBootclasspathBefore).isEqualTo("Q");
+        assertThat(entry.onBootclasspathBefore).isEqualTo("A");
         assertThat(entry.onBootclasspathSince).isEqualTo("W");
     }
 
diff --git a/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java b/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java
index 22d383a..fc5213c 100644
--- a/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java
+++ b/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java
@@ -82,7 +82,7 @@
             uptimeMillis = uptimeMillis - SystemClock.uptimeMillis() + mClock.getAsLong();
         }
 
-        // post a dummy queue entry to keep track of message removal
+        // post a sentinel queue entry to keep track of message removal
         return super.sendMessageAtTime(msg, Long.MAX_VALUE)
                 && mMessages.add(new MsgInfo(Message.obtain(msg), uptimeMillis, mMessageCount));
     }
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 874846d..8f8b1c5 100755
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -128,6 +128,7 @@
 import android.app.PendingIntent;
 import android.app.Person;
 import android.app.RemoteInput;
+import android.app.RemoteInputHistoryItem;
 import android.app.StatsManager;
 import android.app.admin.DevicePolicyManagerInternal;
 import android.app.usage.UsageStatsManagerInternal;
@@ -5373,10 +5374,36 @@
     public void testVisitUris() throws Exception {
         final Uri audioContents = Uri.parse("content://com.example/audio");
         final Uri backgroundImage = Uri.parse("content://com.example/background");
+        final Icon personIcon1 = Icon.createWithContentUri("content://media/person1");
+        final Icon personIcon2 = Icon.createWithContentUri("content://media/person2");
+        final Icon personIcon3 = Icon.createWithContentUri("content://media/person3");
+        final Person person1 = new Person.Builder()
+                .setName("Messaging Person")
+                .setIcon(personIcon1)
+                .build();
+        final Person person2 = new Person.Builder()
+                .setName("People List Person 1")
+                .setIcon(personIcon2)
+                .build();
+        final Person person3 = new Person.Builder()
+                .setName("People List Person 2")
+                .setIcon(personIcon3)
+                .build();
+        final Uri historyUri1 = Uri.parse("content://com.example/history1");
+        final Uri historyUri2 = Uri.parse("content://com.example/history2");
+        final RemoteInputHistoryItem historyItem1 = new RemoteInputHistoryItem(null, historyUri1,
+                "a");
+        final RemoteInputHistoryItem historyItem2 = new RemoteInputHistoryItem(null, historyUri2,
+                "b");
 
         Bundle extras = new Bundle();
         extras.putParcelable(Notification.EXTRA_AUDIO_CONTENTS_URI, audioContents);
         extras.putString(Notification.EXTRA_BACKGROUND_IMAGE_URI, backgroundImage.toString());
+        extras.putParcelable(Notification.EXTRA_MESSAGING_PERSON, person1);
+        extras.putParcelableArrayList(Notification.EXTRA_PEOPLE_LIST,
+                new ArrayList<>(Arrays.asList(person2, person3)));
+        extras.putParcelableArray(Notification.EXTRA_REMOTE_INPUT_HISTORY_ITEMS,
+                new RemoteInputHistoryItem[]{historyItem1, historyItem2});
 
         Notification n = new Notification.Builder(mContext, "a")
                 .setContentTitle("notification with uris")
@@ -5388,6 +5415,34 @@
         n.visitUris(visitor);
         verify(visitor, times(1)).accept(eq(audioContents));
         verify(visitor, times(1)).accept(eq(backgroundImage));
+        verify(visitor, times(1)).accept(eq(personIcon1.getUri()));
+        verify(visitor, times(1)).accept(eq(personIcon2.getUri()));
+        verify(visitor, times(1)).accept(eq(personIcon3.getUri()));
+        verify(visitor, times(1)).accept(eq(historyUri1));
+        verify(visitor, times(1)).accept(eq(historyUri2));
+    }
+
+    @Test
+    public void testVisitUris_callStyle() {
+        Icon personIcon = Icon.createWithContentUri("content://media/person");
+        Icon verificationIcon = Icon.createWithContentUri("content://media/verification");
+        Person callingPerson = new Person.Builder().setName("Someone")
+                .setIcon(personIcon)
+                .build();
+        PendingIntent hangUpIntent = PendingIntent.getActivity(mContext, 0, new Intent(),
+                PendingIntent.FLAG_IMMUTABLE);
+        Notification n = new Notification.Builder(mContext, "a")
+                .setStyle(Notification.CallStyle.forOngoingCall(callingPerson, hangUpIntent)
+                        .setVerificationIcon(verificationIcon))
+                .setContentTitle("Calling...")
+                .setSmallIcon(android.R.drawable.sym_def_app_icon)
+                .build();
+
+        Consumer<Uri> visitor = (Consumer<Uri>) spy(Consumer.class);
+        n.visitUris(visitor);
+
+        verify(visitor, times(1)).accept(eq(personIcon.getUri()));
+        verify(visitor, times(1)).accept(eq(verificationIcon.getUri()));
     }
 
     @Test
diff --git a/services/tests/wmtests/OWNERS b/services/tests/wmtests/OWNERS
index 7a128fc..cece37f 100644
--- a/services/tests/wmtests/OWNERS
+++ b/services/tests/wmtests/OWNERS
@@ -1,3 +1,4 @@
+# Bug template url: https://b.corp.google.com/issues/new?component=316125&template=1018199
 include /services/core/java/com/android/server/wm/OWNERS
 
 # Voice Interaction
diff --git a/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java
index b277283..4ffd18a 100644
--- a/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LetterboxUiControllerTest.java
@@ -39,9 +39,9 @@
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ALLOW_REFRESH;
 import static android.view.WindowManager.PROPERTY_CAMERA_COMPAT_ENABLE_REFRESH_VIA_PAUSE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_DISPLAY_ORIENTATION_OVERRIDE;
+import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_IGNORING_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED;
 import static android.view.WindowManager.PROPERTY_COMPAT_ALLOW_ORIENTATION_OVERRIDE;
 import static android.view.WindowManager.PROPERTY_COMPAT_ENABLE_FAKE_FOCUS;
-import static android.view.WindowManager.PROPERTY_COMPAT_IGNORE_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED;
 import static android.view.WindowManager.PROPERTY_COMPAT_IGNORE_REQUESTED_ORIENTATION;
 
 import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
@@ -206,7 +206,7 @@
             throws Exception {
         doReturn(true).when(mLetterboxConfiguration)
                 .isPolicyForIgnoringRequestedOrientationEnabled();
-        mockThatProperty(PROPERTY_COMPAT_IGNORE_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED,
+        mockThatProperty(PROPERTY_COMPAT_ALLOW_IGNORING_ORIENTATION_REQUEST_WHEN_LOOP_DETECTED,
                 /* value */ false);
         doReturn(false).when(mActivity).isLetterboxedForFixedOrientationAndAspectRatio();
 
diff --git a/startop/apps/ColorChanging/app/build.gradle b/startop/apps/ColorChanging/app/build.gradle
index ab955aa..11b14c0 100644
--- a/startop/apps/ColorChanging/app/build.gradle
+++ b/startop/apps/ColorChanging/app/build.gradle
@@ -14,7 +14,7 @@
     buildTypes {
         release {
             minifyEnabled false
-            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt')
         }
     }
 }
diff --git a/startop/apps/ColorChanging/app/proguard-rules.pro b/startop/apps/ColorChanging/app/proguard-rules.pro
deleted file mode 100644
index f1b4245..0000000
--- a/startop/apps/ColorChanging/app/proguard-rules.pro
+++ /dev/null
@@ -1,21 +0,0 @@
-# Add project specific ProGuard rules here.
-# You can control the set of applied configuration files using the
-# proguardFiles setting in build.gradle.
-#
-# For more details, see
-#   http://developer.android.com/guide/developing/tools/proguard.html
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-#   public *;
-#}
-
-# Uncomment this to preserve the line number information for
-# debugging stack traces.
-#-keepattributes SourceFile,LineNumberTable
-
-# If you keep the line number information, uncomment this to
-# hide the original source file name.
-#-renamesourcefileattribute SourceFile
diff --git a/telecomm/OWNERS b/telecomm/OWNERS
index dcaf858..b57b7c7 100644
--- a/telecomm/OWNERS
+++ b/telecomm/OWNERS
@@ -4,7 +4,6 @@
 tgunn@google.com
 xiaotonj@google.com
 rgreenwalt@google.com
-chinmayd@google.com
 grantmenke@google.com
 pmadapurmath@google.com
 tjstuart@google.com
\ No newline at end of file
diff --git a/telecomm/java/android/telecom/RemoteConnectionManager.java b/telecomm/java/android/telecom/RemoteConnectionManager.java
index fbbfefd..fbf8eef 100644
--- a/telecomm/java/android/telecom/RemoteConnectionManager.java
+++ b/telecomm/java/android/telecom/RemoteConnectionManager.java
@@ -39,18 +39,21 @@
     void addConnectionService(
             ComponentName componentName,
             IConnectionService outgoingConnectionServiceRpc) {
-        if (!mRemoteConnectionServices.containsKey(componentName)) {
-            try {
-                RemoteConnectionService remoteConnectionService = new RemoteConnectionService(
-                        outgoingConnectionServiceRpc,
-                        mOurConnectionServiceImpl);
-                mRemoteConnectionServices.put(componentName, remoteConnectionService);
-            } catch (RemoteException e) {
-                Log.w(RemoteConnectionManager.this,
-                        "error when addConnectionService of %s: %s", componentName,
-                        e.toString());
-            }
-        }
+        mRemoteConnectionServices.computeIfAbsent(
+                componentName,
+                key -> {
+                    try {
+                        return new RemoteConnectionService(
+                                outgoingConnectionServiceRpc, mOurConnectionServiceImpl);
+                    } catch (RemoteException e) {
+                        Log.w(
+                                RemoteConnectionManager.this,
+                                "error when addConnectionService of %s: %s",
+                                componentName,
+                                e.toString());
+                        return null;
+                    }
+                });
     }
 
     public RemoteConnection createRemoteConnection(
@@ -63,17 +66,14 @@
         }
 
         ComponentName componentName = request.getAccountHandle().getComponentName();
-        if (!mRemoteConnectionServices.containsKey(componentName)) {
+        RemoteConnectionService remoteService = mRemoteConnectionServices.get(componentName);
+        if (remoteService == null) {
             throw new UnsupportedOperationException("accountHandle not supported: "
                     + componentName);
         }
 
-        RemoteConnectionService remoteService = mRemoteConnectionServices.get(componentName);
-        if (remoteService != null) {
-            return remoteService.createRemoteConnection(
-                    connectionManagerPhoneAccount, request, isIncoming);
-        }
-        return null;
+        return remoteService.createRemoteConnection(
+                connectionManagerPhoneAccount, request, isIncoming);
     }
 
     /**
@@ -94,17 +94,14 @@
         }
 
         ComponentName componentName = request.getAccountHandle().getComponentName();
-        if (!mRemoteConnectionServices.containsKey(componentName)) {
+        RemoteConnectionService remoteService = mRemoteConnectionServices.get(componentName);
+        if (remoteService == null) {
             throw new UnsupportedOperationException("accountHandle not supported: "
                     + componentName);
         }
 
-        RemoteConnectionService remoteService = mRemoteConnectionServices.get(componentName);
-        if (remoteService != null) {
-            return remoteService.createRemoteConference(
-                    connectionManagerPhoneAccount, request, isIncoming);
-        }
-        return null;
+        return remoteService.createRemoteConference(
+                connectionManagerPhoneAccount, request, isIncoming);
     }
 
     public void conferenceRemoteConnections(RemoteConnection a, RemoteConnection b) {
diff --git a/telephony/common/com/android/internal/telephony/SmsApplication.java b/telephony/common/com/android/internal/telephony/SmsApplication.java
index 4230225..dc75fb5 100644
--- a/telephony/common/com/android/internal/telephony/SmsApplication.java
+++ b/telephony/common/com/android/internal/telephony/SmsApplication.java
@@ -783,7 +783,7 @@
                         AppOpsManager.MODE_ALLOWED);
             }
         } catch (NameNotFoundException e) {
-            // No whitelisted system app on this device
+            // No allowlisted system app on this device
             Log.e(LOG_TAG, "Package not found: " + packageName);
         }
 
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index 63dbeeb..e6b7cf3b 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -244,7 +244,8 @@
     /**
      * Boolean indicating if the "Caller ID" item is visible in the Additional Settings menu.
      * true means visible. false means gone.
-     * @hide
+     *
+     * The default value is true.
      */
     public static final String KEY_ADDITIONAL_SETTINGS_CALLER_ID_VISIBILITY_BOOL =
             "additional_settings_caller_id_visibility_bool";
@@ -252,7 +253,8 @@
     /**
      * Boolean indicating if the "Call Waiting" item is visible in the Additional Settings menu.
      * true means visible. false means gone.
-     * @hide
+     *
+     * The default value is true.
      */
     public static final String KEY_ADDITIONAL_SETTINGS_CALL_WAITING_VISIBILITY_BOOL =
             "additional_settings_call_waiting_visibility_bool";
@@ -4437,12 +4439,12 @@
      *
      * <p>Example:
      *
-     * <pre><code>
+     * <pre>{@code
      * <string-array name="carrier_service_name_array" num="2">
      *   <item value="Police"/>
      *   <item value="Ambulance"/>
      * </string-array>
-     * </code></pre>
+     * }</pre>
      */
     public static final String KEY_CARRIER_SERVICE_NAME_STRING_ARRAY = "carrier_service_name_array";
 
@@ -4456,18 +4458,18 @@
      *
      * <ul>
      *   <li>The number of items in both the arrays are equal
-     *   <li>The item added in this key follows a specific format. Either it should be all numbers,
-     *       or "+" followed by all numbers.
+     *   <li>The item should contain dialable characters only which includes 0-9, -, *, #, (, ),
+     *       SPACE.
      * </ul>
      *
      * <p>Example:
      *
-     * <pre><code>
+     * <pre>{@code
      * <string-array name="carrier_service_number_array" num="2">
-     *   <item value="123"/>
-     *   <item value="+343"/>
+     *   <item value="*123"/>
+     *   <item value="+ (111) 111-111"/>
      * </string-array>
-     * </code></pre>
+     * }</pre>
      */
     public static final String KEY_CARRIER_SERVICE_NUMBER_STRING_ARRAY =
         "carrier_service_number_array";
@@ -9899,4 +9901,38 @@
         }
         trm.removeCarrierConfigChangedListener(listener);
     }
+
+    /**
+     * Get subset of specified carrier configuration if available or empty bundle, without throwing
+     * {@link RuntimeException} to caller.
+     *
+     * <p>This is a system internally used only utility to reduce the repetitive logic.
+     *
+     * <p>Requires Permission:
+     * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}, or the calling app
+     * has carrier privileges on the specified subscription (see
+     * {@link TelephonyManager#hasCarrierPrivileges()}).
+     *
+     * @param context Context used to get the CarrierConfigManager service.
+     * @param subId The subscription ID to get the config from.
+     * @param keys The config keys the client is interested in.
+     * @return Config bundle with key/value for the specified keys or empty bundle when failed
+     * @hide
+     */
+    @RequiresPermission(anyOf = {
+            Manifest.permission.READ_PHONE_STATE,
+            "carrier privileges",
+    })
+    @NonNull
+    public static PersistableBundle getCarrierConfigSubset(
+            @NonNull Context context, int subId, @NonNull String... keys) {
+        PersistableBundle configs = null;
+        CarrierConfigManager ccm = context.getSystemService(CarrierConfigManager.class);
+        try {
+            configs = ccm.getConfigForSubId(subId, keys);
+        } catch (RuntimeException exception) {
+            Rlog.w(TAG, "CarrierConfigLoader is not available.");
+        }
+        return configs != null ? configs : new PersistableBundle();
+    }
 }
diff --git a/telephony/java/android/telephony/PhysicalChannelConfig.java b/telephony/java/android/telephony/PhysicalChannelConfig.java
index 212aaae..2c6d457 100644
--- a/telephony/java/android/telephony/PhysicalChannelConfig.java
+++ b/telephony/java/android/telephony/PhysicalChannelConfig.java
@@ -37,15 +37,26 @@
 
     /**
      * UE has connection to cell for signalling and possibly data (3GPP 36.331, 25.331).
+     *
+     * @deprecated Use {@link  CellInfo#CONNECTION_PRIMARY_SERVING} instead.
      */
+    @Deprecated
     public static final int CONNECTION_PRIMARY_SERVING = 1;
 
     /**
      * UE has connection to cell for data (3GPP 36.331, 25.331).
+     *
+     * @deprecated Use {@link  CellInfo#CONNECTION_SECONDARY_SERVING} instead.
      */
+    @Deprecated
     public static final int CONNECTION_SECONDARY_SERVING = 2;
 
-    /** Connection status is unknown. */
+    /**
+     * Connection status is unknown.
+     *
+     * @deprecated Use {@link  CellInfo#CONNECTION_UNKNOWN} instead.
+     */
+    @Deprecated
     public static final int CONNECTION_UNKNOWN = -1;
 
     /** Channel number is unknown. */
diff --git a/telephony/java/android/telephony/SmsManager.java b/telephony/java/android/telephony/SmsManager.java
index 1cf2969..1a28ad8 100644
--- a/telephony/java/android/telephony/SmsManager.java
+++ b/telephony/java/android/telephony/SmsManager.java
@@ -340,7 +340,7 @@
     }
 
     /**
-     * Get {@link Context#getOpPackageName()} if this manager has a context, otherwise a dummy
+     * Get {@link Context#getOpPackageName()} if this manager has a context, otherwise a placeholder
      * value.
      *
      * @return The package name to be used for app-ops checks
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index 45c092e..96dc44a 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -174,7 +174,7 @@
     /**
      * Key to the backup & restore data byte array in the Bundle that is returned by {@link
      * #getAllSimSpecificSettingsForBackup()} or to be pass in to {@link
-     * #restoreAllSimSpecificSettings()}.
+     * #restoreAllSimSpecificSettingsFromBackup(byte[])}.
      *
      * @hide
      */
@@ -2218,46 +2218,46 @@
     }
 
     /**
-     * Get an array of subscription ids for specified logical SIM slot Index.
+     * Get an array of subscription ids for the specified logical SIM slot Index. The maximum size
+     * of the array is 1. This API was mistakenly designed to return multiple subscription ids,
+     * which is not possible in the current Android telephony architecture.
      *
      * @param slotIndex The logical SIM slot index.
      *
-     * @return subscription Ids or {@code null} if the given slot index is not valid or there are
-     * no active subscription in the slot. In the implementation today, there will be no more
-     * than one subscriptions per logical SIM slot.
+     * @return Subscription id of the active subscription on the specified logical SIM slot index.
+     * If SIM is absent on the slot, a single element array of {@link #INVALID_SUBSCRIPTION_ID} will
+     * be returned. {@code null} if the provided {@code slotIndex} is not valid.
      *
      * @deprecated Use {@link #getSubscriptionId(int)} instead.
      */
     @Deprecated
     @Nullable
     public int[] getSubscriptionIds(int slotIndex) {
-        int subId = getSubscriptionId(slotIndex);
-        if (!isValidSubscriptionId(subId)) {
+        if (!isValidSlotIndex(slotIndex)) {
             return null;
         }
         return new int[]{getSubscriptionId(slotIndex)};
     }
 
-    /** @hide */
-    @UnsupportedAppUsage
+    /**
+     * Get an array of subscription ids for the specified logical SIM slot Index. The maximum size
+     * of the array is 1. This API was mistakenly designed to return multiple subscription ids,
+     * which is not possible in the current Android telephony architecture.
+     *
+     * @param slotIndex The logical SIM slot index.
+     *
+     * @return Subscription id of the active subscription on the specified logical SIM slot index.
+     * If SIM is absent on the slot, a single element array of {@link #INVALID_SUBSCRIPTION_ID} will
+     * be returned. {@code null} if the provided {@code slotIndex} is not valid.
+     *
+     * @deprecated Use {@link #getSubscriptionId(int)} instead.
+     * @hide
+     */
     public static int[] getSubId(int slotIndex) {
         if (!isValidSlotIndex(slotIndex)) {
-            logd("[getSubId]- fail");
             return null;
         }
-
-        int[] subId = null;
-
-        try {
-            ISub iSub = TelephonyManager.getSubscriptionService();
-            if (iSub != null) {
-                subId = iSub.getSubIds(slotIndex);
-            }
-        } catch (RemoteException ex) {
-            // ignore it
-        }
-
-        return subId;
+        return new int[]{getSubscriptionId(slotIndex)};
     }
 
     /**
@@ -3628,17 +3628,10 @@
     }
 
     /**
-     * Enables or disables a subscription. This is currently used in the settings page. It will
-     * fail and return false if operation is not supported or failed.
+     * Enable or disable a subscription. This method is same as
+     * {@link #setUiccApplicationsEnabled(int, boolean)}.
      *
-     * To disable an active subscription on a physical (non-Euicc) SIM,
-     * {@link #canDisablePhysicalSubscription} needs to be true.
-     *
-     * <p>
-     * Permissions android.Manifest.permission.MODIFY_PHONE_STATE is required
-     *
-     * @param subscriptionId Subscription to be enabled or disabled. It could be a eSIM or pSIM
-     * subscription.
+     * @param subscriptionId Subscription to be enabled or disabled.
      * @param enable whether user is turning it on or off.
      *
      * @return whether the operation is successful.
@@ -3648,19 +3641,15 @@
     @SystemApi
     @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
     public boolean setSubscriptionEnabled(int subscriptionId, boolean enable) {
-        if (VDBG) {
-            logd("setSubscriptionActivated subId= " + subscriptionId + " enable " + enable);
-        }
         try {
             ISub iSub = TelephonyManager.getSubscriptionService();
             if (iSub != null) {
-                return iSub.setSubscriptionEnabled(enable, subscriptionId);
+                iSub.setUiccApplicationsEnabled(enable, subscriptionId);
             }
         } catch (RemoteException ex) {
-            // ignore it
+            return false;
         }
-
-        return false;
+        return true;
     }
 
     /**
@@ -3683,11 +3672,7 @@
             logd("setUiccApplicationsEnabled subId= " + subscriptionId + " enable " + enabled);
         }
         try {
-            ISub iSub = ISub.Stub.asInterface(
-                    TelephonyFrameworkInitializer
-                            .getTelephonyServiceManager()
-                            .getSubscriptionServiceRegisterer()
-                            .get());
+            ISub iSub = TelephonyManager.getSubscriptionService();
             if (iSub != null) {
                 iSub.setUiccApplicationsEnabled(enabled, subscriptionId);
             }
@@ -3715,11 +3700,7 @@
             logd("canDisablePhysicalSubscription");
         }
         try {
-            ISub iSub = ISub.Stub.asInterface(
-                    TelephonyFrameworkInitializer
-                            .getTelephonyServiceManager()
-                            .getSubscriptionServiceRegisterer()
-                            .get());
+            ISub iSub = TelephonyManager.getSubscriptionService();
             if (iSub != null) {
                 return iSub.canDisablePhysicalSubscription();
             }
@@ -3843,10 +3824,15 @@
     }
 
     /**
-     * DO NOT USE.
-     * This API is designed for features that are not finished at this point. Do not call this API.
+     * Get the active subscription id by logical SIM slot index.
+     *
+     * @param slotIndex The logical SIM slot index.
+     * @return The active subscription id.
+     *
+     * @throws IllegalArgumentException if the provided slot index is invalid.
+     * @throws SecurityException if callers do not hold the required permission.
+     *
      * @hide
-     * TODO b/135547512: further clean up
      */
     @SystemApi
     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
@@ -4027,39 +4013,16 @@
     }
 
     /**
-     * Called to attempt to restore the backed up sim-specific configs to device for specific sim.
-     * This will try to restore the data that was stored internally when {@link
-     * #restoreAllSimSpecificSettingsFromBackup(byte[] data)} was called during setup wizard.
-     * End result is SimInfoDB is modified to match any backed up configs for the requested
-     * inserted sim.
-     *
-     * <p>
-     * The {@link Uri} {@link #SIM_INFO_BACKUP_AND_RESTORE_CONTENT_URI} is notified if any SimInfoDB
-     * entry is updated as the result of this method call.
-     *
-     * @param iccId of the sim that a restore is requested for.
-     *
-     * @hide
-     */
-    @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
-    public void restoreSimSpecificSettingsForIccIdFromBackup(@NonNull String iccId) {
-        mContext.getContentResolver().call(
-                SIM_INFO_BACKUP_AND_RESTORE_CONTENT_URI,
-                RESTORE_SIM_SPECIFIC_SETTINGS_METHOD_NAME,
-                iccId, null);
-    }
-
-    /**
      * Called during setup wizard restore flow to attempt to restore the backed up sim-specific
-     * configs to device for all existing SIMs in SimInfoDB. Internally, it will store the backup
-     * data in an internal file. This file will persist on device for device's lifetime and will be
-     * used later on when a SIM is inserted to restore that specific SIM's settings by calling
-     * {@link #restoreSimSpecificSettingsForIccIdFromBackup(String iccId)}. End result is
-     * SimInfoDB is modified to match any backed up configs for the appropriate inserted SIMs.
+     * configs to device for all existing SIMs in the subscription database {@link SimInfo}.
+     * Internally, it will store the backup data in an internal file. This file will persist on
+     * device for device's lifetime and will be used later on when a SIM is inserted to restore that
+     * specific SIM's settings. End result is subscription database is modified to match any backed
+     * up configs for the appropriate inserted SIMs.
      *
      * <p>
-     * The {@link Uri} {@link #SIM_INFO_BACKUP_AND_RESTORE_CONTENT_URI} is notified if any SimInfoDB
-     * entry is updated as the result of this method call.
+     * The {@link Uri} {@link #SIM_INFO_BACKUP_AND_RESTORE_CONTENT_URI} is notified if any
+     * {@link SimInfo} entry is updated as the result of this method call.
      *
      * @param data with the sim specific configs to be backed up.
      *
@@ -4068,12 +4031,18 @@
     @SystemApi
     @RequiresPermission(Manifest.permission.MODIFY_PHONE_STATE)
     public void restoreAllSimSpecificSettingsFromBackup(@NonNull byte[] data) {
-        Bundle bundle = new Bundle();
-        bundle.putByteArray(KEY_SIM_SPECIFIC_SETTINGS_DATA, data);
-        mContext.getContentResolver().call(
-                SIM_INFO_BACKUP_AND_RESTORE_CONTENT_URI,
-                RESTORE_SIM_SPECIFIC_SETTINGS_METHOD_NAME,
-                null, bundle);
+        try {
+            ISub iSub = TelephonyManager.getSubscriptionService();
+            if (iSub != null) {
+                iSub.restoreAllSimSpecificSettingsFromBackup(data);
+            } else {
+                throw new IllegalStateException("subscription service unavailable.");
+            }
+        } catch (RemoteException ex) {
+            if (!isSystemProcess()) {
+                ex.rethrowAsRuntimeException();
+            }
+        }
     }
 
     /**
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index fa60031..692ac70 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -7713,7 +7713,7 @@
     }
 
     /**
-     * Rollback modem configurations to factory default except some config which are in whitelist.
+     * Rollback modem configurations to factory default except some config which are in allowlist.
      * Used for device configuration by some carriers.
      *
      * <p>Requires Permission:
@@ -14785,7 +14785,7 @@
      *
      *  1) User data is turned on, or
      *  2) APN is un-metered for this subscription, or
-     *  3) APN type is whitelisted. E.g. MMS is whitelisted if
+     *  3) APN type is allowlisted. E.g. MMS is allowlisted if
      *  {@link #MOBILE_DATA_POLICY_MMS_ALWAYS_ALLOWED} is enabled.
      *
      * @param apnType Value indicating the apn type. Apn types are defined in {@link ApnSetting}.
diff --git a/telephony/java/android/telephony/ims/ImsReasonInfo.java b/telephony/java/android/telephony/ims/ImsReasonInfo.java
index dda021e..67acda0 100644
--- a/telephony/java/android/telephony/ims/ImsReasonInfo.java
+++ b/telephony/java/android/telephony/ims/ImsReasonInfo.java
@@ -460,7 +460,7 @@
      */
     public static final int CODE_LOW_BATTERY = 505;
     /**
-     * Device declined a call due to a blacklisted caller ID.
+     * Device declined a call due to a denylisted caller ID.
      */
     public static final int CODE_BLACKLISTED_CALL_ID = 506;
     // IMS -> Telephony
diff --git a/telephony/java/com/android/internal/telephony/ISub.aidl b/telephony/java/com/android/internal/telephony/ISub.aidl
index defa046..6a5380d 100644
--- a/telephony/java/com/android/internal/telephony/ISub.aidl
+++ b/telephony/java/com/android/internal/telephony/ISub.aidl
@@ -236,8 +236,6 @@
 
     int getSlotIndex(int subId);
 
-    int[] getSubIds(int slotIndex);
-
     int getSubId(int slotIndex);
 
     int getDefaultSubId();
@@ -267,8 +265,6 @@
     String getSubscriptionProperty(int subId, String propKey, String callingPackage,
             String callingFeatureId);
 
-    boolean setSubscriptionEnabled(boolean enable, int subId);
-
     boolean isSubscriptionEnabled(int subId);
 
     int getEnabledSubscriptionId(int slotIndex);
@@ -279,7 +275,7 @@
 
     boolean canDisablePhysicalSubscription();
 
-    int setUiccApplicationsEnabled(boolean enabled, int subscriptionId);
+    void setUiccApplicationsEnabled(boolean enabled, int subscriptionId);
 
     int setDeviceToDeviceStatusSharing(int sharing, int subId);
 
@@ -363,4 +359,20 @@
         */
        //TODO: Removed before U AOSP public release.
        boolean isSubscriptionManagerServiceEnabled();
+
+      /**
+       * Called during setup wizard restore flow to attempt to restore the backed up sim-specific
+       * configs to device for all existing SIMs in the subscription database
+       * {@link Telephony.SimInfo}. Internally, it will store the backup data in an internal file.
+       * This file will persist on device for device's lifetime and will be used later on when a SIM
+       * is inserted to restore that specific SIM's settings. End result is subscription database is
+       * modified to match any backed up configs for the appropriate inserted SIMs.
+       *
+       * <p>
+       * The {@link Uri} {@link #SIM_INFO_BACKUP_AND_RESTORE_CONTENT_URI} is notified if any
+       * {@link Telephony.SimInfo} entry is updated as the result of this method call.
+       *
+       * @param data with the sim specific configs to be backed up.
+       */
+       void restoreAllSimSpecificSettingsFromBackup(in byte[] data);
 }
diff --git a/telephony/java/com/android/internal/telephony/ITelephony.aidl b/telephony/java/com/android/internal/telephony/ITelephony.aidl
index ecafe70..9d05517 100644
--- a/telephony/java/com/android/internal/telephony/ITelephony.aidl
+++ b/telephony/java/com/android/internal/telephony/ITelephony.aidl
@@ -1791,6 +1791,22 @@
             String gid2, String plmn, String spn, String carrierPrivilegeRules, String apn);
 
     /**
+     * Forcibly sets a package as a carrier provisioning package.
+     *
+     * This override is ephemeral, and will disappear upon phone process restart (including
+     * device reboot).
+     *
+     * WARNING: This API is meant for testing purposes only. This enables automated testing for
+     * cases where the carrier service package is used as a permissioning gate for features such as
+     * restricted carrier network access (restricted APNs and Merged Carrier Wifi)
+     *
+     * @param carrierServicePackage The package that should be marked as the carrier service
+     *     package, or {@code null} to disable the override.
+     */
+    void setCarrierServicePackageOverride(int subId, String carrierServicePackage,
+                String callingPackage);
+
+    /**
      * A test API to return installed carrier id list version.
      */
     int getCarrierIdListVersion(int subId);
diff --git a/tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java
index 0f694c2..fe91260 100644
--- a/tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java
+++ b/tests/ApkVerityTest/ApkVerityTestApp/feature_split/src/com/android/apkverity/feature_x/DummyActivity.java
@@ -18,5 +18,5 @@
 
 import android.app.Activity;
 
-/** Dummy class just to generate some dex */
+/** Placeholder class just to generate some dex */
 public class DummyActivity extends Activity {}
diff --git a/tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java b/tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java
index 837c7be..a7bd771 100644
--- a/tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java
+++ b/tests/ApkVerityTest/ApkVerityTestApp/src/com/android/apkverity/DummyActivity.java
@@ -18,5 +18,5 @@
 
 import android.app.Activity;
 
-/** Dummy class just to generate some dex */
+/** Placeholder class just to generate some dex */
 public class DummyActivity extends Activity {}
diff --git a/tests/AppLaunch/src/com/android/tests/applaunch/AppLaunch.java b/tests/AppLaunch/src/com/android/tests/applaunch/AppLaunch.java
index 1a58f17..fa452dd 100644
--- a/tests/AppLaunch/src/com/android/tests/applaunch/AppLaunch.java
+++ b/tests/AppLaunch/src/com/android/tests/applaunch/AppLaunch.java
@@ -674,7 +674,7 @@
             return true;
         }
 
-        // iorap compiler filters specified: the compilerFilter must be in the whitelist.
+        // iorap compiler filters specified: the compilerFilter must be in the allowlist.
         if (mIorapCompilerFilters.indexOf(compilerFilter) != -1) {
             return true;
         }
diff --git a/tests/AttestationVerificationTest/src/android/security/attestationverification/PeerDeviceSystemAttestationVerificationTest.kt b/tests/AttestationVerificationTest/src/android/security/attestationverification/PeerDeviceSystemAttestationVerificationTest.kt
index 32c2230..ad95fbc 100644
--- a/tests/AttestationVerificationTest/src/android/security/attestationverification/PeerDeviceSystemAttestationVerificationTest.kt
+++ b/tests/AttestationVerificationTest/src/android/security/attestationverification/PeerDeviceSystemAttestationVerificationTest.kt
@@ -39,7 +39,7 @@
     @Before
     fun setup() {
         rule.getScenario().onActivity {
-            avm = it.getSystemService(AttestationVerificationManager::class.java)
+            avm = it.getSystemService(AttestationVerificationManager::class.java)!!
             activity = it
         }
         invalidAttestationByteArray = TEST_ATTESTATION_CERT_FILENAME.fromPEMFileToByteArray()
diff --git a/tests/AttestationVerificationTest/src/android/security/attestationverification/SystemAttestationVerificationTest.kt b/tests/AttestationVerificationTest/src/android/security/attestationverification/SystemAttestationVerificationTest.kt
index 169effa..8f06b4a2 100644
--- a/tests/AttestationVerificationTest/src/android/security/attestationverification/SystemAttestationVerificationTest.kt
+++ b/tests/AttestationVerificationTest/src/android/security/attestationverification/SystemAttestationVerificationTest.kt
@@ -43,7 +43,7 @@
     @Before
     fun setup() {
         rule.getScenario().onActivity {
-            avm = it.getSystemService(AttestationVerificationManager::class.java)
+            avm = it.getSystemService(AttestationVerificationManager::class.java)!!
             activity = it
             androidKeystore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
         }
diff --git a/tests/BinderLeakTest/Android.bp b/tests/BinderLeakTest/Android.bp
new file mode 100644
index 0000000..78b0ede
--- /dev/null
+++ b/tests/BinderLeakTest/Android.bp
@@ -0,0 +1,40 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_base_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_base_license"],
+}
+
+filegroup {
+    name: "binder_leak_test_aidl",
+    srcs: ["**/*.aidl"],
+    path: "aidl",
+}
+
+java_defaults {
+    name: "BinderTest.defaults",
+    srcs: [
+        "**/*.java",
+        ":binder_leak_test_aidl",
+    ],
+    static_libs: [
+        "androidx.test.ext.junit",
+        "androidx.test.rules",
+        "androidx.test.runner",
+    ],
+}
+
+// Built with target_sdk_version: current
+android_test {
+    name: "BinderLeakTest",
+    defaults: ["BinderTest.defaults"],
+}
+
+// Built with target_sdk_version: 33
+android_test {
+    name: "BinderLeakTest_legacy",
+    defaults: ["BinderTest.defaults"],
+    manifest: "AndroidManifest_legacy.xml",
+}
diff --git a/tests/BinderLeakTest/AndroidManifest.xml b/tests/BinderLeakTest/AndroidManifest.xml
new file mode 100644
index 0000000..756def7
--- /dev/null
+++ b/tests/BinderLeakTest/AndroidManifest.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.test.binder">
+    <application>
+        <service
+            android:name=".MyService"
+            android:enabled="true"
+            android:exported="true"
+            android:process=":service">
+        </service>
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.test.binder"
+        android:label="Binder leak test">
+    </instrumentation>
+</manifest>
diff --git a/tests/BinderLeakTest/AndroidManifest_legacy.xml b/tests/BinderLeakTest/AndroidManifest_legacy.xml
new file mode 100644
index 0000000..03d1dfd
--- /dev/null
+++ b/tests/BinderLeakTest/AndroidManifest_legacy.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.test.binder">
+    <uses-sdk android:minSdkVersion="33"
+          android:targetSdkVersion="33"
+          android:maxSdkVersion="33" />
+    <application>
+        <service
+            android:name=".MyService"
+            android:enabled="true"
+            android:exported="true"
+            android:process=":service">
+        </service>
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.test.binder"
+        android:label="Binder leak test">
+    </instrumentation>
+</manifest>
diff --git a/tests/BinderLeakTest/aidl/com/android/test/binder/IFoo.aidl b/tests/BinderLeakTest/aidl/com/android/test/binder/IFoo.aidl
new file mode 100644
index 0000000..a721959
--- /dev/null
+++ b/tests/BinderLeakTest/aidl/com/android/test/binder/IFoo.aidl
@@ -0,0 +1,5 @@
+package com.android.test.binder;
+
+interface IFoo {
+
+}
diff --git a/tests/BinderLeakTest/aidl/com/android/test/binder/IFooProvider.aidl b/tests/BinderLeakTest/aidl/com/android/test/binder/IFooProvider.aidl
new file mode 100644
index 0000000..b487f51
--- /dev/null
+++ b/tests/BinderLeakTest/aidl/com/android/test/binder/IFooProvider.aidl
@@ -0,0 +1,10 @@
+package com.android.test.binder;
+import com.android.test.binder.IFoo;
+
+interface IFooProvider {
+    IFoo createFoo();
+
+    boolean isFooGarbageCollected();
+
+    oneway void killProcess();
+}
diff --git a/tests/BinderLeakTest/java/com/android/test/binder/BinderTest.java b/tests/BinderLeakTest/java/com/android/test/binder/BinderTest.java
new file mode 100644
index 0000000..f07317f
--- /dev/null
+++ b/tests/BinderLeakTest/java/com/android/test/binder/BinderTest.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2023 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.test.binder;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+
+import android.content.Intent;
+import android.os.Build;
+import android.os.IBinder;
+import android.os.RemoteException;
+
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.rule.ServiceTestRule;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.lang.ref.PhantomReference;
+import java.lang.ref.ReferenceQueue;
+import java.util.concurrent.TimeoutException;
+
+@RunWith(AndroidJUnit4.class)
+public class BinderTest {
+    @Rule
+    public final ServiceTestRule serviceRule = new ServiceTestRule();
+
+    @Test
+    public void testDeathRecipientLeaksOrNot()
+            throws RemoteException, TimeoutException, InterruptedException {
+        Intent intent = new Intent(ApplicationProvider.getApplicationContext(), MyService.class);
+        IFooProvider provider = IFooProvider.Stub.asInterface(serviceRule.bindService(intent));
+        FooHolder holder = new FooHolder(provider.createFoo());
+
+        // ref will get enqueued right after holder is finalized for gc.
+        ReferenceQueue<FooHolder> refQueue = new ReferenceQueue<>();
+        PhantomReference<FooHolder> ref = new PhantomReference<>(holder, refQueue);
+
+        DeathRecorder deathRecorder = new DeathRecorder();
+        holder.registerDeathRecorder(deathRecorder);
+
+        if (getSdkVersion() >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
+            /////////////////////////////////////////////
+            // New behavior
+            //
+            // Reference chain at this moment:
+            // holder --(java strong ref)--> FooHolder
+            // FooHolder.mProxy --(java strong ref)--> IFoo.Proxy
+            // IFoo.Proxy.mRemote --(java strong ref)--> BinderProxy
+            // BinderProxy --(binder ref)--> Foo.Stub
+            // In other words, the variable "holder" is the root of the reference chain.
+
+            // By setting the variable to null, we make FooHolder, IFoo.Proxy, BinderProxy, and even
+            // Foo.Stub unreachable.
+            holder = null;
+
+            // Ensure that the objects are garbage collected
+            forceGc();
+            assertEquals(ref, refQueue.poll());
+            assertTrue(provider.isFooGarbageCollected());
+
+            // The binder has died, but we don't get notified since the death recipient is GC'ed.
+            provider.killProcess();
+            Thread.sleep(1000); // give some time for the service process to die and reaped
+            assertFalse(deathRecorder.deathRecorded);
+        } else {
+            /////////////////////////////////////////////
+            // Legacy behavior
+            //
+            // Reference chain at this moment:
+            // JavaDeathRecipient --(JNI strong ref)--> FooHolder
+            // holder --(java strong ref)--> FooHolder
+            // FooHolder.mProxy --(java strong ref)--> IFoo.Proxy
+            // IFoo.Proxy.mRemote --(java strong ref)--> BinderProxy
+            // BinderProxy --(binder ref)--> Foo.Stub
+            // So, BOTH JavaDeathRecipient and holder are roots of the reference chain.
+
+            // Even if we set holder to null, it doesn't make other objects unreachable; they are
+            // still reachable via the JNI strong ref.
+            holder = null;
+
+            // Check that objects are not garbage collected
+            forceGc();
+            assertNotEquals(ref, refQueue.poll());
+            assertFalse(provider.isFooGarbageCollected());
+
+            // The legacy behavior is getting notified even when there's no reference
+            provider.killProcess();
+            Thread.sleep(1000); // give some time for the service process to die and reaped
+            assertTrue(deathRecorder.deathRecorded);
+        }
+    }
+
+    static class FooHolder implements IBinder.DeathRecipient {
+        private IFoo mProxy;
+        private DeathRecorder mDeathRecorder;
+
+        FooHolder(IFoo proxy) throws RemoteException {
+            proxy.asBinder().linkToDeath(this, 0);
+
+            // A strong reference from DeathRecipient(this) to the binder proxy is created here
+            mProxy = proxy;
+        }
+
+        public void registerDeathRecorder(DeathRecorder dr) {
+            mDeathRecorder = dr;
+        }
+
+        @Override
+        public void binderDied() {
+            if (mDeathRecorder != null) {
+                mDeathRecorder.deathRecorded = true;
+            }
+        }
+    }
+
+    static class DeathRecorder {
+        public boolean deathRecorded = false;
+    }
+
+    // Try calling System.gc() until an orphaned object is confirmed to be finalized
+    private static void forceGc() {
+        Object obj = new Object();
+        ReferenceQueue<Object> refQueue = new ReferenceQueue<>();
+        PhantomReference<Object> ref = new PhantomReference<>(obj, refQueue);
+        obj = null; // make it an orphan
+        while (refQueue.poll() != ref) {
+            System.gc();
+        }
+    }
+
+    private static int getSdkVersion() {
+        return ApplicationProvider.getApplicationContext().getApplicationInfo().targetSdkVersion;
+    }
+}
diff --git a/tests/BinderLeakTest/java/com/android/test/binder/MyService.java b/tests/BinderLeakTest/java/com/android/test/binder/MyService.java
new file mode 100644
index 0000000..c701253
--- /dev/null
+++ b/tests/BinderLeakTest/java/com/android/test/binder/MyService.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2023 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.test.binder;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.os.RemoteException;
+
+import java.lang.ref.PhantomReference;
+import java.lang.ref.ReferenceQueue;
+
+public class MyService extends Service {
+    @Override
+    public IBinder onBind(Intent intent) {
+        return new IFooProvider.Stub() {
+            ReferenceQueue<IFoo> mRefQueue = new ReferenceQueue<>();
+            PhantomReference<IFoo> mRef;
+
+            @Override
+            public IFoo createFoo() throws RemoteException {
+                IFoo binder = new IFoo.Stub() {};
+                mRef = new PhantomReference<>(binder, mRefQueue);
+                return binder;
+            }
+
+            @Override
+            public boolean isFooGarbageCollected() throws RemoteException {
+                forceGc();
+                return mRefQueue.poll() == mRef;
+            }
+
+            @Override
+            public void killProcess() throws RemoteException {
+                android.os.Process.killProcess(android.os.Process.myPid());
+            }
+        };
+    }
+
+    private static void forceGc() {
+        Object obj = new Object();
+        ReferenceQueue<Object> refQueue = new ReferenceQueue<>();
+        PhantomReference<Object> ref = new PhantomReference<>(obj, refQueue);
+        obj = null; // make it an orphan
+        while (refQueue.poll() != ref) {
+            System.gc();
+        }
+    }
+}
diff --git a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/BackingStore.java b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/BackingStore.java
index 216e743..df140b9 100644
--- a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/BackingStore.java
+++ b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/BackingStore.java
@@ -14,17 +14,10 @@
 
 package androidx.media.filterfw;
 
-import android.annotation.TargetApi;
 import android.graphics.Bitmap;
-import android.os.Build;
-import android.renderscript.Allocation;
-import android.renderscript.Element;
-import android.renderscript.RenderScript;
-import android.renderscript.Type;
 import android.util.Log;
 
 import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
 import java.util.Arrays;
 import java.util.Vector;
 
@@ -42,14 +35,11 @@
     static final int ACCESS_OBJECT = 0x08;
     /** Access mode Bitmap: Frame data will be accessed as a Bitmap. */
     static final int ACCESS_BITMAP = 0x10;
-    /** Access mode Allocation: Frame data will be accessed as a RenderScript Allocation. */
-    static final int ACCESS_ALLOCATION = 0x20;
 
     private static final int BACKING_BYTEBUFFER = 1;
     private static final int BACKING_TEXTURE = 2;
     private static final int BACKING_OBJECT = 3;
     private static final int BACKING_BITMAP = 4;
-    private static final int BACKING_ALLOCATION = 5;
 
     private final FrameType mType;
     private int[] mDimensions;
@@ -243,14 +233,6 @@
                 case ACCESS_BITMAP:
                     backing = new BitmapBacking();
                     break;
-                case ACCESS_ALLOCATION:
-                    if (!AllocationBacking.isSupported()) {
-                        throw new RuntimeException(
-                                "Attempted to create an AllocationBacking in context that does " +
-                                "not support RenderScript!");
-                    }
-                    backing = new AllocationBacking(mFrameManager.getContext().getRenderScript());
-                    break;
             }
             if (backing == null) {
                 throw new RuntimeException(
@@ -518,9 +500,6 @@
                 RenderTarget renderTarget = (RenderTarget) backing.lock(ACCESS_RENDERTARGET);
                 mBitmap.copyPixelsFromBuffer(
                         renderTarget.getPixelData(mDimensions[0], mDimensions[1]));
-            } else if ((access & ACCESS_ALLOCATION) != 0 && AllocationBacking.isSupported()) {
-                createBitmap();
-                syncToAllocationBacking(backing);
             } else {
                 throw new RuntimeException("Cannot sync bytebuffer backing!");
             }
@@ -528,12 +507,6 @@
             mIsDirty = false;
         }
 
-        @TargetApi(11)
-        private void syncToAllocationBacking(Backing backing) {
-            Allocation allocation = (Allocation) backing.lock(ACCESS_ALLOCATION);
-            allocation.copyTo(mBitmap);
-        }
-
         @Override
         public Object lock(int accessType) {
             return mBitmap;
@@ -612,8 +585,6 @@
                 int w = mDimensions[0];
                 int h = mDimensions[1];
                 ImageShader.renderTextureToTarget(texture, getRenderTarget(), w, h);
-            } else if ((access & ACCESS_ALLOCATION) != 0 && AllocationBacking.isSupported()) {
-                syncToAllocationBacking(backing);
             } else {
                 throw new RuntimeException("Cannot sync bytebuffer backing!");
             }
@@ -621,14 +592,6 @@
             mIsDirty = false;
         }
 
-        @TargetApi(11)
-        private void syncToAllocationBacking(Backing backing) {
-            Allocation allocation = (Allocation) backing.lock(ACCESS_ALLOCATION);
-            ByteBuffer pixels = ByteBuffer.allocateDirect(getSize());
-            allocation.copyTo(pixels.array());
-            mTexture.allocateWithPixels(pixels, mDimensions[0], mDimensions[1]);
-        }
-
         @Override
         public Object lock(int accessType) {
             switch (accessType) {
@@ -733,8 +696,6 @@
                 ByteBuffer otherBuffer = (ByteBuffer) backing.lock(ACCESS_BYTES);
                 mBuffer.put(otherBuffer);
                 otherBuffer.rewind();
-            } else if ((access & ACCESS_ALLOCATION) != 0 && AllocationBacking.isSupported()) {
-                syncToAllocationBacking(backing);
             } else {
                 throw new RuntimeException("Cannot sync bytebuffer backing!");
             }
@@ -743,23 +704,6 @@
             mIsDirty = false;
         }
 
-        @TargetApi(11)
-        private void syncToAllocationBacking(Backing backing) {
-            Allocation allocation = (Allocation) backing.lock(ACCESS_ALLOCATION);
-            if (getElementId() == FrameType.ELEMENT_RGBA8888) {
-                byte[] bytes = mBuffer.array();
-                allocation.copyTo(bytes);
-            } else if (getElementId() == FrameType.ELEMENT_FLOAT32) {
-                float[] floats = new float[getSize() / 4];
-                allocation.copyTo(floats);
-                mBuffer.asFloatBuffer().put(floats);
-            } else {
-                throw new RuntimeException(
-                        "Trying to sync to an allocation with an unsupported element id: "
-                        + getElementId());
-            }
-        }
-
         @Override
         public Object lock(int accessType) {
             return mBuffer.rewind();
@@ -791,139 +735,4 @@
         }
 
     }
-
-    @TargetApi(11)
-    static class AllocationBacking extends Backing {
-
-        private final RenderScript mRenderScript;
-        private Allocation mAllocation = null;
-
-        public AllocationBacking(RenderScript renderScript) {
-            mRenderScript = renderScript;
-        }
-
-        @Override
-        public void allocate(FrameType frameType) {
-            assertCompatible(frameType);
-
-            Element element = null;
-            switch (frameType.getElementId()) {
-                case FrameType.ELEMENT_RGBA8888:
-                    element = Element.RGBA_8888(mRenderScript);
-                    break;
-                case FrameType.ELEMENT_FLOAT32:
-                    element = Element.F32(mRenderScript);
-                    break;
-            }
-            Type.Builder imageTypeBuilder = new Type.Builder(mRenderScript, element);
-            imageTypeBuilder.setX(mDimensions.length >= 1 ? mDimensions[0] : 1);
-            imageTypeBuilder.setY(mDimensions.length == 2 ? mDimensions[1] : 1);
-            Type imageType = imageTypeBuilder.create();
-
-            mAllocation = Allocation.createTyped(mRenderScript, imageType);
-        }
-
-        @Override
-        public int readAccess() {
-            return ACCESS_ALLOCATION;
-        }
-
-        @Override
-        public int writeAccess() {
-            return ACCESS_ALLOCATION;
-        }
-
-        @Override
-        public boolean requiresGpu() {
-            return false;
-        }
-
-        @Override
-        public void syncTo(Backing backing) {
-            int access = backing.readAccess();
-            if ((access & ACCESS_TEXTURE) != 0) {
-                RenderTarget target = (RenderTarget) backing.lock(ACCESS_RENDERTARGET);
-                ByteBuffer pixels = ByteBuffer.allocateDirect(getSize());
-                GLToolbox.readTarget(target, pixels, mDimensions[0], mDimensions[1]);
-                mAllocation.copyFrom(pixels.array());
-            } else if ((access & ACCESS_BITMAP) != 0) {
-                Bitmap bitmap = (Bitmap) backing.lock(ACCESS_BITMAP);
-                mAllocation.copyFrom(bitmap);
-            } else if ((access & ACCESS_BYTES) != 0) {
-                ByteBuffer buffer = (ByteBuffer) backing.lock(ACCESS_BYTES);
-                if (buffer.order() != ByteOrder.nativeOrder()) {
-                    throw new RuntimeException(
-                            "Trying to sync to the ByteBufferBacking with non-native byte order!");
-                }
-                byte[] bytes;
-                if (buffer.hasArray()) {
-                    bytes = buffer.array();
-                } else {
-                    bytes = new byte[getSize()];
-                    buffer.get(bytes);
-                    buffer.rewind();
-                }
-                mAllocation.copyFromUnchecked(bytes);
-            } else {
-                throw new RuntimeException("Cannot sync allocation backing!");
-            }
-            backing.unlock();
-            mIsDirty = false;
-        }
-
-        @Override
-        public Object lock(int accessType) {
-            return mAllocation;
-        }
-
-        @Override
-        public void unlock() {
-        }
-
-        @Override
-        public int getType() {
-            return BACKING_ALLOCATION;
-        }
-
-        @Override
-        public boolean shouldCache() {
-            return true;
-        }
-
-        @Override
-        public void destroy() {
-            if (mAllocation != null) {
-                mAllocation.destroy();
-                mAllocation = null;
-            }
-        }
-
-        @Override
-        public int getSize() {
-            int elementCount = 1;
-            for (int dim : mDimensions) {
-                elementCount *= dim;
-            }
-            return getElementSize() * elementCount;
-        }
-
-        public static boolean isSupported() {
-            return Build.VERSION.SDK_INT >= 11;
-        }
-
-        private void assertCompatible(FrameType type) {
-            // TODO: consider adding support for other data types.
-            if (type.getElementId() != FrameType.ELEMENT_RGBA8888
-                    && type.getElementId() != FrameType.ELEMENT_FLOAT32) {
-                throw new RuntimeException(
-                        "Cannot allocate allocation with a non-RGBA or non-float data type!");
-            }
-            if (mDimensions == null || mDimensions.length > 2) {
-                throw new RuntimeException(
-                        "Cannot create an allocation with more than 2 dimensions!");
-            }
-        }
-
-    }
-
 }
diff --git a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/FrameBuffer1D.java b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/FrameBuffer1D.java
index 0e24f5b..20cc1bf 100644
--- a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/FrameBuffer1D.java
+++ b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/FrameBuffer1D.java
@@ -16,9 +16,6 @@
 
 package androidx.media.filterfw;
 
-import android.annotation.TargetApi;
-import android.renderscript.Allocation;
-
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
 
@@ -40,19 +37,6 @@
         return (ByteBuffer)mBackingStore.lockData(mode, BackingStore.ACCESS_BYTES);
     }
 
-    /**
-     * Access frame's data using a RenderScript {@link Allocation}.
-     * This is a convenience method and is equivalent to calling {@code lockData} with an
-     * {@code accessFormat} of {@code ACCESS_ALLOCATION}.
-     *
-     * @return The Allocation instance holding the Frame's data.
-     */
-    @TargetApi(11)
-    public Allocation lockAllocation(int mode) {
-        assertAccessible(mode);
-        return (Allocation) mBackingStore.lockData(mode, BackingStore.ACCESS_ALLOCATION);
-    }
-
     public int getLength() {
         return mLength;
     }
diff --git a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/GraphExporter.java b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/GraphExporter.java
index 0013965..4b7ca53 100644
--- a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/GraphExporter.java
+++ b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/GraphExporter.java
@@ -113,7 +113,7 @@
                         getDotName(target.getFilter().getName()) + ":" +
                         getDotName(target.getName()) + "_IN;\n" );
                 } else {
-                    // Found a unconnected output port, add dummy node
+                    // Found a unconnected output port, add placeholder node
                     String color = filter.getSignature().getOutputPortInfo(portName).isRequired()
                         ? "red" : "blue";  // red for unconnected, required ports
                     dotFile.write("  " +
@@ -131,7 +131,7 @@
                 if(target != null) {
                     // Found a connection -- nothing to do, connections have been written out above
                 } else {
-                    // Found a unconnected input port, add dummy node
+                    // Found a unconnected input port, add placeholder node
                     String color = filter.getSignature().getInputPortInfo(portName).isRequired()
                         ? "red" : "blue";  // red for unconnected, required ports
                     dotFile.write("  " +
diff --git a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/MffContext.java b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/MffContext.java
index b7212f9..8fd44d2 100644
--- a/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/MffContext.java
+++ b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/MffContext.java
@@ -16,15 +16,12 @@
 
 package androidx.media.filterfw;
 
-import android.annotation.TargetApi;
 import android.app.Activity;
 import android.app.ActivityManager;
 import android.content.Context;
 import android.content.pm.ConfigurationInfo;
-import android.os.Build;
 import android.os.Handler;
 import android.os.Looper;
-import android.renderscript.RenderScript;
 import android.util.Log;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
@@ -66,9 +63,9 @@
 
         /**
          * On older Android versions the Camera may need a SurfaceView to render into in order to
-         * function. You may specify a dummy SurfaceView here if you do not want the context to
+         * function. You may specify a placeholder SurfaceView here if you do not want the context to
          * create its own view. Note, that your view may or may not be used. You cannot rely on
-         * your dummy view to be used by the Camera. If you pass null, no dummy view will be used.
+         * your placeholder view to be used by the Camera. If you pass null, no placeholder view will be used.
          * In this case your application may not run correctly on older devices if you use the
          * camera. This flag has no effect if you do not require the camera.
          */
@@ -104,7 +101,7 @@
     /** The current context state. */
     private State mState = new State();
 
-    /** A dummy SurfaceView that is required for Camera operation on older devices. */
+    /** A placeholder SurfaceView that is required for Camera operation on older devices. */
     private SurfaceView mDummySurfaceView = null;
 
     /** Handler to execute code in the context's thread, such as issuing callbacks. */
@@ -116,9 +113,6 @@
     /** Flag whether camera streaming is supported in this context. */
     private boolean mCameraStreamingSupport;
 
-    /** RenderScript base master class. */
-    private RenderScript mRenderScript;
-
     /**
      * Creates a new MffContext with the default configuration.
      *
@@ -126,7 +120,7 @@
      * multiple MffContexts, however data between them cannot be shared. The context must be
      * created in a thread with a Looper (such as the main/UI thread).
      *
-     * On older versions of Android, the MffContext may create a visible dummy view for the
+     * On older versions of Android, the MffContext may create a visible placeholder view for the
      * camera to render into. This is a 1x1 SurfaceView that is placed into the top-left corner.
      *
      * @param context The application context to attach the MffContext to.
@@ -142,7 +136,7 @@
      * multiple MffContexts, however data between them cannot be shared. The context must be
      * created in a thread with a Looper (such as the main/UI thread).
      *
-     * On older versions of Android, the MffContext may create a visible dummy view for the
+     * On older versions of Android, the MffContext may create a visible placeholder view for the
      * camera to render into. This is a 1x1 SurfaceView that is placed into the top-left corner.
      * You may alternatively specify your own SurfaceView in the configuration.
      *
@@ -200,9 +194,7 @@
                     mCameraStreamer.stop();
                     mCameraStreamer.tearDown();
                 }
-                if (Build.VERSION.SDK_INT >= 11) {
-                    maybeDestroyRenderScript();
-                }
+
                 stopRunners(false);
                 waitUntilStopped();
                 tearDown();
@@ -301,14 +293,6 @@
         return mCameraStreamingSupport;
     }
 
-    @TargetApi(11)
-    public final RenderScript getRenderScript() {
-        if (mRenderScript == null) {
-            mRenderScript = RenderScript.create(mApplicationContext);
-        }
-        return mRenderScript;
-    }
-
     final void assertOpenGLSupported() {
         if (!isOpenGLSupported()) {
             throw new RuntimeException("Attempting to use OpenGL ES 2 in a context that does not "
@@ -459,12 +443,4 @@
         return (context instanceof Activity) ? (Activity) context : null;
     }
 
-    @TargetApi(11)
-    private void maybeDestroyRenderScript() {
-        if (mRenderScript != null) {
-            mRenderScript.destroy();
-            mRenderScript = null;
-        }
-    }
-
 }
diff --git a/tests/DynamicCodeLoggerIntegrationTests/src/com/android/dcl/Simple.java b/tests/DynamicCodeLoggerIntegrationTests/src/com/android/dcl/Simple.java
index e995a26..2ca91fb 100644
--- a/tests/DynamicCodeLoggerIntegrationTests/src/com/android/dcl/Simple.java
+++ b/tests/DynamicCodeLoggerIntegrationTests/src/com/android/dcl/Simple.java
@@ -16,7 +16,7 @@
 
 package com.android.dcl;
 
-/** Dummy class which is built into a jar purely so we can pass it to DexClassLoader. */
+/** Placeholder class which is built into a jar purely so we can pass it to DexClassLoader. */
 public final class Simple {
     public Simple() {}
 }
diff --git a/tests/Input/OWNERS b/tests/Input/OWNERS
index d701f23..3cffce9 100644
--- a/tests/Input/OWNERS
+++ b/tests/Input/OWNERS
@@ -1 +1,2 @@
+# Bug component: 136048
 include /core/java/android/hardware/input/OWNERS
diff --git a/tests/Input/src/com/android/test/input/AnrTest.kt b/tests/Input/src/com/android/test/input/AnrTest.kt
index 8025406..1355fd2 100644
--- a/tests/Input/src/com/android/test/input/AnrTest.kt
+++ b/tests/Input/src/com/android/test/input/AnrTest.kt
@@ -134,7 +134,7 @@
     private fun getExitReasons(): List<ApplicationExitInfo> {
         lateinit var infos: List<ApplicationExitInfo>
         instrumentation.runOnMainSync {
-            val am = instrumentation.getContext().getSystemService(ActivityManager::class.java)
+            val am = instrumentation.getContext().getSystemService(ActivityManager::class.java)!!
             infos = am.getHistoricalProcessExitReasons(PACKAGE_NAME, ALL_PIDS, NO_MAX)
         }
         return infos
diff --git a/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt b/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt
index d83a457..29d5c77 100644
--- a/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt
+++ b/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt
@@ -47,6 +47,6 @@
         super.onCreate(savedInstanceState)
         mInputMonitor = InputManager.getInstance().monitorGestureInput(MONITOR_NAME, displayId)
         mInputEventReceiver = UnresponsiveReceiver(
-                mInputMonitor.getInputChannel(), Looper.myLooper())
+                mInputMonitor.getInputChannel(), Looper.myLooper()!!)
     }
 }
diff --git a/tests/Internal/src/stub/DummyWallpaperService.java b/tests/Internal/src/stub/DummyWallpaperService.java
index 084c036..db1b780 100644
--- a/tests/Internal/src/stub/DummyWallpaperService.java
+++ b/tests/Internal/src/stub/DummyWallpaperService.java
@@ -19,7 +19,7 @@
 import android.service.wallpaper.WallpaperService;
 
 /**
- * Dummy wallpaper service only for test purposes, won't draw anything.
+ * Placeholder wallpaper service only for test purposes, won't draw anything.
  */
 public class DummyWallpaperService extends WallpaperService {
     @Override
diff --git a/tests/NetworkSecurityConfigTest/res/raw/ca_certs_der.der b/tests/NetworkSecurityConfigTest/res/raw/ca_certs_der.der
index 235bd47..fd888ec 100644
--- a/tests/NetworkSecurityConfigTest/res/raw/ca_certs_der.der
+++ b/tests/NetworkSecurityConfigTest/res/raw/ca_certs_der.der
Binary files differ
diff --git a/tests/NetworkSecurityConfigTest/res/raw/ca_certs_pem.pem b/tests/NetworkSecurityConfigTest/res/raw/ca_certs_pem.pem
index 413e3c0..66f7bfd 100644
--- a/tests/NetworkSecurityConfigTest/res/raw/ca_certs_pem.pem
+++ b/tests/NetworkSecurityConfigTest/res/raw/ca_certs_pem.pem
@@ -1,35 +1,31 @@
 -----BEGIN CERTIFICATE-----
-MIIDfTCCAuagAwIBAgIDErvmMA0GCSqGSIb3DQEBBQUAME4xCzAJBgNVBAYTAlVT
-MRAwDgYDVQQKEwdFcXVpZmF4MS0wKwYDVQQLEyRFcXVpZmF4IFNlY3VyZSBDZXJ0
-aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDIwNTIxMDQwMDAwWhcNMTgwODIxMDQwMDAw
-WjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UE
-AxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
-CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9m
-OSm9BXiLnTjoBbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIu
-T8rxh0PBFpVXLVDviS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6c
-JmTM386DGXHKTubU1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmR
-Cw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5asz
-PeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo4HwMIHtMB8GA1UdIwQYMBaAFEjm
-aPkr0rKV10fYIyAQTzOYkJ/UMB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrM
-TjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjA6BgNVHR8EMzAxMC+g
-LaArhilodHRwOi8vY3JsLmdlb3RydXN0LmNvbS9jcmxzL3NlY3VyZWNhLmNybDBO
-BgNVHSAERzBFMEMGBFUdIAAwOzA5BggrBgEFBQcCARYtaHR0cHM6Ly93d3cuZ2Vv
-dHJ1c3QuY29tL3Jlc291cmNlcy9yZXBvc2l0b3J5MA0GCSqGSIb3DQEBBQUAA4GB
-AHbhEm5OSxYShjAGsoEIz/AIx8dxfmbuwu3UOx//8PDITtZDOLC5MH0Y0FWDomrL
-NhGc6Ehmo21/uBPUR/6LWlxz/K7ZGzIZOKuXNBSqltLroxwUCEm2u+WR74M26x1W
-b8ravHNjkOR/ez4iyz0H7V84dJzjA1BOoa+Y7mHyhD8S
------END CERTIFICATE-----
------BEGIN CERTIFICATE-----
-MIICPDCCAaUCEDyRMcsf9tAbDpq40ES/Er4wDQYJKoZIhvcNAQEFBQAwXzELMAkG
-A1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFz
-cyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2
-MDEyOTAwMDAwMFoXDTI4MDgwMjIzNTk1OVowXzELMAkGA1UEBhMCVVMxFzAVBgNV
-BAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmlt
-YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUAA4GN
-ADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhE
-BarsAx94f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/is
-I19wKTakyYbnsZogy1Olhec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0G
-CSqGSIb3DQEBBQUAA4GBABByUqkFFBkyCEHwxWsKzH4PIRnN5GfcX6kb5sroc50i
-2JhucwNhkcV8sEVAbkSdjbCxlnRhLQ2pRdKkkirWmnWXbj9T/UWZYB2oK0z5XqcJ
-2HUw19JlYD1n1khVdWk/kfVIC0dpImmClr7JyDiGSnoscxlIaU5rfGW/D/xwzoiQ
+MIIFYjCCBEqgAwIBAgIQd70NbNs2+RrqIQ/E8FjTDTANBgkqhkiG9w0BAQsFADBX
+MQswCQYDVQQGEwJCRTEZMBcGA1UEChMQR2xvYmFsU2lnbiBudi1zYTEQMA4GA1UE
+CxMHUm9vdCBDQTEbMBkGA1UEAxMSR2xvYmFsU2lnbiBSb290IENBMB4XDTIwMDYx
+OTAwMDA0MloXDTI4MDEyODAwMDA0MlowRzELMAkGA1UEBhMCVVMxIjAgBgNVBAoT
+GUdvb2dsZSBUcnVzdCBTZXJ2aWNlcyBMTEMxFDASBgNVBAMTC0dUUyBSb290IFIx
+MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAthECix7joXebO9y/lD63
+ladAPKH9gvl9MgaCcfb2jH/76Nu8ai6Xl6OMS/kr9rH5zoQdsfnFl97vufKj6bwS
+iV6nqlKr+CMny6SxnGPb15l+8Ape62im9MZaRw1NEDPjTrETo8gYbEvs/AmQ351k
+KSUjB6G00j0uYODP0gmHu81I8E3CwnqIiru6z1kZ1q+PsAewnjHxgsHA3y6mbWwZ
+DrXYfiYaRQM9sHmklCitD38m5agI/pboPGiUU+6DOogrFZYJsuB6jC511pzrp1Zk
+j5ZPaK49l8KEj8C8QMALXL32h7M1bKwYUH+E4EzNktMg6TO8UpmvMrUpsyUqtEj5
+cuHKZPfmghCN6J3Cioj6OGaK/GP5Afl4/Xtcd/p2h/rs37EOeZVXtL0m79YB0esW
+CruOC7XFxYpVq9Os6pFLKcwZpDIlTirxZUTQAs6qzkm06p98g7BAe+dDq6dso499
+iYH6TKX/1Y7DzkvgtdizjkXPdsDtQCv9Uw+wp9U7DbGKogPeMa3Md+pvez7W35Ei
+Eua++tgy/BBjFFFy3l3WFpO9KWgz7zpm7AeKJt8T11dleCfeXkkUAKIAf5qoIbap
+sZWwpbkNFhHax2xIPEDgfg1azVY80ZcFuctL7TlLnMQ/0lUTbiSw1nH69MG6zO0b
+9f6BQdgAmD06yK56mDcYBZUCAwEAAaOCATgwggE0MA4GA1UdDwEB/wQEAwIBhjAP
+BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTkrysmcRorSCeFL1JmLO/wiRNxPjAf
+BgNVHSMEGDAWgBRge2YaRQ2XyolQL30EzTSo//z9SzBgBggrBgEFBQcBAQRUMFIw
+JQYIKwYBBQUHMAGGGWh0dHA6Ly9vY3NwLnBraS5nb29nL2dzcjEwKQYIKwYBBQUH
+MAKGHWh0dHA6Ly9wa2kuZ29vZy9nc3IxL2dzcjEuY3J0MDIGA1UdHwQrMCkwJ6Al
+oCOGIWh0dHA6Ly9jcmwucGtpLmdvb2cvZ3NyMS9nc3IxLmNybDA7BgNVHSAENDAy
+MAgGBmeBDAECATAIBgZngQwBAgIwDQYLKwYBBAHWeQIFAwIwDQYLKwYBBAHWeQIF
+AwMwDQYJKoZIhvcNAQELBQADggEBADSkHrEoo9C0dhemMXoh6dFSPsjbdBZBiLg9
+NR3t5P+T4Vxfq7vqfM/b5A3Ri1fyJm9bvhdGaJQ3b2t6yMAYN/olUazsaL+yyEn9
+WprKASOshIArAoyZl+tJaox118fessmXn1hIVw41oeQa1v1vg4Fv74zPl6/AhSrw
+9U5pCZEt4Wi4wStz6dTZ/CLANx8LZh1J7QJVj2fhMtfTJr9w4z30Z209fOU0iOMy
++qduBmpvvYuR7hZL6Dupszfnw0Skfths18dG9ZKb59UhvmaSGZRVbNQpsg3BZlvi
+d0lIKO2d1xozclOzgjXPYovJJIultzkMu34qQb9Sz/yilrbCgj8=
 -----END CERTIFICATE-----
diff --git a/tests/NetworkSecurityConfigTest/res/xml/domain_whitespace.xml b/tests/NetworkSecurityConfigTest/res/xml/domain_whitespace.xml
index 5d23d36e..99106ad 100644
--- a/tests/NetworkSecurityConfigTest/res/xml/domain_whitespace.xml
+++ b/tests/NetworkSecurityConfigTest/res/xml/domain_whitespace.xml
@@ -5,7 +5,7 @@
     </domain>
     <domain>   developer.android.com    </domain>
     <pin-set>
-      <pin digest="SHA-256">  7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=  </pin>
+      <pin digest="SHA-256">  zCTnfLwLKbS9S2sbp+uFz4KZOocFvXxkV06Ce9O5M2w=  </pin>
     </pin-set>
   </domain-config>
 </network-security-config>
diff --git a/tests/NetworkSecurityConfigTest/res/xml/nested_domains.xml b/tests/NetworkSecurityConfigTest/res/xml/nested_domains.xml
index d45fd77..232f88f 100644
--- a/tests/NetworkSecurityConfigTest/res/xml/nested_domains.xml
+++ b/tests/NetworkSecurityConfigTest/res/xml/nested_domains.xml
@@ -9,7 +9,7 @@
       <domain-config>
           <domain>developer.android.com</domain>
           <pin-set>
-              <pin digest="SHA-256">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin>
+              <pin digest="SHA-256">zCTnfLwLKbS9S2sbp+uFz4KZOocFvXxkV06Ce9O5M2w=</pin>
           </pin-set>
       </domain-config>
     </domain-config>
diff --git a/tests/NetworkSecurityConfigTest/res/xml/pins1.xml b/tests/NetworkSecurityConfigTest/res/xml/pins1.xml
index 1773d280..7cc81b0 100644
--- a/tests/NetworkSecurityConfigTest/res/xml/pins1.xml
+++ b/tests/NetworkSecurityConfigTest/res/xml/pins1.xml
@@ -3,7 +3,7 @@
   <domain-config>
     <domain>android.com</domain>
     <pin-set>
-      <pin digest="SHA-256">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin>
+      <pin digest="SHA-256">zCTnfLwLKbS9S2sbp+uFz4KZOocFvXxkV06Ce9O5M2w=</pin>
     </pin-set>
   </domain-config>
 </network-security-config>
diff --git a/tests/NetworkSecurityConfigTest/src/android/security/net/config/NetworkSecurityConfigTests.java b/tests/NetworkSecurityConfigTest/src/android/security/net/config/NetworkSecurityConfigTests.java
index 047be16..0494f17 100644
--- a/tests/NetworkSecurityConfigTest/src/android/security/net/config/NetworkSecurityConfigTests.java
+++ b/tests/NetworkSecurityConfigTest/src/android/security/net/config/NetworkSecurityConfigTests.java
@@ -22,23 +22,17 @@
 import android.test.ActivityUnitTestCase;
 import android.util.ArraySet;
 import android.util.Pair;
+
+import com.android.org.conscrypt.TrustedCertificateStore;
+
 import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.net.Socket;
-import java.net.URL;
 import java.security.cert.Certificate;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Collections;
 import java.util.HashSet;
 import java.util.Set;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.TrustManager;
 
-import com.android.org.conscrypt.TrustedCertificateStore;
+import javax.net.ssl.SSLContext;
 
 public class NetworkSecurityConfigTests extends ActivityUnitTestCase<Activity> {
 
@@ -46,9 +40,9 @@
         super(Activity.class);
     }
 
-    // SHA-256 of the G2 intermediate CA for android.com (as of 10/2015).
-    private static final byte[] G2_SPKI_SHA256
-            = hexToBytes("ec722969cb64200ab6638f68ac538e40abab5b19a6485661042a1061c4612776");
+    // SHA-256 of the GTS intermediate CA (CN = GTS CA 1C3) for android.com (as of 09/2023).
+    private static final byte[] GTS_INTERMEDIATE_SPKI_SHA256 =
+        hexToBytes("cc24e77cbc0b29b4bd4b6b1ba7eb85cf82993a8705bd7c64574e827bd3b9336c");
 
     private static final byte[] TEST_CA_BYTES
             = hexToBytes(
@@ -161,7 +155,7 @@
 
     public void testGoodPin() throws Exception {
         ArraySet<Pin> pins = new ArraySet<Pin>();
-        pins.add(new Pin("SHA-256", G2_SPKI_SHA256));
+        pins.add(new Pin("SHA-256", GTS_INTERMEDIATE_SPKI_SHA256));
         NetworkSecurityConfig domain = new NetworkSecurityConfig.Builder()
                 .setPinSet(new PinSet(pins, Long.MAX_VALUE))
                 .addCertificatesEntryRef(
@@ -247,7 +241,7 @@
 
     public void testWithUrlConnection() throws Exception {
         ArraySet<Pin> pins = new ArraySet<Pin>();
-        pins.add(new Pin("SHA-256", G2_SPKI_SHA256));
+        pins.add(new Pin("SHA-256", GTS_INTERMEDIATE_SPKI_SHA256));
         NetworkSecurityConfig domain = new NetworkSecurityConfig.Builder()
                 .setPinSet(new PinSet(pins, Long.MAX_VALUE))
                 .addCertificatesEntryRef(
@@ -304,7 +298,7 @@
         } finally {
             // Delete the user added CA. We don't know the alias so just delete them all.
             for (String alias : store.aliases()) {
-                if (store.isUser(alias)) {
+                if (TrustedCertificateStore.isUser(alias)) {
                     try {
                         store.deleteCertificateEntry(alias);
                     } catch (Exception ignored) {
diff --git a/tests/NetworkSecurityConfigTest/src/android/security/net/config/TestUtils.java b/tests/NetworkSecurityConfigTest/src/android/security/net/config/TestUtils.java
index 9dec21b..39b5cb4c 100644
--- a/tests/NetworkSecurityConfigTest/src/android/security/net/config/TestUtils.java
+++ b/tests/NetworkSecurityConfigTest/src/android/security/net/config/TestUtils.java
@@ -16,19 +16,20 @@
 
 package android.security.net.config;
 
+import static org.junit.Assert.fail;
+
 import android.content.pm.ApplicationInfo;
 import android.os.Build;
-import java.net.Socket;
+
 import java.net.URL;
+
 import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.TrustManager;
+import javax.net.ssl.SSLSocket;
 import javax.net.ssl.TrustManagerFactory;
 
-import junit.framework.Assert;
-
-public final class TestUtils extends Assert {
+public final class TestUtils {
 
     private TestUtils() {
     }
@@ -36,8 +37,8 @@
     public static void assertConnectionFails(SSLContext context, String host, int port)
             throws Exception {
         try {
-            Socket s = context.getSocketFactory().createSocket(host, port);
-            s.getInputStream();
+            SSLSocket s = (SSLSocket) context.getSocketFactory().createSocket(host, port);
+            s.startHandshake();
             fail("Expected connection to " + host + ":" + port + " to fail.");
         } catch (SSLHandshakeException expected) {
         }
@@ -45,7 +46,8 @@
 
     public static void assertConnectionSucceeds(SSLContext context, String host, int port)
             throws Exception {
-        Socket s = context.getSocketFactory().createSocket(host, port);
+        SSLSocket s = (SSLSocket) context.getSocketFactory().createSocket(host, port);
+        s.startHandshake();
         s.getInputStream();
     }
 
diff --git a/tests/NetworkSecurityConfigTest/src/android/security/net/config/XmlConfigTests.java b/tests/NetworkSecurityConfigTest/src/android/security/net/config/XmlConfigTests.java
index 4b7a014..81e05c1 100644
--- a/tests/NetworkSecurityConfigTest/src/android/security/net/config/XmlConfigTests.java
+++ b/tests/NetworkSecurityConfigTest/src/android/security/net/config/XmlConfigTests.java
@@ -16,26 +16,18 @@
 
 package android.security.net.config;
 
-import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
-import android.util.ArraySet;
-import android.util.Pair;
+
 import java.io.IOException;
 import java.net.InetAddress;
-import java.net.Socket;
-import java.net.URL;
 import java.security.KeyStore;
 import java.security.Provider;
-import java.security.Security;
 import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Collections;
 import java.util.Set;
-import javax.net.ssl.HttpsURLConnection;
+
 import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLHandshakeException;
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.TrustManagerFactory;
@@ -52,7 +44,7 @@
         NetworkSecurityConfig config = appConfig.getConfigForHostname("");
         assertNotNull(config);
         // Check defaults.
-        assertTrue(config.isCleartextTrafficPermitted());
+        assertFalse(config.isCleartextTrafficPermitted());
         assertFalse(config.isHstsEnforced());
         assertFalse(config.getTrustAnchors().isEmpty());
         PinSet pinSet = config.getPins();
@@ -72,7 +64,7 @@
         NetworkSecurityConfig config = appConfig.getConfigForHostname("");
         assertNotNull(config);
         // Check defaults.
-        assertTrue(config.isCleartextTrafficPermitted());
+        assertFalse(config.isCleartextTrafficPermitted());
         assertFalse(config.isHstsEnforced());
         assertTrue(config.getTrustAnchors().isEmpty());
         PinSet pinSet = config.getPins();
@@ -91,14 +83,14 @@
         NetworkSecurityConfig config = appConfig.getConfigForHostname("");
         assertNotNull(config);
         // Check defaults.
-        assertTrue(config.isCleartextTrafficPermitted());
+        assertFalse(config.isCleartextTrafficPermitted());
         assertFalse(config.isHstsEnforced());
         assertTrue(config.getTrustAnchors().isEmpty());
         PinSet pinSet = config.getPins();
         assertTrue(pinSet.pins.isEmpty());
         // Check android.com.
         config = appConfig.getConfigForHostname("android.com");
-        assertTrue(config.isCleartextTrafficPermitted());
+        assertFalse(config.isCleartextTrafficPermitted());
         assertFalse(config.isHstsEnforced());
         assertFalse(config.getTrustAnchors().isEmpty());
         pinSet = config.getPins();
@@ -188,7 +180,7 @@
         ApplicationConfig appConfig = new ApplicationConfig(source);
         assertTrue(appConfig.hasPerDomainConfigs());
         NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
-        assertTrue(config.isCleartextTrafficPermitted());
+        assertFalse(config.isCleartextTrafficPermitted());
         assertFalse(config.isHstsEnforced());
         assertFalse(config.getTrustAnchors().isEmpty());
         PinSet pinSet = config.getPins();
@@ -250,9 +242,9 @@
         ApplicationConfig appConfig = new ApplicationConfig(source);
         // Check android.com.
         NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
-        assertTrue(config.isCleartextTrafficPermitted());
+        assertFalse(config.isCleartextTrafficPermitted());
         assertFalse(config.isHstsEnforced());
-        assertEquals(2, config.getTrustAnchors().size());
+        assertEquals(1, config.getTrustAnchors().size());
         // Try connections.
         SSLContext context = TestUtils.getSSLContext(source);
         TestUtils.assertConnectionSucceeds(context, "android.com", 443);
@@ -267,9 +259,9 @@
         ApplicationConfig appConfig = new ApplicationConfig(source);
         // Check android.com.
         NetworkSecurityConfig config = appConfig.getConfigForHostname("android.com");
-        assertTrue(config.isCleartextTrafficPermitted());
+        assertFalse(config.isCleartextTrafficPermitted());
         assertFalse(config.isHstsEnforced());
-        assertEquals(2, config.getTrustAnchors().size());
+        assertEquals(1, config.getTrustAnchors().size());
         // Try connections.
         SSLContext context = TestUtils.getSSLContext(source);
         TestUtils.assertConnectionSucceeds(context, "android.com", 443);
diff --git a/tests/PlatformCompatGating/src/com/android/compat/testing/DummyApi.java b/tests/PlatformCompatGating/src/com/android/compat/testing/DummyApi.java
index 731be8e..a77950f 100644
--- a/tests/PlatformCompatGating/src/com/android/compat/testing/DummyApi.java
+++ b/tests/PlatformCompatGating/src/com/android/compat/testing/DummyApi.java
@@ -24,7 +24,7 @@
 import com.android.internal.compat.IPlatformCompat;
 
 /**
- * This is a dummy API to test gating
+ * This is a placeholder API to test gating
  *
  * @hide
  */
@@ -36,7 +36,7 @@
     public static final long CHANGE_SYSTEM_SERVER = 666016;
 
     /**
-     * Dummy method
+     * Placeholder method
      * @return "A" if change is enabled, "B" otherwise.
      */
     public static String dummyFunc() {
@@ -47,7 +47,7 @@
     }
 
     /**
-     * Dummy combined method
+     * Placeholder combined method
      * @return "0" if {@link CHANGE_ID_1} is disabled and {@link CHANGE_ID_2} is disabled,
                "1" if {@link CHANGE_ID_1} is disabled and {@link CHANGE_ID_2} is enabled,
                "2" if {@link CHANGE_ID_1} is enabled and {@link CHANGE_ID_2} is disabled,
@@ -68,7 +68,7 @@
     }
 
     /**
-     * Dummy api using system server API.
+     * Placeholder api using system server API.
      */
     public static boolean dummySystemServer(Context context) {
         IPlatformCompat platformCompat = IPlatformCompat.Stub
diff --git a/tests/SilkFX/src/com/android/test/silkfx/materials/BackgroundBlurActivity.kt b/tests/SilkFX/src/com/android/test/silkfx/materials/BackgroundBlurActivity.kt
index 9d17d38..4d38660 100644
--- a/tests/SilkFX/src/com/android/test/silkfx/materials/BackgroundBlurActivity.kt
+++ b/tests/SilkFX/src/com/android/test/silkfx/materials/BackgroundBlurActivity.kt
@@ -132,7 +132,7 @@
         mBlurForceDisabled = disabled
         Settings.Global.putInt(getContentResolver(), Settings.Global.DISABLE_WINDOW_BLURS,
                 if (mBlurForceDisabled) 1 else 0)
-        (findViewById(R.id.toggle_blur_enabled) as Button)
+        (requireViewById(R.id.toggle_blur_enabled) as Button)
                 .setText(if (mBlurForceDisabled) "Enable blurs" else "Disable blurs")
     }
 
@@ -142,13 +142,13 @@
 
     fun setBackgroundBlur(radius: Int) {
         mBackgroundBlurRadius = radius
-        (findViewById(R.id.background_blur_radius) as TextView).setText(radius.toString())
+        (requireViewById(R.id.background_blur_radius) as TextView).setText(radius.toString())
         window.setBackgroundBlurRadius(mBackgroundBlurRadius)
     }
 
     fun setBlurBehind(radius: Int) {
         mBlurBehindRadius = radius
-        (findViewById(R.id.blur_behind_radius) as TextView).setText(radius.toString())
+        (requireViewById(R.id.blur_behind_radius) as TextView).setText(radius.toString())
         window.getAttributes().setBlurBehindRadius(mBlurBehindRadius)
         window.setAttributes(window.getAttributes())
     }
@@ -159,7 +159,7 @@
         } else {
             mDimAmountNoBlur = amount
         }
-        (findViewById(R.id.dim_amount) as TextView).setText("%.2f".format(amount))
+        (requireViewById(R.id.dim_amount) as TextView).setText("%.2f".format(amount))
         window.getAttributes().dimAmount = amount
         window.setAttributes(window.getAttributes())
     }
@@ -168,7 +168,7 @@
         mBatterySavingModeOn = on
         Settings.Global.putInt(getContentResolver(),
             Settings.Global.LOW_POWER_MODE, if (on) 1 else 0)
-        (findViewById(R.id.toggle_battery_saving_mode) as Button).setText(
+        (requireViewById(R.id.toggle_battery_saving_mode) as Button).setText(
             if (on) "Exit low power mode" else "Enter low power mode")
     }
 
@@ -182,7 +182,7 @@
         } else {
             mAlphaNoBlur = alpha
         }
-        (findViewById(R.id.background_alpha) as TextView).setText("%.2f".format(alpha))
+        (requireViewById(R.id.background_alpha) as TextView).setText("%.2f".format(alpha))
         mBackgroundDrawable.setAlpha((alpha * 255f).toInt())
         getWindowManager().updateViewLayout(window.getDecorView(), window.getAttributes())
     }
diff --git a/tests/SoundTriggerTestApp/src/com/android/test/soundtrigger/SoundTriggerTestService.java b/tests/SoundTriggerTestApp/src/com/android/test/soundtrigger/SoundTriggerTestService.java
index 6d4ffcf..f9e9205 100644
--- a/tests/SoundTriggerTestApp/src/com/android/test/soundtrigger/SoundTriggerTestService.java
+++ b/tests/SoundTriggerTestApp/src/com/android/test/soundtrigger/SoundTriggerTestService.java
@@ -469,7 +469,7 @@
             }
         }
 
-        // Create a few dummy models if we didn't load anything.
+        // Create a few placeholder models if we didn't load anything.
         if (!loadedModel) {
             Properties dummyModelProperties = new Properties();
             for (String name : new String[]{"1", "2", "3"}) {
diff --git a/tests/StagedInstallTest/OWNERS b/tests/StagedInstallTest/OWNERS
index aac68e9..d7301dc 100644
--- a/tests/StagedInstallTest/OWNERS
+++ b/tests/StagedInstallTest/OWNERS
@@ -1,3 +1,5 @@
+# Bug component: 36137
+
 include /services/core/java/com/android/server/pm/OWNERS
 
 dariofreni@google.com
diff --git a/tests/TrustTests/Android.bp b/tests/TrustTests/Android.bp
index a1b888a..c216bce 100644
--- a/tests/TrustTests/Android.bp
+++ b/tests/TrustTests/Android.bp
@@ -25,6 +25,7 @@
         "androidx.test.rules",
         "androidx.test.ext.junit",
         "androidx.test.uiautomator_uiautomator",
+        "flag-junit",
         "mockito-target-minus-junit4",
         "servicestests-utils",
         "truth-prebuilt",
diff --git a/tests/TrustTests/src/android/trust/test/GrantAndRevokeTrustTest.kt b/tests/TrustTests/src/android/trust/test/GrantAndRevokeTrustTest.kt
index f864fed..1dfd5c0 100644
--- a/tests/TrustTests/src/android/trust/test/GrantAndRevokeTrustTest.kt
+++ b/tests/TrustTests/src/android/trust/test/GrantAndRevokeTrustTest.kt
@@ -16,6 +16,10 @@
 
 package android.trust.test
 
+import android.content.pm.PackageManager
+import android.platform.test.annotations.RequiresFlagsDisabled
+import android.platform.test.annotations.RequiresFlagsEnabled
+import android.platform.test.flag.junit.DeviceFlagsValueProvider
 import android.service.trust.GrantTrustResult
 import android.trust.BaseTrustAgentService
 import android.trust.TrustTestActivity
@@ -27,6 +31,7 @@
 import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
 import androidx.test.uiautomator.UiDevice
 import com.android.server.testutils.mock
+import org.junit.Assume.assumeFalse
 import org.junit.Before
 import org.junit.Rule
 import org.junit.Test
@@ -45,6 +50,7 @@
     private val activityScenarioRule = ActivityScenarioRule(TrustTestActivity::class.java)
     private val lockStateTrackingRule = LockStateTrackingRule()
     private val trustAgentRule = TrustAgentRule<GrantAndRevokeTrustAgent>()
+    private val packageManager = getInstrumentation().getTargetContext().getPackageManager()
 
     @get:Rule
     val rule: RuleChain = RuleChain
@@ -52,6 +58,7 @@
         .around(ScreenLockRule())
         .around(lockStateTrackingRule)
         .around(trustAgentRule)
+        .around(DeviceFlagsValueProvider.createCheckFlagsRule())
 
     @Before
     fun manageTrust() {
@@ -72,7 +79,7 @@
         trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 10000, 0) {}
         uiDevice.sleep()
 
-        lockStateTrackingRule.assertUnlocked()
+        lockStateTrackingRule.assertUnlockedAndTrusted()
     }
 
     @Test
@@ -86,6 +93,51 @@
     }
 
     @Test
+    @RequiresFlagsEnabled(android.security.Flags.FLAG_FIX_UNLOCKED_DEVICE_REQUIRED_KEYS)
+    fun grantCannotActivelyUnlockDevice() {
+        // On automotive, trust agents can actively unlock the device.
+        assumeFalse(packageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE))
+
+        // Lock the device.
+        uiDevice.sleep()
+        lockStateTrackingRule.assertLocked()
+
+        // Grant trust.
+        trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 10000, 0) {}
+
+        // The grant should not have unlocked the device.  Wait a bit so that
+        // TrustManagerService probably will have finished processing the grant.
+        await()
+        lockStateTrackingRule.assertLocked()
+
+        // Turn the screen on and off to cause TrustManagerService to refresh
+        // its deviceLocked state.  Then verify the state is still locked.  This
+        // part failed before the fix for b/296464083.
+        uiDevice.wakeUp()
+        uiDevice.sleep()
+        await()
+        lockStateTrackingRule.assertLocked()
+    }
+
+    @Test
+    @RequiresFlagsDisabled(android.security.Flags.FLAG_FIX_UNLOCKED_DEVICE_REQUIRED_KEYS)
+    fun grantCouldCauseWrongDeviceLockedStateDueToBug() {
+        // On automotive, trust agents can actively unlock the device.
+        assumeFalse(packageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE))
+
+        // Verify that b/296464083 exists.  That is, when the device is locked
+        // and a trust agent grants trust, the deviceLocked state incorrectly
+        // becomes false even though the device correctly remains locked.
+        uiDevice.sleep()
+        lockStateTrackingRule.assertLocked()
+        trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 10000, 0) {}
+        uiDevice.wakeUp()
+        uiDevice.sleep()
+        await()
+        lockStateTrackingRule.assertUnlockedButNotReally()
+    }
+
+    @Test
     fun grantDoesNotCallBack() {
         val callback = mock<(GrantTrustResult) -> Unit>()
         trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 0, 0, callback)
diff --git a/tests/TrustTests/src/android/trust/test/TemporaryAndRenewableTrustTest.kt b/tests/TrustTests/src/android/trust/test/TemporaryAndRenewableTrustTest.kt
index ae722477..96362b8 100644
--- a/tests/TrustTests/src/android/trust/test/TemporaryAndRenewableTrustTest.kt
+++ b/tests/TrustTests/src/android/trust/test/TemporaryAndRenewableTrustTest.kt
@@ -102,7 +102,7 @@
         trustAgentRule.agent.grantTrust(
             GRANT_MESSAGE, 0, FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE) {}
 
-        lockStateTrackingRule.assertUnlocked()
+        lockStateTrackingRule.assertUnlockedAndTrusted()
     }
 
     @Test
@@ -125,7 +125,7 @@
             Log.i(TAG, "Callback received; status=${it.status}")
             result = it
         }
-        lockStateTrackingRule.assertUnlocked()
+        lockStateTrackingRule.assertUnlockedAndTrusted()
 
         wait("callback triggered") { result?.status == STATUS_UNLOCKED_BY_GRANT }
     }
diff --git a/tests/TrustTests/src/android/trust/test/lib/LockStateTrackingRule.kt b/tests/TrustTests/src/android/trust/test/lib/LockStateTrackingRule.kt
index 1930a1c..fe47fde 100644
--- a/tests/TrustTests/src/android/trust/test/lib/LockStateTrackingRule.kt
+++ b/tests/TrustTests/src/android/trust/test/lib/LockStateTrackingRule.kt
@@ -16,6 +16,7 @@
 
 package android.trust.test.lib
 
+import android.app.KeyguardManager
 import android.app.trust.TrustManager
 import android.app.trust.TrustManager.TrustListener
 import android.content.Context
@@ -27,18 +28,23 @@
 import org.junit.runners.model.Statement
 
 /**
- * Rule for tracking the lock state of the device based on events emitted to [TrustListener].
+ * Rule for tracking the trusted state of the device based on events emitted to
+ * [TrustListener].  Provides helper methods for verifying that the trusted
+ * state has a particular value and is consistent with (a) the keyguard "locked"
+ * (i.e. showing) value when applicable, and (b) the device locked value that is
+ * tracked by TrustManagerService and is queryable via KeyguardManager.
  */
 class LockStateTrackingRule : TestRule {
     private val context: Context = getApplicationContext()
-    private val windowManager = WindowManagerGlobal.getWindowManagerService()
+    private val windowManager = checkNotNull(WindowManagerGlobal.getWindowManagerService())
+    private val keyguardManager = context.getSystemService(KeyguardManager::class.java) as KeyguardManager
 
-    @Volatile lateinit var lockState: LockState
+    @Volatile lateinit var trustState: TrustState
         private set
 
     override fun apply(base: Statement, description: Description) = object : Statement() {
         override fun evaluate() {
-            lockState = LockState(locked = windowManager.isKeyguardLocked)
+            trustState = TrustState()
             val trustManager = context.getSystemService(TrustManager::class.java) as TrustManager
             val listener = Listener()
 
@@ -52,12 +58,25 @@
     }
 
     fun assertLocked() {
-        wait("un-locked per TrustListener") { lockState.locked == true }
-        wait("keyguard lock") { windowManager.isKeyguardLocked }
+        wait("device locked") { keyguardManager.isDeviceLocked }
+        // isDeviceLocked implies isKeyguardLocked && !trusted.
+        wait("keyguard locked") { windowManager.isKeyguardLocked }
+        wait("not trusted") { trustState.trusted == false }
     }
 
-    fun assertUnlocked() {
-        wait("locked per TrustListener") { lockState.locked == false }
+    // TODO(b/299298338) remove this when removing FLAG_FIX_UNLOCKED_DEVICE_REQUIRED_KEYS
+    fun assertUnlockedButNotReally() {
+        wait("device unlocked") { !keyguardManager.isDeviceLocked }
+        wait("not trusted") { trustState.trusted == false }
+        wait("keyguard locked") { windowManager.isKeyguardLocked }
+    }
+
+    fun assertUnlockedAndTrusted() {
+        wait("device unlocked") { !keyguardManager.isDeviceLocked }
+        wait("trusted") { trustState.trusted == true }
+        // Can't check for !isKeyguardLocked here, since isKeyguardLocked
+        // returns true in the case where the keyguard is dismissible with
+        // swipe, which is considered "device unlocked"!
     }
 
     inner class Listener : TrustListener {
@@ -69,7 +88,7 @@
             trustGrantedMessages: MutableList<String>
         ) {
             Log.d(TAG, "Device became trusted=$enabled")
-            lockState = lockState.copy(locked = !enabled)
+            trustState = trustState.copy(trusted=enabled)
         }
 
         override fun onTrustManagedChanged(enabled: Boolean, userId: Int) {
@@ -77,10 +96,13 @@
 
         override fun onTrustError(message: CharSequence) {
         }
+
+        override fun onEnabledTrustAgentsChanged(userId: Int) {
+        }
     }
 
-    data class LockState(
-        val locked: Boolean? = null
+    data class TrustState(
+        val trusted: Boolean? = null
     )
 
     companion object {
diff --git a/tests/TrustTests/src/android/trust/test/lib/ScreenLockRule.kt b/tests/TrustTests/src/android/trust/test/lib/ScreenLockRule.kt
index 4189baa..f1edca3 100644
--- a/tests/TrustTests/src/android/trust/test/lib/ScreenLockRule.kt
+++ b/tests/TrustTests/src/android/trust/test/lib/ScreenLockRule.kt
@@ -36,7 +36,7 @@
 class ScreenLockRule : TestRule {
     private val context: Context = getApplicationContext()
     private val uiDevice = UiDevice.getInstance(getInstrumentation())
-    private val windowManager = WindowManagerGlobal.getWindowManagerService()
+    private val windowManager = checkNotNull(WindowManagerGlobal.getWindowManagerService())
     private val lockPatternUtils = LockPatternUtils(context)
     private var instantLockSavedValue = false
 
diff --git a/tests/libs-permissions/system_ext/java/com/android/test/libs/system_ext/LibsSystemExtTest.java b/tests/libs-permissions/system_ext/java/com/android/test/libs/system_ext/LibsSystemExtTest.java
index 9999aba..673c73a 100644
--- a/tests/libs-permissions/system_ext/java/com/android/test/libs/system_ext/LibsSystemExtTest.java
+++ b/tests/libs-permissions/system_ext/java/com/android/test/libs/system_ext/LibsSystemExtTest.java
@@ -22,7 +22,7 @@
 public class LibsSystemExtTest {
 
     /**
-     * Dummy method for testing.
+     * Placeholder method for testing.
      */
     public static void test() {
     }
diff --git a/tests/vcn/java/com/android/server/vcn/TelephonySubscriptionTrackerTest.java b/tests/vcn/java/com/android/server/vcn/TelephonySubscriptionTrackerTest.java
index 965b073..34f884b 100644
--- a/tests/vcn/java/com/android/server/vcn/TelephonySubscriptionTrackerTest.java
+++ b/tests/vcn/java/com/android/server/vcn/TelephonySubscriptionTrackerTest.java
@@ -19,9 +19,6 @@
 import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
 import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
 import static android.net.vcn.VcnManager.VCN_RESTRICTED_TRANSPORTS_INT_ARRAY_KEY;
-import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
-import static android.telephony.CarrierConfigManager.EXTRA_SLOT_INDEX;
-import static android.telephony.CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX;
 import static android.telephony.SubscriptionManager.INVALID_SIM_SLOT_INDEX;
 import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
 import static android.telephony.TelephonyCallback.ActiveDataSubscriptionIdListener;
@@ -143,6 +140,8 @@
     @NonNull private TelephonySubscriptionTrackerCallback mCallback;
     @NonNull private TelephonySubscriptionTracker mTelephonySubscriptionTracker;
 
+    @NonNull private CarrierConfigManager.CarrierConfigChangeListener mCarrierConfigChangeListener;
+
     public TelephonySubscriptionTrackerTest() {
         mContext = mock(Context.class);
         mTestLooper = new TestLooper();
@@ -173,7 +172,7 @@
                 .getSystemService(Context.CARRIER_CONFIG_SERVICE);
         doReturn(TEST_CARRIER_CONFIG)
                 .when(mCarrierConfigManager)
-                .getConfigForSubId(eq(TEST_SUBSCRIPTION_ID_1));
+                .getConfigForSubId(eq(TEST_SUBSCRIPTION_ID_1), any());
 
         // subId 1, 2 are in same subGrp, only subId 1 is active
         doReturn(TEST_PARCEL_UUID).when(TEST_SUBINFO_1).getGroupUuid();
@@ -189,9 +188,15 @@
         doReturn(2).when(mTelephonyManager).getActiveModemCount();
 
         mCallback = mock(TelephonySubscriptionTrackerCallback.class);
+        // Capture CarrierConfigChangeListener to emulate the carrier config change notification
+        ArgumentCaptor<CarrierConfigManager.CarrierConfigChangeListener> listenerArgumentCaptor =
+                ArgumentCaptor.forClass(CarrierConfigManager.CarrierConfigChangeListener.class);
         mTelephonySubscriptionTracker =
                 new TelephonySubscriptionTracker(mContext, mHandler, mCallback, mDeps);
         mTelephonySubscriptionTracker.register();
+        verify(mCarrierConfigManager).registerCarrierConfigChangeListener(any(),
+                listenerArgumentCaptor.capture());
+        mCarrierConfigChangeListener = listenerArgumentCaptor.getAllValues().get(0);
 
         doReturn(true).when(mDeps).isConfigForIdentifiedCarrier(any());
         doReturn(Arrays.asList(TEST_SUBINFO_1, TEST_SUBINFO_2))
@@ -239,14 +244,11 @@
         return intent;
     }
 
-    private Intent buildTestBroadcastIntent(boolean hasValidSubscription) {
-        Intent intent = new Intent(ACTION_CARRIER_CONFIG_CHANGED);
-        intent.putExtra(EXTRA_SLOT_INDEX, TEST_SIM_SLOT_INDEX);
-        intent.putExtra(
-                EXTRA_SUBSCRIPTION_INDEX,
-                hasValidSubscription ? TEST_SUBSCRIPTION_ID_1 : INVALID_SUBSCRIPTION_ID);
-
-        return intent;
+    private void sendCarrierConfigChange(boolean hasValidSubscription) {
+        mCarrierConfigChangeListener.onCarrierConfigChanged(
+                TEST_SIM_SLOT_INDEX,
+                hasValidSubscription ? TEST_SUBSCRIPTION_ID_1 : INVALID_SUBSCRIPTION_ID,
+                TelephonyManager.UNKNOWN_CARRIER_ID, TelephonyManager.UNKNOWN_CARRIER_ID);
     }
 
     private TelephonySubscriptionSnapshot buildExpectedSnapshot(
@@ -302,14 +304,15 @@
                         any(),
                         eq(mHandler));
         final IntentFilter filter = getIntentFilter();
-        assertEquals(2, filter.countActions());
-        assertTrue(filter.hasAction(ACTION_CARRIER_CONFIG_CHANGED));
+        assertEquals(1, filter.countActions());
         assertTrue(filter.hasAction(ACTION_MULTI_SIM_CONFIG_CHANGED));
 
         verify(mSubscriptionManager)
                 .addOnSubscriptionsChangedListener(any(HandlerExecutor.class), any());
         assertNotNull(getOnSubscriptionsChangedListener());
 
+        verify(mCarrierConfigManager).registerCarrierConfigChangeListener(any(), any());
+
         verify(mTelephonyManager, times(2))
                 .registerCarrierPrivilegesCallback(anyInt(), any(HandlerExecutor.class), any());
         verify(mTelephonyManager)
@@ -442,7 +445,7 @@
 
     @Test
     public void testReceiveBroadcast_ConfigReadyWithSubscriptions() throws Exception {
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(true));
+        sendCarrierConfigChange(true /* hasValidSubscription */);
         mTestLooper.dispatchAll();
 
         verify(mCallback).onNewSnapshot(eq(buildExpectedSnapshot(TEST_PRIVILEGED_PACKAGES)));
@@ -454,7 +457,7 @@
                 .when(mSubscriptionManager)
                 .getAllSubscriptionInfoList();
 
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(true));
+        sendCarrierConfigChange(true /* hasValidSubscription */);
         mTestLooper.dispatchAll();
 
         // Expect an empty snapshot
@@ -465,7 +468,7 @@
     public void testReceiveBroadcast_SlotCleared() throws Exception {
         setupReadySubIds();
 
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(false));
+        sendCarrierConfigChange(false /* hasValidSubscription */);
         mTestLooper.dispatchAll();
 
         verifyNoActiveSubscriptions();
@@ -476,7 +479,7 @@
     public void testReceiveBroadcast_ConfigNotReady() throws Exception {
         doReturn(false).when(mDeps).isConfigForIdentifiedCarrier(any());
 
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(true));
+        sendCarrierConfigChange(true /* hasValidSubscription */);
         mTestLooper.dispatchAll();
 
         // No interactions expected; config was not loaded
@@ -485,21 +488,21 @@
 
     @Test
     public void testSubscriptionsClearedAfterValidTriggersCallbacks() throws Exception {
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(true));
+        sendCarrierConfigChange(true /* hasValidSubscription */);
         mTestLooper.dispatchAll();
         verify(mCallback).onNewSnapshot(eq(buildExpectedSnapshot(TEST_PRIVILEGED_PACKAGES)));
         assertNotNull(
                 mTelephonySubscriptionTracker.getReadySubIdsBySlotId().get(TEST_SIM_SLOT_INDEX));
 
         doReturn(Collections.emptyList()).when(mSubscriptionManager).getAllSubscriptionInfoList();
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(true));
+        sendCarrierConfigChange(true /* hasValidSubscription */);
         mTestLooper.dispatchAll();
         verify(mCallback).onNewSnapshot(eq(buildExpectedSnapshot(emptyMap(), emptyMap())));
     }
 
     @Test
     public void testCarrierConfigUpdatedAfterValidTriggersCallbacks() throws Exception {
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(true));
+        sendCarrierConfigChange(true /* hasValidSubscription */);
         mTestLooper.dispatchAll();
         verify(mCallback).onNewSnapshot(eq(buildExpectedSnapshot(TEST_PRIVILEGED_PACKAGES)));
         reset(mCallback);
@@ -510,12 +513,12 @@
                 new int[] {TRANSPORT_WIFI, TRANSPORT_CELLULAR});
         doReturn(updatedConfig)
                 .when(mCarrierConfigManager)
-                .getConfigForSubId(eq(TEST_SUBSCRIPTION_ID_1));
+                .getConfigForSubId(eq(TEST_SUBSCRIPTION_ID_1), any());
 
         Map<Integer, PersistableBundleWrapper> subIdToCarrierConfigMap = new HashMap<>();
         subIdToCarrierConfigMap.put(
                 TEST_SUBSCRIPTION_ID_1, new PersistableBundleWrapper(updatedConfig));
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(true));
+        sendCarrierConfigChange(true /* hasValidSubscription */);
         mTestLooper.dispatchAll();
 
         verify(mCallback)
@@ -530,13 +533,13 @@
 
     @Test
     public void testSlotClearedAfterValidTriggersCallbacks() throws Exception {
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(true));
+        sendCarrierConfigChange(true /* hasValidSubscription */);
         mTestLooper.dispatchAll();
         verify(mCallback).onNewSnapshot(eq(buildExpectedSnapshot(TEST_PRIVILEGED_PACKAGES)));
         assertNotNull(
                 mTelephonySubscriptionTracker.getReadySubIdsBySlotId().get(TEST_SIM_SLOT_INDEX));
 
-        mTelephonySubscriptionTracker.onReceive(mContext, buildTestBroadcastIntent(false));
+        sendCarrierConfigChange(false /* hasValidSubscription */);
         mTestLooper.dispatchAll();
         verify(mCallback)
                 .onNewSnapshot(
diff --git a/tools/aapt/AaptAssets.cpp b/tools/aapt/AaptAssets.cpp
index 899d268..82bcfc2 100644
--- a/tools/aapt/AaptAssets.cpp
+++ b/tools/aapt/AaptAssets.cpp
@@ -7,7 +7,9 @@
 #include "AaptUtil.h"
 #include "Main.h"
 #include "ResourceFilter.h"
+#include "Utils.h"
 
+#include <androidfw/PathUtils.h>
 #include <utils/misc.h>
 #include <utils/SortedVector.h>
 
@@ -96,8 +98,8 @@
     char *matchedPattern = NULL;
 
     String8 fullPath(root);
-    fullPath.appendPath(path);
-    FileType type = getFileType(fullPath);
+    appendPath(fullPath, String8(path));
+    FileType type = getFileType(fullPath.c_str());
 
     int plen = strlen(path);
 
@@ -219,7 +221,7 @@
      if (numTags >= 1) {
          const String8& lang = parts[0];
          if (isAlpha(lang) && (lang.length() == 2 || lang.length() == 3)) {
-             setLanguage(lang.string());
+             setLanguage(lang.c_str());
              valid = true;
          }
      }
@@ -232,11 +234,11 @@
      const String8& part2 = parts[1];
      if ((part2.length() == 2 && isAlpha(part2)) ||
          (part2.length() == 3 && isNumber(part2))) {
-         setRegion(part2.string());
+         setRegion(part2.c_str());
      } else if (part2.length() == 4 && isAlpha(part2)) {
-         setScript(part2.string());
+         setScript(part2.c_str());
      } else if (part2.length() >= 4 && part2.length() <= 8) {
-         setVariant(part2.string());
+         setVariant(part2.c_str());
      } else {
          valid = false;
      }
@@ -249,9 +251,9 @@
      const String8& part3 = parts[2];
      if (((part3.length() == 2 && isAlpha(part3)) ||
          (part3.length() == 3 && isNumber(part3))) && script[0]) {
-         setRegion(part3.string());
+         setRegion(part3.c_str());
      } else if (part3.length() >= 4 && part3.length() <= 8) {
-         setVariant(part3.string());
+         setVariant(part3.c_str());
      } else {
          valid = false;
      }
@@ -262,7 +264,7 @@
 
      const String8& part4 = parts[3];
      if (part4.length() >= 4 && part4.length() <= 8) {
-         setVariant(part4.string());
+         setVariant(part4.c_str());
      } else {
          valid = false;
      }
@@ -285,19 +287,19 @@
         Vector<String8> subtags = AaptUtil::splitAndLowerCase(part, '+');
         subtags.removeItemsAt(0);
         if (subtags.size() == 1) {
-            setLanguage(subtags[0]);
+            setLanguage(subtags[0].c_str());
         } else if (subtags.size() == 2) {
-            setLanguage(subtags[0]);
+            setLanguage(subtags[0].c_str());
 
             // The second tag can either be a region, a variant or a script.
             switch (subtags[1].size()) {
                 case 2:
                 case 3:
-                    setRegion(subtags[1]);
+                    setRegion(subtags[1].c_str());
                     break;
                 case 4:
                     if (isAlpha(subtags[1])) {
-                        setScript(subtags[1]);
+                        setScript(subtags[1].c_str());
                         break;
                     }
                     // This is not alphabetical, so we fall through to variant
@@ -306,50 +308,50 @@
                 case 6:
                 case 7:
                 case 8:
-                    setVariant(subtags[1]);
+                    setVariant(subtags[1].c_str());
                     break;
                 default:
                     fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name %s\n",
-                            part.string());
+                            part.c_str());
                     return -1;
             }
         } else if (subtags.size() == 3) {
             // The language is always the first subtag.
-            setLanguage(subtags[0]);
+            setLanguage(subtags[0].c_str());
 
             // The second subtag can either be a script or a region code.
             // If its size is 4, it's a script code, else it's a region code.
             if (subtags[1].size() == 4) {
-                setScript(subtags[1]);
+                setScript(subtags[1].c_str());
             } else if (subtags[1].size() == 2 || subtags[1].size() == 3) {
-                setRegion(subtags[1]);
+                setRegion(subtags[1].c_str());
             } else {
-                fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name %s\n", part.string());
+                fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name %s\n", part.c_str());
                 return -1;
             }
 
             // The third tag can either be a region code (if the second tag was
             // a script), else a variant code.
             if (subtags[2].size() >= 4) {
-                setVariant(subtags[2]);
+                setVariant(subtags[2].c_str());
             } else {
-                setRegion(subtags[2]);
+                setRegion(subtags[2].c_str());
             }
         } else if (subtags.size() == 4) {
-            setLanguage(subtags[0]);
-            setScript(subtags[1]);
-            setRegion(subtags[2]);
-            setVariant(subtags[3]);
+            setLanguage(subtags[0].c_str());
+            setScript(subtags[1].c_str());
+            setRegion(subtags[2].c_str());
+            setVariant(subtags[3].c_str());
         } else {
-            fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name: %s\n", part.string());
+            fprintf(stderr, "ERROR: Invalid BCP 47 tag in directory name: %s\n", part.c_str());
             return -1;
         }
 
         return ++currentIndex;
     } else {
         if ((part.length() == 2 || part.length() == 3)
-               && isAlpha(part) && strcmp("car", part.string())) {
-            setLanguage(part);
+               && isAlpha(part) && strcmp("car", part.c_str())) {
+            setLanguage(part.c_str());
             if (++currentIndex == size) {
                 return size;
             }
@@ -358,8 +360,8 @@
         }
 
         part = parts[currentIndex];
-        if (part.string()[0] == 'r' && part.length() == 3) {
-            setRegion(part.string() + 1);
+        if (part.c_str()[0] == 'r' && part.length() == 3) {
+            setRegion(part.c_str() + 1);
             if (++currentIndex == size) {
                 return size;
             }
@@ -508,7 +510,7 @@
 {
     if (hasData()) {
         String8 name(mGroupEntry.toDirName(String8()));
-        name.appendPath(mPath);
+        appendPath(name, mPath);
         name.append(" #generated");
         return name;
     }
@@ -524,8 +526,8 @@
     ssize_t index = mFiles.indexOfKey(file->getGroupEntry());
     if (index >= 0 && overwriteDuplicate) {
         fprintf(stderr, "warning: overwriting '%s' with '%s'\n",
-                mFiles[index]->getSourceFile().string(),
-                file->getSourceFile().string());
+                mFiles[index]->getSourceFile().c_str(),
+                file->getSourceFile().c_str());
         removeFile(index);
         index = -1;
     }
@@ -545,7 +547,7 @@
     const sp<AaptFile>& originalFile = mFiles.valueAt(index);
     SourcePos(file->getSourceFile(), -1)
             .error("Duplicate file.\n%s: Original is here. %s",
-                   originalFile->getPrintableSource().string(),
+                   originalFile->getPrintableSource().c_str(),
                    (withoutVersion.version != 0) ? "The version qualifier may be implied." : "");
     return UNKNOWN_ERROR;
 }
@@ -557,21 +559,21 @@
 
 void AaptGroup::print(const String8& prefix) const
 {
-    printf("%s%s\n", prefix.string(), getPath().string());
+    printf("%s%s\n", prefix.c_str(), getPath().c_str());
     const size_t N=mFiles.size();
     size_t i;
     for (i=0; i<N; i++) {
         sp<AaptFile> file = mFiles.valueAt(i);
         const AaptGroupEntry& e = file->getGroupEntry();
         if (file->hasData()) {
-            printf("%s  Gen: (%s) %d bytes\n", prefix.string(), e.toDirName(String8()).string(),
+            printf("%s  Gen: (%s) %d bytes\n", prefix.c_str(), e.toDirName(String8()).c_str(),
                     (int)file->getSize());
         } else {
-            printf("%s  Src: (%s) %s\n", prefix.string(), e.toDirName(String8()).string(),
-                    file->getPrintableSource().string());
+            printf("%s  Src: (%s) %s\n", prefix.c_str(), e.toDirName(String8()).c_str(),
+                    file->getPrintableSource().c_str());
         }
-        //printf("%s  File Group Entry: %s\n", prefix.string(),
-        //        file->getGroupEntry().toDirName(String8()).string());
+        //printf("%s  File Group Entry: %s\n", prefix.c_str(),
+        //        file->getGroupEntry().toDirName(String8()).c_str());
     }
 }
 
@@ -615,7 +617,7 @@
     String8 remain = path;
 
     sp<AaptDir> subdir = this;
-    while (name = remain.walkPath(&remain), remain != "") {
+    while (name = walkPath(remain, &remain), remain != "") {
         subdir = subdir->makeDir(name);
     }
 
@@ -623,7 +625,7 @@
     if (i >= 0) {
         return subdir->mDirs.valueAt(i);
     }
-    sp<AaptDir> dir = new AaptDir(name, subdir->mPath.appendPathCopy(name));
+    sp<AaptDir> dir = new AaptDir(name, appendPathCopy(subdir->mPath, name));
     subdir->mDirs.add(name, dir);
     return dir;
 }
@@ -645,7 +647,7 @@
     if (mFiles.indexOfKey(leafName) >= 0) {
         group = mFiles.valueFor(leafName);
     } else {
-        group = new AaptGroup(leafName, mPath.appendPathCopy(leafName));
+        group = new AaptGroup(leafName, appendPathCopy(mPath, leafName));
         mFiles.add(leafName, group);
     }
 
@@ -660,9 +662,9 @@
     {
         DIR* dir = NULL;
 
-        dir = opendir(srcDir.string());
+        dir = opendir(srcDir.c_str());
         if (dir == NULL) {
-            fprintf(stderr, "ERROR: opendir(%s): %s\n", srcDir.string(), strerror(errno));
+            fprintf(stderr, "ERROR: opendir(%s): %s\n", srcDir.c_str(), strerror(errno));
             return UNKNOWN_ERROR;
         }
 
@@ -676,7 +678,7 @@
             if (entry == NULL)
                 break;
 
-            if (isHidden(srcDir.string(), entry->d_name))
+            if (isHidden(srcDir.c_str(), entry->d_name))
                 continue;
 
             String8 name(entry->d_name);
@@ -684,7 +686,7 @@
             // Add fully qualified path for dependency purposes
             // if we're collecting them
             if (fullResPaths != NULL) {
-                fullResPaths->add(srcDir.appendPathCopy(name));
+                fullResPaths->add(appendPathCopy(srcDir, name));
             }
         }
         closedir(dir);
@@ -701,15 +703,15 @@
         String8 pathName(srcDir);
         FileType type;
 
-        pathName.appendPath(fileNames[i].string());
-        type = getFileType(pathName.string());
+        appendPath(pathName, fileNames[i]);
+        type = getFileType(pathName.c_str());
         if (type == kFileTypeDirectory) {
             sp<AaptDir> subdir;
             bool notAdded = false;
             if (mDirs.indexOfKey(fileNames[i]) >= 0) {
                 subdir = mDirs.valueFor(fileNames[i]);
             } else {
-                subdir = new AaptDir(fileNames[i], mPath.appendPathCopy(fileNames[i]));
+                subdir = new AaptDir(fileNames[i], appendPathCopy(mPath, fileNames[i]));
                 notAdded = true;
             }
             ssize_t res = subdir->slurpFullTree(bundle, pathName, kind,
@@ -732,7 +734,7 @@
 
         } else {
             if (bundle->getVerbose())
-                printf("   (ignoring non-file/dir '%s')\n", pathName.string());
+                printf("   (ignoring non-file/dir '%s')\n", pathName.c_str());
         }
     }
 
@@ -745,7 +747,7 @@
     const size_t ND = mDirs.size();
     size_t i;
     for (i = 0; i < NF; i++) {
-        if (!validateFileName(mFiles.valueAt(i)->getLeaf().string())) {
+        if (!validateFileName(mFiles.valueAt(i)->getLeaf().c_str())) {
             SourcePos(mFiles.valueAt(i)->getPrintableSource(), -1).error(
                     "Invalid filename.  Unable to add.");
             return UNKNOWN_ERROR;
@@ -753,11 +755,11 @@
 
         size_t j;
         for (j = i+1; j < NF; j++) {
-            if (strcasecmp(mFiles.valueAt(i)->getLeaf().string(),
-                           mFiles.valueAt(j)->getLeaf().string()) == 0) {
+            if (strcasecmp(mFiles.valueAt(i)->getLeaf().c_str(),
+                           mFiles.valueAt(j)->getLeaf().c_str()) == 0) {
                 SourcePos(mFiles.valueAt(i)->getPrintableSource(), -1).error(
                         "File is case-insensitive equivalent to: %s",
-                        mFiles.valueAt(j)->getPrintableSource().string());
+                        mFiles.valueAt(j)->getPrintableSource().c_str());
                 return UNKNOWN_ERROR;
             }
 
@@ -766,18 +768,18 @@
         }
 
         for (j = 0; j < ND; j++) {
-            if (strcasecmp(mFiles.valueAt(i)->getLeaf().string(),
-                           mDirs.valueAt(j)->getLeaf().string()) == 0) {
+            if (strcasecmp(mFiles.valueAt(i)->getLeaf().c_str(),
+                           mDirs.valueAt(j)->getLeaf().c_str()) == 0) {
                 SourcePos(mFiles.valueAt(i)->getPrintableSource(), -1).error(
                         "File conflicts with dir from: %s",
-                        mDirs.valueAt(j)->getPrintableSource().string());
+                        mDirs.valueAt(j)->getPrintableSource().c_str());
                 return UNKNOWN_ERROR;
             }
         }
     }
 
     for (i = 0; i < ND; i++) {
-        if (!validateFileName(mDirs.valueAt(i)->getLeaf().string())) {
+        if (!validateFileName(mDirs.valueAt(i)->getLeaf().c_str())) {
             SourcePos(mDirs.valueAt(i)->getPrintableSource(), -1).error(
                     "Invalid directory name, unable to add.");
             return UNKNOWN_ERROR;
@@ -785,11 +787,11 @@
 
         size_t j;
         for (j = i+1; j < ND; j++) {
-            if (strcasecmp(mDirs.valueAt(i)->getLeaf().string(),
-                           mDirs.valueAt(j)->getLeaf().string()) == 0) {
+            if (strcasecmp(mDirs.valueAt(i)->getLeaf().c_str(),
+                           mDirs.valueAt(j)->getLeaf().c_str()) == 0) {
                 SourcePos(mDirs.valueAt(i)->getPrintableSource(), -1).error(
                         "Directory is case-insensitive equivalent to: %s",
-                        mDirs.valueAt(j)->getPrintableSource().string());
+                        mDirs.valueAt(j)->getPrintableSource().c_str());
                 return UNKNOWN_ERROR;
             }
         }
@@ -821,11 +823,11 @@
 {
     if (mFiles.size() > 0) {
         // Arbitrarily pull the first file out of the list as the source dir.
-        return mFiles.valueAt(0)->getPrintableSource().getPathDir();
+        return getPathDir(mFiles.valueAt(0)->getPrintableSource());
     }
     if (mDirs.size() > 0) {
         // Or arbitrarily pull the first dir out of the list as the source dir.
-        return mDirs.valueAt(0)->getPrintableSource().getPathDir();
+        return getPathDir(mDirs.valueAt(0)->getPrintableSource());
     }
 
     // Should never hit this case, but to be safe...
@@ -846,12 +848,12 @@
         const AaptSymbolEntry& entry = javaSymbols->mSymbols.valueAt(i);
         ssize_t pos = mSymbols.indexOfKey(name);
         if (pos < 0) {
-            entry.sourcePos.error("Symbol '%s' declared with <java-symbol> not defined\n", name.string());
+            entry.sourcePos.error("Symbol '%s' declared with <java-symbol> not defined\n", name.c_str());
             err = UNKNOWN_ERROR;
             continue;
         }
         //printf("**** setting symbol #%d/%d %s to isJavaSymbol=%d\n",
-        //        i, N, name.string(), entry.isJavaSymbol ? 1 : 0);
+        //        i, N, name.c_str(), entry.isJavaSymbol ? 1 : 0);
         mSymbols.editValueAt(pos).isJavaSymbol = entry.isJavaSymbol;
     }
 
@@ -862,11 +864,11 @@
         ssize_t pos = mNestedSymbols.indexOfKey(name);
         if (pos < 0) {
             SourcePos pos;
-            pos.error("Java symbol dir %s not defined\n", name.string());
+            pos.error("Java symbol dir %s not defined\n", name.c_str());
             err = UNKNOWN_ERROR;
             continue;
         }
-        //printf("**** applying java symbols in dir %s\n", name.string());
+        //printf("**** applying java symbols in dir %s\n", name.c_str());
         status_t myerr = mNestedSymbols.valueAt(pos)->applyJavaSymbols(symbols);
         if (myerr != NO_ERROR) {
             err = myerr;
@@ -908,8 +910,8 @@
     sp<AaptFile> file;
     String8 root, remain(filePath), partialPath;
     while (remain.length() > 0) {
-        root = remain.walkPath(&remain);
-        partialPath.appendPath(root);
+        root = walkPath(remain, &remain);
+        appendPath(partialPath, root);
 
         const String8 rootStr(root);
 
@@ -924,7 +926,7 @@
                     return NULL;
                 }
             }
-            file = new AaptFile(srcDir.appendPathCopy(filePath), entry, resType);
+            file = new AaptFile(appendPathCopy(srcDir, filePath), entry, resType);
             status_t res = group->addFile(file);
             if (res != NO_ERROR) {
                 return NULL;
@@ -981,7 +983,7 @@
     if (bundle->getAndroidManifestFile() != NULL) {
         // place at root of zip.
         String8 srcFile(bundle->getAndroidManifestFile());
-        addFile(srcFile.getPathLeaf(), AaptGroupEntry(), srcFile.getPathDir(),
+        addFile(getPathLeaf(srcFile), AaptGroupEntry(), getPathDir(srcFile),
                 NULL, String8());
         totalCount++;
     }
@@ -1131,9 +1133,9 @@
 {
     ssize_t err = 0;
 
-    DIR* dir = opendir(srcDir.string());
+    DIR* dir = opendir(srcDir.c_str());
     if (dir == NULL) {
-        fprintf(stderr, "ERROR: opendir(%s): %s\n", srcDir.string(), strerror(errno));
+        fprintf(stderr, "ERROR: opendir(%s): %s\n", srcDir.c_str(), strerror(errno));
         return UNKNOWN_ERROR;
     }
 
@@ -1149,18 +1151,18 @@
             break;
         }
 
-        if (isHidden(srcDir.string(), entry->d_name)) {
+        if (isHidden(srcDir.c_str(), entry->d_name)) {
             continue;
         }
 
         String8 subdirName(srcDir);
-        subdirName.appendPath(entry->d_name);
+        appendPath(subdirName, entry->d_name);
 
         AaptGroupEntry group;
         String8 resType;
         bool b = group.initFromDirName(entry->d_name, &resType);
         if (!b) {
-            fprintf(stderr, "invalid resource directory name: %s %s\n", srcDir.string(),
+            fprintf(stderr, "invalid resource directory name: %s %s\n", srcDir.c_str(),
                     entry->d_name);
             err = -1;
             continue;
@@ -1168,7 +1170,7 @@
 
         if (bundle->getMaxResVersion() != NULL && group.getVersionString().length() != 0) {
             int maxResInt = atoi(bundle->getMaxResVersion());
-            const char *verString = group.getVersionString().string();
+            const char *verString = group.getVersionString().c_str();
             int dirVersionInt = atoi(verString + 1); // skip 'v' in version name
             if (dirVersionInt > maxResInt) {
               fprintf(stderr, "max res %d, skipping %s\n", maxResInt, entry->d_name);
@@ -1176,7 +1178,7 @@
             }
         }
 
-        FileType type = getFileType(subdirName.string());
+        FileType type = getFileType(subdirName.c_str());
 
         if (type == kFileTypeDirectory) {
             sp<AaptDir> dir = makeDir(resType);
@@ -1200,7 +1202,7 @@
             }
         } else {
             if (bundle->getVerbose()) {
-                fprintf(stderr, "   (ignoring file '%s')\n", subdirName.string());
+                fprintf(stderr, "   (ignoring file '%s')\n", subdirName.c_str());
             }
         }
     }
@@ -1239,16 +1241,16 @@
 
         String8 entryName(entry->getFileName());
 
-        String8 dirName = entryName.getPathDir();
+        String8 dirName = getPathDir(entryName);
         sp<AaptDir> dir = dirName == "" ? this : makeDir(dirName);
 
         String8 resType;
         AaptGroupEntry kind;
 
         String8 remain;
-        if (entryName.walkPath(&remain) == kResourceDir) {
+        if (walkPath(entryName, &remain) == kResourceDir) {
             // these are the resources, pull their type out of the directory name
-            kind.initFromDirName(remain.walkPath().string(), &resType);
+            kind.initFromDirName(walkPath(remain).c_str(), &resType);
         } else {
             // these are untyped and don't have an AaptGroupEntry
         }
@@ -1258,12 +1260,12 @@
         }
 
         // use the one from the zip file if they both exist.
-        dir->removeFile(entryName.getPathLeaf());
+        dir->removeFile(getPathLeaf(entryName));
 
         sp<AaptFile> file = new AaptFile(entryName, kind, resType);
-        status_t err = dir->addLeafFile(entryName.getPathLeaf(), file);
+        status_t err = dir->addLeafFile(getPathLeaf(entryName), file);
         if (err != NO_ERROR) {
-            fprintf(stderr, "err=%s entryName=%s\n", strerror(err), entryName.string());
+            fprintf(stderr, "err=%s entryName=%s\n", strerror(err), entryName.c_str());
             count = err;
             goto bail;
         }
@@ -1273,7 +1275,7 @@
         if (entryName == "AndroidManifest.xml") {
             printf("AndroidManifest.xml\n");
         }
-        printf("\n\nfile: %s\n", entryName.string());
+        printf("\n\nfile: %s\n", entryName.c_str());
 #endif
 
         size_t len = entry->getUncompressedLen();
@@ -1317,9 +1319,9 @@
     uint32_t preferredDensity = 0;
     if (bundle->getPreferredDensity().size() > 0) {
         ResTable_config preferredConfig;
-        if (!AaptConfig::parseDensity(bundle->getPreferredDensity().string(), &preferredConfig)) {
+        if (!AaptConfig::parseDensity(bundle->getPreferredDensity().c_str(), &preferredConfig)) {
             fprintf(stderr, "Error parsing preferred density: %s\n",
-                    bundle->getPreferredDensity().string());
+                    bundle->getPreferredDensity().c_str());
             return UNKNOWN_ERROR;
         }
         preferredDensity = preferredConfig.density;
@@ -1332,11 +1334,11 @@
     if (bundle->getVerbose()) {
         if (!reqFilter->isEmpty()) {
             printf("Applying required filter: %s\n",
-                    bundle->getConfigurations().string());
+                    bundle->getConfigurations().c_str());
         }
         if (preferredDensity > 0) {
             printf("Applying preferred density filter: %s\n",
-                    bundle->getPreferredDensity().string());
+                    bundle->getPreferredDensity().c_str());
         }
     }
 
@@ -1374,7 +1376,7 @@
                     // containing no entries.
                     continue;
                 }
-                if (file->getPath().getPathExtension() == ".xml") {
+                if (getPathExtension(file->getPath()) == ".xml") {
                     // We can't remove .xml files at this point, because when
                     // we parse them they may add identifier resources, so
                     // removing them can cause our resource identifiers to
@@ -1385,7 +1387,7 @@
                 if (!reqFilter->match(config)) {
                     if (bundle->getVerbose()) {
                         printf("Pruning unneeded resource: %s\n",
-                                file->getPrintableSource().string());
+                                file->getPrintableSource().c_str());
                     }
                     grp->removeFile(k);
                     k--;
@@ -1411,7 +1413,7 @@
                     // containing no entries.
                     continue;
                 }
-                if (file->getPath().getPathExtension() == ".xml") {
+                if (getPathExtension(file->getPath()) == ".xml") {
                     // We can't remove .xml files at this point, because when
                     // we parse them they may add identifier resources, so
                     // removing them can cause our resource identifiers to
@@ -1453,7 +1455,7 @@
                     if (bestDensity != config.density) {
                         if (bundle->getVerbose()) {
                             printf("Pruning unneeded resource: %s\n",
-                                    file->getPrintableSource().string());
+                                    file->getPrintableSource().c_str());
                         }
                         grp->removeFile(k);
                         k--;
@@ -1495,10 +1497,10 @@
         ssize_t pos = mSymbols.indexOfKey(name);
         if (pos < 0) {
             SourcePos pos;
-            pos.error("Java symbol dir %s not defined\n", name.string());
+            pos.error("Java symbol dir %s not defined\n", name.c_str());
             return UNKNOWN_ERROR;
         }
-        //printf("**** applying java symbols in dir %s\n", name.string());
+        //printf("**** applying java symbols in dir %s\n", name.c_str());
         status_t err = mSymbols.valueAt(pos)->applyJavaSymbols(symbols);
         if (err != NO_ERROR) {
             return err;
@@ -1510,7 +1512,7 @@
 
 bool AaptAssets::isJavaSymbol(const AaptSymbolEntry& sym, bool includePrivate) const {
     //printf("isJavaSymbol %s: public=%d, includePrivate=%d, isJavaSymbol=%d\n",
-    //        sym.name.string(), sym.isPublic ? 1 : 0, includePrivate ? 1 : 0,
+    //        sym.name.c_str(), sym.isPublic ? 1 : 0, includePrivate ? 1 : 0,
     //        sym.isJavaSymbol ? 1 : 0);
     if (!mHavePrivateSymbols) return true;
     if (sym.isPublic) return true;
@@ -1529,26 +1531,26 @@
     const size_t packageIncludeCount = includes.size();
     for (size_t i = 0; i < packageIncludeCount; i++) {
         if (bundle->getVerbose()) {
-            printf("Including resources from package: %s\n", includes[i].string());
+            printf("Including resources from package: %s\n", includes[i].c_str());
         }
 
         if (!mIncludedAssets.addAssetPath(includes[i], NULL)) {
             fprintf(stderr, "ERROR: Asset package include '%s' not found.\n",
-                    includes[i].string());
+                    includes[i].c_str());
             return UNKNOWN_ERROR;
         }
     }
 
     const String8& featureOfBase = bundle->getFeatureOfPackage();
-    if (!featureOfBase.isEmpty()) {
+    if (!featureOfBase.empty()) {
         if (bundle->getVerbose()) {
             printf("Including base feature resources from package: %s\n",
-                    featureOfBase.string());
+                    featureOfBase.c_str());
         }
 
         if (!mIncludedAssets.addAssetPath(featureOfBase, NULL)) {
             fprintf(stderr, "ERROR: base feature package '%s' not found.\n",
-                    featureOfBase.string());
+                    featureOfBase.c_str());
             return UNKNOWN_ERROR;
         }
     }
@@ -1581,23 +1583,23 @@
     innerPrefix.append("  ");
     String8 innerInnerPrefix(innerPrefix);
     innerInnerPrefix.append("  ");
-    printf("%sConfigurations:\n", prefix.string());
+    printf("%sConfigurations:\n", prefix.c_str());
     const size_t N=mGroupEntries.size();
     for (size_t i=0; i<N; i++) {
         String8 cname = mGroupEntries.itemAt(i).toDirName(String8());
-        printf("%s %s\n", prefix.string(),
-                cname != "" ? cname.string() : "(default)");
+        printf("%s %s\n", prefix.c_str(),
+                cname != "" ? cname.c_str() : "(default)");
     }
 
-    printf("\n%sFiles:\n", prefix.string());
+    printf("\n%sFiles:\n", prefix.c_str());
     AaptDir::print(innerPrefix);
 
-    printf("\n%sResource Dirs:\n", prefix.string());
+    printf("\n%sResource Dirs:\n", prefix.c_str());
     const Vector<sp<AaptDir> >& resdirs = mResDirs;
     const size_t NR = resdirs.size();
     for (size_t i=0; i<NR; i++) {
         const sp<AaptDir>& d = resdirs.itemAt(i);
-        printf("%s  Type %s\n", prefix.string(), d->getLeaf().string());
+        printf("%s  Type %s\n", prefix.c_str(), d->getLeaf().c_str());
         d->print(innerInnerPrefix);
     }
 }
@@ -1631,7 +1633,7 @@
         NULL
     };
     const char*const* k = KEYWORDS;
-    const char*const s = symbol.string();
+    const char*const s = symbol.c_str();
     while (*k) {
         if (0 == strcmp(s, *k)) {
             return false;
diff --git a/tools/aapt/AaptAssets.h b/tools/aapt/AaptAssets.h
index eadd48a..498fc4e 100644
--- a/tools/aapt/AaptAssets.h
+++ b/tools/aapt/AaptAssets.h
@@ -463,7 +463,7 @@
         if (valid_symbol_name(symbol)) {
             return true;
         }
-        pos.error("invalid %s: '%s'\n", label, symbol.string());
+        pos.error("invalid %s: '%s'\n", label, symbol.c_str());
         return false;
     }
     AaptSymbolEntry& edit_symbol(const String8& symbol, const SourcePos* pos) {
diff --git a/tools/aapt/AaptConfig.cpp b/tools/aapt/AaptConfig.cpp
index 0aca45e..7578f79 100644
--- a/tools/aapt/AaptConfig.cpp
+++ b/tools/aapt/AaptConfig.cpp
@@ -39,7 +39,7 @@
     ssize_t index = 0;
     ssize_t localeIndex = 0;
     const ssize_t N = parts.size();
-    const char* part = parts[index].string();
+    const char* part = parts[index].c_str();
 
     if (str.length() == 0) {
         goto success;
@@ -50,7 +50,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseMnc(part, &config)) {
@@ -58,7 +58,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     // Locale spans a few '-' separators, so we let it
@@ -72,7 +72,7 @@
         if (index >= N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseLayoutDirection(part, &config)) {
@@ -80,7 +80,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseSmallestScreenWidthDp(part, &config)) {
@@ -88,7 +88,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenWidthDp(part, &config)) {
@@ -96,7 +96,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenHeightDp(part, &config)) {
@@ -104,7 +104,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenLayoutSize(part, &config)) {
@@ -112,7 +112,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenLayoutLong(part, &config)) {
@@ -120,7 +120,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenRound(part, &config)) {
@@ -128,7 +128,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseWideColorGamut(part, &config)) {
@@ -136,7 +136,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseHdr(part, &config)) {
@@ -144,7 +144,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseOrientation(part, &config)) {
@@ -152,7 +152,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseUiModeType(part, &config)) {
@@ -160,7 +160,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseUiModeNight(part, &config)) {
@@ -168,7 +168,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseDensity(part, &config)) {
@@ -176,7 +176,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseTouchscreen(part, &config)) {
@@ -184,7 +184,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseKeysHidden(part, &config)) {
@@ -192,7 +192,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseKeyboard(part, &config)) {
@@ -200,7 +200,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseNavHidden(part, &config)) {
@@ -208,7 +208,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseNavigation(part, &config)) {
@@ -216,7 +216,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseScreenSize(part, &config)) {
@@ -224,7 +224,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     if (parseVersion(part, &config)) {
@@ -232,7 +232,7 @@
         if (index == N) {
             goto success;
         }
-        part = parts[index].string();
+        part = parts[index].c_str();
     }
 
     // Unrecognized.
@@ -773,8 +773,8 @@
     if (y == name || *y != 0) return false;
     String8 yName(x, y-x);
 
-    uint16_t w = (uint16_t)atoi(xName.string());
-    uint16_t h = (uint16_t)atoi(yName.string());
+    uint16_t w = (uint16_t)atoi(xName.c_str());
+    uint16_t h = (uint16_t)atoi(yName.c_str());
     if (w < h) {
         return false;
     }
@@ -805,7 +805,7 @@
     String8 xName(name, x-name);
 
     if (out) {
-        out->smallestScreenWidthDp = (uint16_t)atoi(xName.string());
+        out->smallestScreenWidthDp = (uint16_t)atoi(xName.c_str());
     }
 
     return true;
@@ -827,7 +827,7 @@
     String8 xName(name, x-name);
 
     if (out) {
-        out->screenWidthDp = (uint16_t)atoi(xName.string());
+        out->screenWidthDp = (uint16_t)atoi(xName.c_str());
     }
 
     return true;
@@ -849,7 +849,7 @@
     String8 xName(name, x-name);
 
     if (out) {
-        out->screenHeightDp = (uint16_t)atoi(xName.string());
+        out->screenHeightDp = (uint16_t)atoi(xName.c_str());
     }
 
     return true;
@@ -875,7 +875,7 @@
     String8 sdkName(name, s-name);
 
     if (out) {
-        out->sdkVersion = (uint16_t)atoi(sdkName.string());
+        out->sdkVersion = (uint16_t)atoi(sdkName.c_str());
         out->minorVersion = 0;
     }
 
diff --git a/tools/aapt/AaptUtil.cpp b/tools/aapt/AaptUtil.cpp
index 293e144..e82860d 100644
--- a/tools/aapt/AaptUtil.cpp
+++ b/tools/aapt/AaptUtil.cpp
@@ -23,7 +23,7 @@
 
 Vector<String8> split(const String8& str, const char sep) {
     Vector<String8> parts;
-    const char* p = str.string();
+    const char* p = str.c_str();
     const char* q;
 
     while (true) {
@@ -41,7 +41,7 @@
 
 Vector<String8> splitAndLowerCase(const String8& str, const char sep) {
     Vector<String8> parts;
-    const char* p = str.string();
+    const char* p = str.c_str();
     const char* q;
 
     while (true) {
diff --git a/tools/aapt/Android.bp b/tools/aapt/Android.bp
index cc10db9..68db56d 100644
--- a/tools/aapt/Android.bp
+++ b/tools/aapt/Android.bp
@@ -51,6 +51,10 @@
         "libz",
     ],
 
+    whole_static_libs: [
+        "libandroidfw_pathutils",
+    ],
+
     cflags: [
         "-Wall",
         "-Werror",
@@ -97,6 +101,7 @@
         "ResourceTable.cpp",
         "SourcePos.cpp",
         "StringPool.cpp",
+        "Utils.cpp",
         "WorkQueue.cpp",
         "XMLNode.cpp",
         "ZipEntry.cpp",
diff --git a/tools/aapt/ApkBuilder.cpp b/tools/aapt/ApkBuilder.cpp
index 01e02e2..335c43b 100644
--- a/tools/aapt/ApkBuilder.cpp
+++ b/tools/aapt/ApkBuilder.cpp
@@ -36,7 +36,7 @@
             if (splitConfigs.count(*iter) > 0) {
                 // Can't have overlapping configurations.
                 fprintf(stderr, "ERROR: Split configuration '%s' is already defined "
-                        "in another split.\n", iter->toString().string());
+                        "in another split.\n", iter->toString().c_str());
                 return ALREADY_EXISTS;
             }
         }
@@ -115,10 +115,10 @@
 }
 
 void ApkSplit::print() const {
-    fprintf(stderr, "APK Split '%s'\n", mName.string());
+    fprintf(stderr, "APK Split '%s'\n", mName.c_str());
 
     std::set<OutputEntry>::const_iterator iter = mFiles.begin();
     for (; iter != mFiles.end(); iter++) {
-        fprintf(stderr, "  %s (%s)\n", iter->getPath().string(), iter->getFile()->getSourceFile().string());
+        fprintf(stderr, "  %s (%s)\n", iter->getPath().c_str(), iter->getFile()->getSourceFile().c_str());
     }
 }
diff --git a/tools/aapt/CacheUpdater.h b/tools/aapt/CacheUpdater.h
index 6fa96d6..dc5493f 100644
--- a/tools/aapt/CacheUpdater.h
+++ b/tools/aapt/CacheUpdater.h
@@ -7,6 +7,7 @@
 #ifndef CACHE_UPDATER_H
 #define CACHE_UPDATER_H
 
+#include <androidfw/PathUtils.h>
 #include <utils/String8.h>
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -16,6 +17,8 @@
 #include <direct.h>
 #endif
 
+#include "Utils.h"
+
 using namespace android;
 
 /** CacheUpdater
@@ -66,25 +69,25 @@
         // Check optomistically to see if all directories exist.
         // If something in the path doesn't exist, then walk the path backwards
         // and find the place to start creating directories forward.
-        if (stat(path.string(),&s) == -1) {
+        if (stat(path.c_str(),&s) == -1) {
             // Walk backwards to find place to start creating directories
             existsPath = path;
             do {
                 // As we remove the end of existsPath add it to
                 // the string of paths to create.
-                toCreate = existsPath.getPathLeaf().appendPath(toCreate);
-                existsPath = existsPath.getPathDir();
-            } while (stat(existsPath.string(),&s) == -1);
+                toCreate = appendPathCopy(getPathLeaf(existsPath), toCreate);
+                existsPath = getPathDir(existsPath);
+            } while (stat(existsPath.c_str(),&s) == -1);
 
             // Walk forwards and build directories as we go
             do {
                 // Advance to the next segment of the path
-                existsPath.appendPath(toCreate.walkPath(&remains));
+                appendPath(existsPath, walkPath(toCreate, &remains));
                 toCreate = remains;
 #ifdef _WIN32
-                _mkdir(existsPath.string());
+                _mkdir(existsPath.c_str());
 #else
-                mkdir(existsPath.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
+                mkdir(existsPath.c_str(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
 #endif
             } while (remains.length() > 0);
         } //if
@@ -93,15 +96,15 @@
     // Delete a file
     virtual void deleteFile(String8 path)
     {
-        if (remove(path.string()) != 0)
-            fprintf(stderr,"ERROR DELETING %s\n",path.string());
+        if (remove(path.c_str()) != 0)
+            fprintf(stderr,"ERROR DELETING %s\n",path.c_str());
     };
 
     // Process an image from source out to dest
     virtual void processImage(String8 source, String8 dest)
     {
         // Make sure we're trying to write to a directory that is extant
-        ensureDirectoriesExist(dest.getPathDir());
+        ensureDirectoriesExist(getPathDir(dest));
 
         preProcessImageToCache(bundle, source, dest);
     };
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index d02fd83..43a8b52 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -12,6 +12,7 @@
 #include "ResourceTable.h"
 #include "XMLNode.h"
 
+#include <androidfw/PathUtils.h>
 #include <utils/Errors.h>
 #include <utils/KeyedVector.h>
 #include <utils/List.h>
@@ -240,13 +241,13 @@
     }
     if (value.dataType == Res_value::TYPE_STRING) {
         String8 result = AaptXml::getResolvedAttribute(resTable, tree, attrRes, outError);
-        printf("%s='%s'", attrLabel.string(),
-                ResTable::normalizeForOutput(result.string()).string());
+        printf("%s='%s'", attrLabel.c_str(),
+                ResTable::normalizeForOutput(result.c_str()).c_str());
     } else if (Res_value::TYPE_FIRST_INT <= value.dataType &&
             value.dataType <= Res_value::TYPE_LAST_INT) {
-        printf("%s='%d'", attrLabel.string(), value.data);
+        printf("%s='%d'", attrLabel.c_str(), value.data);
     } else {
-        printf("%s='0x%x'", attrLabel.string(), (int)value.data);
+        printf("%s='0x%x'", attrLabel.c_str(), (int)value.data);
     }
 }
 
@@ -353,23 +354,23 @@
 }
 
 static void printUsesPermission(const String8& name, bool optional=false, int maxSdkVersion=-1,
-        const String8& requiredFeature = String8::empty(),
-        const String8& requiredNotFeature = String8::empty()) {
-    printf("uses-permission: name='%s'", ResTable::normalizeForOutput(name.string()).string());
+        const String8& requiredFeature = String8(),
+        const String8& requiredNotFeature = String8()) {
+    printf("uses-permission: name='%s'", ResTable::normalizeForOutput(name.c_str()).c_str());
     if (maxSdkVersion != -1) {
          printf(" maxSdkVersion='%d'", maxSdkVersion);
     }
     if (requiredFeature.length() > 0) {
-         printf(" requiredFeature='%s'", requiredFeature.string());
+         printf(" requiredFeature='%s'", requiredFeature.c_str());
     }
     if (requiredNotFeature.length() > 0) {
-         printf(" requiredNotFeature='%s'", requiredNotFeature.string());
+         printf(" requiredNotFeature='%s'", requiredNotFeature.c_str());
     }
     printf("\n");
 
     if (optional) {
         printf("optional-permission: name='%s'",
-                ResTable::normalizeForOutput(name.string()).string());
+                ResTable::normalizeForOutput(name.c_str()).c_str());
         if (maxSdkVersion != -1) {
             printf(" maxSdkVersion='%d'", maxSdkVersion);
         }
@@ -380,7 +381,7 @@
 static void printUsesPermissionSdk23(const String8& name, int maxSdkVersion=-1) {
     printf("uses-permission-sdk-23: ");
 
-    printf("name='%s'", ResTable::normalizeForOutput(name.string()).string());
+    printf("name='%s'", ResTable::normalizeForOutput(name.c_str()).c_str());
     if (maxSdkVersion != -1) {
         printf(" maxSdkVersion='%d'", maxSdkVersion);
     }
@@ -390,17 +391,17 @@
 static void printUsesImpliedPermission(const String8& name, const String8& reason,
         const int32_t maxSdkVersion = -1) {
     printf("uses-implied-permission: name='%s'",
-            ResTable::normalizeForOutput(name.string()).string());
+            ResTable::normalizeForOutput(name.c_str()).c_str());
     if (maxSdkVersion != -1) {
         printf(" maxSdkVersion='%d'", maxSdkVersion);
     }
-    printf(" reason='%s'\n", ResTable::normalizeForOutput(reason.string()).string());
+    printf(" reason='%s'\n", ResTable::normalizeForOutput(reason.c_str()).c_str());
 }
 
 Vector<String8> getNfcAidCategories(AssetManager& assets, const String8& xmlPath, bool offHost,
         String8 *outError = NULL)
 {
-    Asset* aidAsset = assets.openNonAsset(xmlPath, Asset::ACCESS_BUFFER);
+    Asset* aidAsset = assets.openNonAsset(xmlPath.c_str(), Asset::ACCESS_BUFFER);
     if (aidAsset == NULL) {
         if (outError != NULL) *outError = "xml resource does not exist";
         return Vector<String8>();
@@ -556,7 +557,7 @@
 
 static void printFeatureGroupImpl(const FeatureGroup& grp,
                                   const KeyedVector<String8, ImpliedFeature>* impliedFeatures) {
-    printf("feature-group: label='%s'\n", grp.label.string());
+    printf("feature-group: label='%s'\n", grp.label.c_str());
 
     if (grp.openGLESVersion > 0) {
         printf("  uses-gl-es: '0x%x'\n", grp.openGLESVersion);
@@ -570,7 +571,7 @@
 
         const String8& featureName = grp.features.keyAt(i);
         printf("  uses-feature%s: name='%s'", (required ? "" : "-not-required"),
-                ResTable::normalizeForOutput(featureName.string()).string());
+                ResTable::normalizeForOutput(featureName.c_str()).c_str());
 
         if (version > 0) {
             printf(" version='%d'", version);
@@ -589,15 +590,15 @@
         }
 
         String8 printableFeatureName(ResTable::normalizeForOutput(
-                    impliedFeature.name.string()));
+                    impliedFeature.name.c_str()));
         const char* sdk23Suffix = impliedFeature.impliedBySdk23 ? "-sdk-23" : "";
 
-        printf("  uses-feature%s: name='%s'\n", sdk23Suffix, printableFeatureName.string());
+        printf("  uses-feature%s: name='%s'\n", sdk23Suffix, printableFeatureName.c_str());
         printf("  uses-implied-feature%s: name='%s' reason='", sdk23Suffix,
-               printableFeatureName.string());
+               printableFeatureName.c_str());
         const size_t numReasons = impliedFeature.reasons.size();
         for (size_t j = 0; j < numReasons; j++) {
-            printf("%s", impliedFeature.reasons[j].string());
+            printf("%s", impliedFeature.reasons[j].c_str());
             if (j + 2 < numReasons) {
                 printf(", ");
             } else if (j + 1 < numReasons) {
@@ -649,43 +650,43 @@
                                             bool impliedBySdk23Permission) {
     if (name == "android.permission.CAMERA") {
         addImpliedFeature(impliedFeatures, "android.hardware.camera",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.ACCESS_FINE_LOCATION") {
         if (targetSdk < SDK_LOLLIPOP) {
             addImpliedFeature(impliedFeatures, "android.hardware.location.gps",
-                              String8::format("requested %s permission", name.string()),
+                              String8::format("requested %s permission", name.c_str()),
                               impliedBySdk23Permission);
             addImpliedFeature(impliedFeatures, "android.hardware.location.gps",
                               String8::format("targetSdkVersion < %d", SDK_LOLLIPOP),
                               impliedBySdk23Permission);
         }
         addImpliedFeature(impliedFeatures, "android.hardware.location",
-                String8::format("requested %s permission", name.string()),
+                String8::format("requested %s permission", name.c_str()),
                 impliedBySdk23Permission);
     } else if (name == "android.permission.ACCESS_COARSE_LOCATION") {
         if (targetSdk < SDK_LOLLIPOP) {
             addImpliedFeature(impliedFeatures, "android.hardware.location.network",
-                              String8::format("requested %s permission", name.string()),
+                              String8::format("requested %s permission", name.c_str()),
                               impliedBySdk23Permission);
             addImpliedFeature(impliedFeatures, "android.hardware.location.network",
                               String8::format("targetSdkVersion < %d", SDK_LOLLIPOP),
                               impliedBySdk23Permission);
         }
         addImpliedFeature(impliedFeatures, "android.hardware.location",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.ACCESS_MOCK_LOCATION" ||
                name == "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" ||
                name == "android.permission.INSTALL_LOCATION_PROVIDER") {
         addImpliedFeature(impliedFeatures, "android.hardware.location",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.BLUETOOTH" ||
                name == "android.permission.BLUETOOTH_ADMIN") {
         if (targetSdk > SDK_DONUT) {
             addImpliedFeature(impliedFeatures, "android.hardware.bluetooth",
-                              String8::format("requested %s permission", name.string()),
+                              String8::format("requested %s permission", name.c_str()),
                               impliedBySdk23Permission);
             addImpliedFeature(impliedFeatures, "android.hardware.bluetooth",
                               String8::format("targetSdkVersion > %d", SDK_DONUT),
@@ -693,13 +694,13 @@
         }
     } else if (name == "android.permission.RECORD_AUDIO") {
         addImpliedFeature(impliedFeatures, "android.hardware.microphone",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.ACCESS_WIFI_STATE" ||
                name == "android.permission.CHANGE_WIFI_STATE" ||
                name == "android.permission.CHANGE_WIFI_MULTICAST_STATE") {
         addImpliedFeature(impliedFeatures, "android.hardware.wifi",
-                          String8::format("requested %s permission", name.string()),
+                          String8::format("requested %s permission", name.c_str()),
                           impliedBySdk23Permission);
     } else if (name == "android.permission.CALL_PHONE" ||
                name == "android.permission.CALL_PRIVILEGED" ||
@@ -746,7 +747,7 @@
     for (size_t i = 0; i < bundle->getPackageIncludes().size(); i++) {
       const String8& assetPath = bundle->getPackageIncludes()[i];
       if (!assets.addAssetPath(assetPath, NULL)) {
-        fprintf(stderr, "ERROR: included asset path %s could not be loaded\n", assetPath.string());
+        fprintf(stderr, "ERROR: included asset path %s could not be loaded\n", assetPath.c_str());
         return 1;
       }
     }
@@ -890,7 +891,7 @@
                     goto bail;
                 }
                 String8 tag(ctag16);
-                //printf("Depth %d tag %s\n", depth, tag.string());
+                //printf("Depth %d tag %s\n", depth, tag.c_str());
                 if (depth == 1) {
                     if (tag != "manifest") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
@@ -898,14 +899,14 @@
                         goto bail;
                     }
                     String8 pkg = AaptXml::getAttribute(tree, NULL, "package", NULL);
-                    printf("package: %s\n", ResTable::normalizeForOutput(pkg.string()).string());
+                    printf("package: %s\n", ResTable::normalizeForOutput(pkg.c_str()).c_str());
                 } else if (depth == 2) {
                     if (tag == "permission") {
                         String8 error;
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name': %s", error.string());
+                                    "ERROR getting 'android:name': %s", error.c_str());
                             goto bail;
                         }
 
@@ -915,13 +916,13 @@
                             goto bail;
                         }
                         printf("permission: %s\n",
-                                ResTable::normalizeForOutput(name.string()).string());
+                                ResTable::normalizeForOutput(name.c_str()).c_str());
                     } else if (tag == "uses-permission") {
                         String8 error;
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -938,7 +939,7 @@
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -1133,12 +1134,12 @@
                 if (code == ResXMLTree::END_TAG) {
                     depth--;
                     if (depth < 2) {
-                        if (withinSupportsInput && !supportedInput.isEmpty()) {
+                        if (withinSupportsInput && !supportedInput.empty()) {
                             printf("supports-input: '");
                             const size_t N = supportedInput.size();
                             for (size_t i=0; i<N; i++) {
                                 printf("%s", ResTable::normalizeForOutput(
-                                        supportedInput[i].string()).string());
+                                        supportedInput[i].c_str()).c_str());
                                 if (i != N - 1) {
                                     printf("' '");
                                 } else {
@@ -1157,27 +1158,27 @@
                                 printf("launchable-activity:");
                                 if (aName.length() > 0) {
                                     printf(" name='%s' ",
-                                            ResTable::normalizeForOutput(aName.string()).string());
+                                            ResTable::normalizeForOutput(aName.c_str()).c_str());
                                 }
                                 printf(" label='%s' icon='%s'\n",
-                                       ResTable::normalizeForOutput(activityLabel.string())
-                                                .string(),
-                                       ResTable::normalizeForOutput(activityIcon.string())
-                                                .string());
+                                       ResTable::normalizeForOutput(activityLabel.c_str())
+                                                .c_str(),
+                                       ResTable::normalizeForOutput(activityIcon.c_str())
+                                                .c_str());
                             }
                             if (isLeanbackLauncherActivity) {
                                 printf("leanback-launchable-activity:");
                                 if (aName.length() > 0) {
                                     printf(" name='%s' ",
-                                            ResTable::normalizeForOutput(aName.string()).string());
+                                            ResTable::normalizeForOutput(aName.c_str()).c_str());
                                 }
                                 printf(" label='%s' icon='%s' banner='%s'\n",
-                                       ResTable::normalizeForOutput(activityLabel.string())
-                                                .string(),
-                                       ResTable::normalizeForOutput(activityIcon.string())
-                                                .string(),
-                                       ResTable::normalizeForOutput(activityBanner.string())
-                                                .string());
+                                       ResTable::normalizeForOutput(activityLabel.c_str())
+                                                .c_str(),
+                                       ResTable::normalizeForOutput(activityIcon.c_str())
+                                                .c_str(),
+                                       ResTable::normalizeForOutput(activityBanner.c_str())
+                                                .c_str());
                             }
                         }
                         if (!hasIntentFilter) {
@@ -1265,7 +1266,7 @@
                     goto bail;
                 }
                 String8 tag(ctag16);
-                //printf("Depth %d,  %s\n", depth, tag.string());
+                //printf("Depth %d,  %s\n", depth, tag.c_str());
                 if (depth == 1) {
                     if (tag != "manifest") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
@@ -1274,13 +1275,13 @@
                     }
                     pkg = AaptXml::getAttribute(tree, NULL, "package", NULL);
                     printf("package: name='%s' ",
-                            ResTable::normalizeForOutput(pkg.string()).string());
+                            ResTable::normalizeForOutput(pkg.c_str()).c_str());
                     int32_t versionCode = AaptXml::getIntegerAttribute(tree, VERSION_CODE_ATTR,
                             &error);
                     if (error != "") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
                                 "ERROR getting 'android:versionCode' attribute: %s",
-                                error.string());
+                                error.c_str());
                         goto bail;
                     }
                     if (versionCode > 0) {
@@ -1293,16 +1294,16 @@
                     if (error != "") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
                                 "ERROR getting 'android:versionName' attribute: %s",
-                                error.string());
+                                error.c_str());
                         goto bail;
                     }
                     printf("versionName='%s'",
-                            ResTable::normalizeForOutput(versionName.string()).string());
+                            ResTable::normalizeForOutput(versionName.c_str()).c_str());
 
                     String8 splitName = AaptXml::getAttribute(tree, NULL, "split");
-                    if (!splitName.isEmpty()) {
+                    if (!splitName.empty()) {
                         printf(" split='%s'", ResTable::normalizeForOutput(
-                                    splitName.string()).string());
+                                    splitName.c_str()).c_str());
                     }
 
                     // For 'platformBuildVersionName', using both string and int type as a fallback
@@ -1313,7 +1314,7 @@
                             AaptXml::getIntegerAttribute(tree, NULL, "platformBuildVersionName", 0,
                                                          NULL);
                     if (platformBuildVersionName != "") {
-                        printf(" platformBuildVersionName='%s'", platformBuildVersionName.string());
+                        printf(" platformBuildVersionName='%s'", platformBuildVersionName.c_str());
                     } else if (platformBuildVersionNameInt > 0) {
                         printf(" platformBuildVersionName='%d'", platformBuildVersionNameInt);
                     }
@@ -1326,7 +1327,7 @@
                             AaptXml::getIntegerAttribute(tree, NULL, "platformBuildVersionCode", 0,
                                                          NULL);
                     if (platformBuildVersionCode != "") {
-                        printf(" platformBuildVersionCode='%s'", platformBuildVersionCode.string());
+                        printf(" platformBuildVersionCode='%s'", platformBuildVersionCode.c_str());
                     } else if (platformBuildVersionCodeInt > 0) {
                         printf(" platformBuildVersionCode='%d'", platformBuildVersionCodeInt);
                     }
@@ -1336,7 +1337,7 @@
                     if (error != "") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
                                 "ERROR getting 'android:compileSdkVersion' attribute: %s",
-                                error.string());
+                                error.c_str());
                         goto bail;
                     }
                     if (compileSdkVersion > 0) {
@@ -1347,7 +1348,7 @@
                             COMPILE_SDK_VERSION_CODENAME_ATTR, &error);
                     if (compileSdkVersionCodename != "") {
                         printf(" compileSdkVersionCodename='%s'", ResTable::normalizeForOutput(
-                                compileSdkVersionCodename.string()).string());
+                                compileSdkVersionCodename.c_str()).c_str());
                     }
 
                     printf("\n");
@@ -1357,7 +1358,7 @@
                     if (error != "") {
                         SourcePos(manifestFile, tree.getLineNumber()).error(
                                 "ERROR getting 'android:installLocation' attribute: %s",
-                                error.string());
+                                error.c_str());
                         goto bail;
                     }
 
@@ -1387,7 +1388,7 @@
                         String8 label;
                         const size_t NL = locales.size();
                         for (size_t i=0; i<NL; i++) {
-                            const char* localeStr =  locales[i].string();
+                            const char* localeStr =  locales[i].c_str();
                             assets.setConfiguration(config, localeStr != NULL ? localeStr : "");
                             String8 llabel = AaptXml::getResolvedAttribute(res, tree, LABEL_ATTR,
                                     &error);
@@ -1395,13 +1396,13 @@
                                 if (localeStr == NULL || strlen(localeStr) == 0) {
                                     label = llabel;
                                     printf("application-label:'%s'\n",
-                                            ResTable::normalizeForOutput(llabel.string()).string());
+                                            ResTable::normalizeForOutput(llabel.c_str()).c_str());
                                 } else {
                                     if (label == "") {
                                         label = llabel;
                                     }
                                     printf("application-label-%s:'%s'\n", localeStr,
-                                           ResTable::normalizeForOutput(llabel.string()).string());
+                                           ResTable::normalizeForOutput(llabel.c_str()).c_str());
                                 }
                             }
                         }
@@ -1415,7 +1416,7 @@
                                     &error);
                             if (icon != "") {
                                 printf("application-icon-%d:'%s'\n", densities[i],
-                                        ResTable::normalizeForOutput(icon.string()).string());
+                                        ResTable::normalizeForOutput(icon.c_str()).c_str());
                             }
                         }
                         assets.setConfiguration(config);
@@ -1423,7 +1424,7 @@
                         String8 icon = AaptXml::getResolvedAttribute(res, tree, ICON_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:icon' attribute: %s", error.string());
+                                    "ERROR getting 'android:icon' attribute: %s", error.c_str());
                             goto bail;
                         }
                         int32_t testOnly = AaptXml::getIntegerAttribute(tree, TEST_ONLY_ATTR, 0,
@@ -1431,7 +1432,7 @@
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
                                     "ERROR getting 'android:testOnly' attribute: %s",
-                                    error.string());
+                                    error.c_str());
                             goto bail;
                         }
 
@@ -1439,15 +1440,15 @@
                                                                        &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:banner' attribute: %s", error.string());
+                                    "ERROR getting 'android:banner' attribute: %s", error.c_str());
                             goto bail;
                         }
                         printf("application: label='%s' ",
-                                ResTable::normalizeForOutput(label.string()).string());
-                        printf("icon='%s'", ResTable::normalizeForOutput(icon.string()).string());
+                                ResTable::normalizeForOutput(label.c_str()).c_str());
+                        printf("icon='%s'", ResTable::normalizeForOutput(icon.c_str()).c_str());
                         if (banner != "") {
                             printf(" banner='%s'",
-                                   ResTable::normalizeForOutput(banner.string()).string());
+                                   ResTable::normalizeForOutput(banner.c_str()).c_str());
                         }
                         printf("\n");
                         if (testOnly != 0) {
@@ -1458,7 +1459,7 @@
                                 ISGAME_ATTR, 0, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:isGame' attribute: %s", error.string());
+                                    "ERROR getting 'android:isGame' attribute: %s", error.c_str());
                             goto bail;
                         }
                         if (isGame != 0) {
@@ -1470,7 +1471,7 @@
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
                                     "ERROR getting 'android:debuggable' attribute: %s",
-                                    error.string());
+                                    error.c_str());
                             goto bail;
                         }
                         if (debuggable != 0) {
@@ -1500,12 +1501,12 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:minSdkVersion' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
                             if (name == "Donut") targetSdk = SDK_DONUT;
                             printf("sdkVersion:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else if (code != -1) {
                             targetSdk = code;
                             printf("sdkVersion:'%d'\n", code);
@@ -1522,7 +1523,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:targetSdkVersion' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
                             if (name == "Donut" && targetSdk < SDK_DONUT) {
@@ -1532,7 +1533,7 @@
                                 targetSdk = SDK_CUR_DEVELOPMENT;
                             }
                             printf("targetSdkVersion:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else if (code != -1) {
                             if (targetSdk < code) {
                                 targetSdk = code;
@@ -1592,7 +1593,7 @@
                         group.label = AaptXml::getResolvedAttribute(res, tree, LABEL_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:label' attribute: %s", error.string());
+                                    "ERROR getting 'android:label' attribute: %s", error.c_str());
                             goto bail;
                         }
                         featureGroups.add(group);
@@ -1608,7 +1609,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "failed to read attribute 'android:required': %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1617,7 +1618,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "failed to read attribute 'android:version': %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1638,7 +1639,7 @@
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -1682,7 +1683,7 @@
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -1701,37 +1702,37 @@
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (name != "" && error == "") {
                             printf("uses-package:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
                     } else if (tag == "original-package") {
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (name != "" && error == "") {
                             printf("original-package:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
                     } else if (tag == "supports-gl-texture") {
                         String8 name = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (name != "" && error == "") {
                             printf("supports-gl-texture:'%s'\n",
-                                    ResTable::normalizeForOutput(name.string()).string());
+                                    ResTable::normalizeForOutput(name.c_str()).c_str());
                         } else {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
                     } else if (tag == "compatible-screens") {
                         printCompatibleScreens(tree, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting compatible screens: %s", error.string());
+                                    "ERROR getting compatible screens: %s", error.c_str());
                             goto bail;
                         }
                         depth--;
@@ -1742,8 +1743,8 @@
                                                                       &error);
                             if (publicKey != "" && error == "") {
                                 printf("package-verifier: name='%s' publicKey='%s'\n",
-                                        ResTable::normalizeForOutput(name.string()).string(),
-                                        ResTable::normalizeForOutput(publicKey.string()).string());
+                                        ResTable::normalizeForOutput(name.c_str()).c_str(),
+                                        ResTable::normalizeForOutput(publicKey.c_str()).c_str());
                             }
                         }
                     }
@@ -1769,7 +1770,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1778,7 +1779,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:label' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1787,7 +1788,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:icon' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1796,7 +1797,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:banner' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -1824,14 +1825,14 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute for uses-library"
-                                        " %s", error.string());
+                                        " %s", error.c_str());
                                 goto bail;
                             }
                             int req = AaptXml::getIntegerAttribute(tree,
                                     REQUIRED_ATTR, 1);
                             printf("uses-library%s:'%s'\n",
                                     req ? "" : "-not-required", ResTable::normalizeForOutput(
-                                            libraryName.string()).string());
+                                            libraryName.c_str()).c_str());
                         } else if (tag == "receiver") {
                             withinReceiver = true;
                             receiverName = AaptXml::getAttribute(tree, NAME_ATTR, &error);
@@ -1839,7 +1840,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute for receiver:"
-                                        " %s", error.string());
+                                        " %s", error.c_str());
                                 goto bail;
                             }
 
@@ -1853,7 +1854,7 @@
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:permission' attribute for"
                                         " receiver '%s': %s",
-                                        receiverName.string(), error.string());
+                                        receiverName.c_str(), error.c_str());
                             }
                         } else if (tag == "service") {
                             withinService = true;
@@ -1862,7 +1863,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute for "
-                                        "service:%s", error.string());
+                                        "service:%s", error.c_str());
                                 goto bail;
                             }
 
@@ -1887,7 +1888,7 @@
                             } else {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:permission' attribute for "
-                                        "service '%s': %s", serviceName.string(), error.string());
+                                        "service '%s': %s", serviceName.c_str(), error.c_str());
                             }
                         } else if (tag == "provider") {
                             withinProvider = true;
@@ -1897,7 +1898,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:exported' attribute for provider:"
-                                        " %s", error.string());
+                                        " %s", error.c_str());
                                 goto bail;
                             }
 
@@ -1906,7 +1907,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:grantUriPermissions' attribute for "
-                                        "provider: %s", error.string());
+                                        "provider: %s", error.c_str());
                                 goto bail;
                             }
 
@@ -1915,7 +1916,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:permission' attribute for "
-                                        "provider: %s", error.string());
+                                        "provider: %s", error.c_str());
                                 goto bail;
                             }
 
@@ -1928,11 +1929,11 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute for "
-                                        "meta-data: %s", error.string());
+                                        "meta-data: %s", error.c_str());
                                 goto bail;
                             }
                             printf("meta-data: name='%s' ",
-                                    ResTable::normalizeForOutput(metaDataName.string()).string());
+                                    ResTable::normalizeForOutput(metaDataName.c_str()).c_str());
                             printResolvedResourceAttribute(res, tree, VALUE_ATTR, String8("value"),
                                     &error);
                             if (error != "") {
@@ -1944,7 +1945,7 @@
                                     SourcePos(manifestFile, tree.getLineNumber()).error(
                                             "ERROR getting 'android:value' or "
                                             "'android:resource' attribute for "
-                                            "meta-data: %s", error.string());
+                                            "meta-data: %s", error.c_str());
                                     goto bail;
                                 }
                             }
@@ -1956,7 +1957,7 @@
                             } else {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:name' attribute: %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
                         }
@@ -1969,13 +1970,13 @@
                             Feature feature(true);
 
                             int32_t featureVers = AaptXml::getIntegerAttribute(
-                                    tree, androidSchema.string(), "version", 0, &error);
+                                    tree, androidSchema.c_str(), "version", 0, &error);
                             if (error == "") {
                                 feature.version = featureVers;
                             } else {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "failed to read attribute 'android:version': %s",
-                                        error.string());
+                                        error.c_str());
                                 goto bail;
                             }
 
@@ -2016,8 +2017,8 @@
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
                                     "ERROR getting 'android:name' attribute for "
-                                    "meta-data tag in service '%s': %s", serviceName.string(),
-                                    error.string());
+                                    "meta-data tag in service '%s': %s", serviceName.c_str(),
+                                    error.c_str());
                             goto bail;
                         }
 
@@ -2034,7 +2035,7 @@
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting 'android:resource' attribute for "
                                         "meta-data tag in service '%s': %s",
-                                        serviceName.string(), error.string());
+                                        serviceName.c_str(), error.c_str());
                                 goto bail;
                             }
 
@@ -2043,7 +2044,7 @@
                             if (error != "") {
                                 SourcePos(manifestFile, tree.getLineNumber()).error(
                                         "ERROR getting AID category for service '%s'",
-                                        serviceName.string());
+                                        serviceName.c_str());
                                 goto bail;
                             }
 
@@ -2064,7 +2065,7 @@
                         action = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'android:name' attribute: %s", error.string());
+                                    "ERROR getting 'android:name' attribute: %s", error.c_str());
                             goto bail;
                         }
 
@@ -2120,7 +2121,7 @@
                         String8 category = AaptXml::getAttribute(tree, NAME_ATTR, &error);
                         if (error != "") {
                             SourcePos(manifestFile, tree.getLineNumber()).error(
-                                    "ERROR getting 'name' attribute: %s", error.string());
+                                    "ERROR getting 'name' attribute: %s", error.c_str());
                             goto bail;
                         }
                         if (withinActivity) {
@@ -2352,7 +2353,7 @@
             printf("locales:");
             const size_t NL = locales.size();
             for (size_t i=0; i<NL; i++) {
-                const char* localeStr =  locales[i].string();
+                const char* localeStr =  locales[i].c_str();
                 if (localeStr == NULL || strlen(localeStr) == 0) {
                     localeStr = "--_--";
                 }
@@ -2373,7 +2374,7 @@
                     SortedVector<String8> architectures;
                     for (size_t i=0; i<dir->getFileCount(); i++) {
                         architectures.add(ResTable::normalizeForOutput(
-                                dir->getFileName(i).string()));
+                                dir->getFileName(i).c_str()));
                     }
 
                     bool outputAltNativeCode = false;
@@ -2401,7 +2402,7 @@
                         }
 
                         if (index >= 0) {
-                            printf("native-code: '%s'\n", architectures[index].string());
+                            printf("native-code: '%s'\n", architectures[index].c_str());
                             architectures.removeAt(index);
                             outputAltNativeCode = true;
                         }
@@ -2414,7 +2415,7 @@
                         }
                         printf("native-code:");
                         for (size_t i = 0; i < archCount; i++) {
-                            printf(" '%s'", architectures[i].string());
+                            printf(" '%s'", architectures[i].c_str());
                         }
                         printf("\n");
                     }
@@ -2428,7 +2429,7 @@
             res.getConfigurations(&configs);
             const size_t N = configs.size();
             for (size_t i=0; i<N; i++) {
-                printf("%s\n", configs[i].toString().string());
+                printf("%s\n", configs[i].toString().c_str());
             }
         } else {
             fprintf(stderr, "ERROR: unknown dump option '%s'\n", option);
@@ -2486,15 +2487,15 @@
     for (int i = 1; i < bundle->getFileSpecCount(); i++) {
         const char* fileName = bundle->getFileSpecEntry(i);
 
-        if (strcasecmp(String8(fileName).getPathExtension().string(), ".gz") == 0) {
+        if (strcasecmp(getPathExtension(String8(fileName)).c_str(), ".gz") == 0) {
             printf(" '%s'... (from gzip)\n", fileName);
-            result = zip->addGzip(fileName, String8(fileName).getBasePath().string(), NULL);
+            result = zip->addGzip(fileName, getBasePath(String8(fileName)).c_str(), NULL);
         } else {
             if (bundle->getJunkPath()) {
-                String8 storageName = String8(fileName).getPathLeaf();
+                String8 storageName = getPathLeaf(String8(fileName));
                 printf(" '%s' as '%s'...\n", fileName,
-                        ResTable::normalizeForOutput(storageName.string()).string());
-                result = zip->add(fileName, storageName.string(),
+                        ResTable::normalizeForOutput(storageName.c_str()).c_str());
+                result = zip->add(fileName, storageName.c_str(),
                                   bundle->getCompressionMethod(), NULL);
             } else {
                 printf(" '%s'...\n", fileName);
@@ -2581,7 +2582,7 @@
     for (size_t i = 0; i < numDirs; i++) {
         bool ignore = ignoreConfig;
         const sp<AaptDir>& subDir = dir->getDirs().valueAt(i);
-        const char* dirStr = subDir->getLeaf().string();
+        const char* dirStr = subDir->getLeaf().c_str();
         if (!ignore && strstr(dirStr, "mipmap") == dirStr) {
             ignore = true;
         }
@@ -2604,7 +2605,7 @@
             }
             if (err != NO_ERROR) {
                 fprintf(stderr, "Failed to add %s (%s) to builder.\n",
-                        gp->getPath().string(), gp->getFiles()[j]->getPrintableSource().string());
+                        gp->getPath().c_str(), gp->getFiles()[j]->getPrintableSource().c_str());
                 return err;
             }
         }
@@ -2617,16 +2618,16 @@
         return original;
     }
 
-    String8 ext(original.getPathExtension());
+    String8 ext(getPathExtension(original));
     if (ext == String8(".apk")) {
         return String8::format("%s_%s%s",
-                original.getBasePath().string(),
-                split->getDirectorySafeName().string(),
-                ext.string());
+                getBasePath(original).c_str(),
+                split->getDirectorySafeName().c_str(),
+                ext.c_str());
     }
 
-    return String8::format("%s_%s", original.string(),
-            split->getDirectorySafeName().string());
+    return String8::format("%s_%s", original.c_str(),
+            split->getDirectorySafeName().c_str());
 }
 
 /*
@@ -2712,7 +2713,7 @@
         for (size_t i = 0; i < numSplits; i++) {
             std::set<ConfigDescription> configs;
             if (!AaptConfig::parseCommaSeparatedList(splitStrs[i], &configs)) {
-                fprintf(stderr, "ERROR: failed to parse split configuration '%s'\n", splitStrs[i].string());
+                fprintf(stderr, "ERROR: failed to parse split configuration '%s'\n", splitStrs[i].c_str());
                 goto bail;
             }
 
@@ -2756,10 +2757,10 @@
             // generate the dependency file in the R.java package subdirectory
             // e.g. gen/com/foo/app/R.java.d
             dependencyFile = String8(bundle->getRClassDir());
-            dependencyFile.appendPath("R.java.d");
+            appendPath(dependencyFile, "R.java.d");
         }
         // Make sure we have a clean dependency file to start with
-        fp = fopen(dependencyFile, "w");
+        fp = fopen(dependencyFile.c_str(), "w");
         fclose(fp);
     }
 
@@ -2835,7 +2836,7 @@
             String8 outputPath = buildApkName(String8(outputAPKFile), split);
             err = writeAPK(bundle, outputPath, split);
             if (err != NO_ERROR) {
-                fprintf(stderr, "ERROR: packaging of '%s' failed\n", outputPath.string());
+                fprintf(stderr, "ERROR: packaging of '%s' failed\n", outputPath.c_str());
                 goto bail;
             }
         }
@@ -2848,7 +2849,7 @@
     if (bundle->getGenDependencies()) {
         // Now that writeResourceSymbols or writeAPK has taken care of writing
         // the targets to our dependency file, we'll write the prereqs
-        fp = fopen(dependencyFile, "a+");
+        fp = fopen(dependencyFile.c_str(), "a+");
         fprintf(fp, " : ");
         bool includeRaw = (outputAPKFile != NULL);
         err = writeDependencyPreReqs(bundle, assets, fp, includeRaw);
diff --git a/tools/aapt/CrunchCache.cpp b/tools/aapt/CrunchCache.cpp
index 7b8a576..e731ce0 100644
--- a/tools/aapt/CrunchCache.cpp
+++ b/tools/aapt/CrunchCache.cpp
@@ -5,6 +5,7 @@
 // This file defines functions laid out and documented in
 // CrunchCache.h
 
+#include <androidfw/PathUtils.h>
 #include <utils/Compat.h>
 #include <utils/Vector.h>
 #include <utils/String8.h>
@@ -44,7 +45,7 @@
         // This efficiently strips the source directory prefix from our path.
         // Also, String8 doesn't have a substring method so this is what we've
         // got to work with.
-        const char* rPathPtr = mSourceFiles.keyAt(0).string()+mSourcePath.length();
+        const char* rPathPtr = mSourceFiles.keyAt(0).c_str()+mSourcePath.length();
         // Strip leading slash if present
         int offset = 0;
         if (rPathPtr[0] == OS_PATH_SEPARATOR)
@@ -52,15 +53,15 @@
         relativePath = String8(rPathPtr + offset);
 
         if (forceOverwrite || needsUpdating(relativePath)) {
-            cu->processImage(mSourcePath.appendPathCopy(relativePath),
-                             mDestPath.appendPathCopy(relativePath));
+            cu->processImage(appendPathCopy(mSourcePath, relativePath),
+                             appendPathCopy(mDestPath, relativePath));
             numFilesUpdated++;
             // crunchFile(relativePath);
         }
         // Delete this file from the source files and (if it exists) from the
         // dest files.
         mSourceFiles.removeItemsAt(0);
-        mDestFiles.removeItem(mDestPath.appendPathCopy(relativePath));
+        mDestFiles.removeItem(appendPathCopy(mDestPath, relativePath));
     }
 
     // Iterate through what's left of destFiles and delete leftovers
@@ -99,7 +100,7 @@
     // Retrieve modification dates for this file entry under the source and
     // cache directory trees. The vectors will return a modification date of 0
     // if the file doesn't exist.
-    time_t sourceDate = mSourceFiles.valueFor(mSourcePath.appendPathCopy(relativePath));
-    time_t destDate = mDestFiles.valueFor(mDestPath.appendPathCopy(relativePath));
+    time_t sourceDate = mSourceFiles.valueFor(appendPathCopy(mSourcePath, relativePath));
+    time_t destDate = mDestFiles.valueFor(appendPathCopy(mDestPath, relativePath));
     return sourceDate > destDate;
 }
diff --git a/tools/aapt/DirectoryWalker.h b/tools/aapt/DirectoryWalker.h
index 88031d0..7f60d4d 100644
--- a/tools/aapt/DirectoryWalker.h
+++ b/tools/aapt/DirectoryWalker.h
@@ -7,6 +7,7 @@
 #ifndef DIRECTORYWALKER_H
 #define DIRECTORYWALKER_H
 
+#include <androidfw/PathUtils.h>
 #include <dirent.h>
 #include <sys/types.h>
 #include <sys/param.h>
@@ -57,7 +58,7 @@
     virtual bool openDir(String8 path) {
         mBasePath = path;
         dir = NULL;
-        dir = opendir(mBasePath.string() );
+        dir = opendir(mBasePath.c_str() );
 
         if (dir == NULL)
             return false;
@@ -77,8 +78,8 @@
 
         mEntry = *entryPtr;
         // Get stats
-        String8 fullPath = mBasePath.appendPathCopy(mEntry.d_name);
-        stat(fullPath.string(),&mStats);
+        String8 fullPath = appendPathCopy(mBasePath, mEntry.d_name);
+        stat(fullPath.c_str(),&mStats);
         return &mEntry;
     };
     // Get the stats for the current entry
diff --git a/tools/aapt/FileFinder.cpp b/tools/aapt/FileFinder.cpp
index c9d0744..69a8fa9 100644
--- a/tools/aapt/FileFinder.cpp
+++ b/tools/aapt/FileFinder.cpp
@@ -5,6 +5,7 @@
 // File Finder implementation.
 // Implementation for the functions declared and documented in FileFinder.h
 
+#include <androidfw/PathUtils.h>
 #include <utils/Vector.h>
 #include <utils/String8.h>
 #include <utils/KeyedVector.h>
@@ -57,16 +58,16 @@
         if (entry->d_name[0] == '.') // Skip hidden files and directories
             continue;
 
-        String8 fullPath = basePath.appendPathCopy(entryName);
+        String8 fullPath = appendPathCopy(basePath, entryName);
         // If this entry is a directory we'll recurse into it
-        if (isDirectory(fullPath.string()) ) {
+        if (isDirectory(fullPath.c_str()) ) {
             DirectoryWalker* copy = dw->clone();
             findFiles(fullPath, extensions, fileStore,copy);
             delete copy;
         }
 
         // If this entry is a file, we'll pass it over to checkAndAddFile
-        if (isFile(fullPath.string()) ) {
+        if (isFile(fullPath.c_str()) ) {
             checkAndAddFile(fullPath,dw->entryStats(),extensions,fileStore);
         }
     }
@@ -83,10 +84,10 @@
 {
     // Loop over the extensions, checking for a match
     bool done = false;
-    String8 ext(path.getPathExtension());
+    String8 ext(getPathExtension(path));
     ext.toLower();
     for (size_t i = 0; i < extensions.size() && !done; ++i) {
-        String8 ext2 = extensions[i].getPathExtension();
+        String8 ext2 = getPathExtension(extensions[i]);
         ext2.toLower();
         // Compare the extensions. If a match is found, add to storage.
         if (ext == ext2) {
diff --git a/tools/aapt/Images.cpp b/tools/aapt/Images.cpp
index 627a231..cd4de90 100644
--- a/tools/aapt/Images.cpp
+++ b/tools/aapt/Images.cpp
@@ -8,6 +8,7 @@
 
 #include "Images.h"
 
+#include <androidfw/PathUtils.h>
 #include <androidfw/ResourceTypes.h>
 #include <utils/ByteOrder.h>
 
@@ -1328,13 +1329,13 @@
 
     png_init_io(read_ptr, fp);
 
-    read_png(printableName.string(), read_ptr, read_info, imageInfo);
+    read_png(printableName.c_str(), read_ptr, read_info, imageInfo);
 
     const size_t nameLen = file->getPath().length();
     if (nameLen > 6) {
-        const char* name = file->getPath().string();
+        const char* name = file->getPath().c_str();
         if (name[nameLen-5] == '9' && name[nameLen-6] == '.') {
-            if (do_9patch(printableName.string(), imageInfo) != NO_ERROR) {
+            if (do_9patch(printableName.c_str(), imageInfo) != NO_ERROR) {
                 return false;
             }
         }
@@ -1349,7 +1350,7 @@
         return false;
     }
 
-    write_png(printableName.string(), write_ptr, write_info, *imageInfo, bundle);
+    write_png(printableName.c_str(), write_ptr, write_info, *imageInfo, bundle);
 
     return true;
 }
@@ -1357,10 +1358,10 @@
 status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& /* assets */,
                          const sp<AaptFile>& file, String8* /* outNewLeafName */)
 {
-    String8 ext(file->getPath().getPathExtension());
+    String8 ext(getPathExtension(file->getPath()));
 
     // We currently only process PNG images.
-    if (strcmp(ext.string(), ".png") != 0) {
+    if (strcmp(ext.c_str(), ".png") != 0) {
         return NO_ERROR;
     }
 
@@ -1371,7 +1372,7 @@
     String8 printableName(file->getPrintableSource());
 
     if (bundle->getVerbose()) {
-        printf("Processing image: %s\n", printableName.string());
+        printf("Processing image: %s\n", printableName.c_str());
     }
 
     png_structp read_ptr = NULL;
@@ -1385,9 +1386,9 @@
 
     status_t error = UNKNOWN_ERROR;
 
-    fp = fopen(file->getSourceFile().string(), "rb");
+    fp = fopen(file->getSourceFile().c_str(), "rb");
     if (fp == NULL) {
-        fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.string());
+        fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.c_str());
         goto bail;
     }
 
@@ -1434,7 +1435,7 @@
         size_t newSize = file->getSize();
         float factor = ((float)newSize)/oldSize;
         int percent = (int)(factor*100);
-        printf("    (processed image %s: %d%% size of source)\n", printableName.string(), percent);
+        printf("    (processed image %s: %d%% size of source)\n", printableName.c_str(), percent);
     }
 
 bail:
@@ -1450,7 +1451,7 @@
 
     if (error != NO_ERROR) {
         fprintf(stderr, "ERROR: Failure processing PNG image %s\n",
-                file->getPrintableSource().string());
+                file->getPrintableSource().c_str());
     }
     return error;
 }
@@ -1470,13 +1471,13 @@
     status_t error = UNKNOWN_ERROR;
 
     if (bundle->getVerbose()) {
-        printf("Processing image to cache: %s => %s\n", source.string(), dest.string());
+        printf("Processing image to cache: %s => %s\n", source.c_str(), dest.c_str());
     }
 
     // Get a file handler to read from
-    fp = fopen(source.string(),"rb");
+    fp = fopen(source.c_str(),"rb");
     if (fp == NULL) {
-        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", source.string());
+        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", source.c_str());
         return error;
     }
 
@@ -1507,7 +1508,7 @@
     png_init_io(read_ptr,fp);
 
     // Actually read data from the file
-    read_png(source.string(), read_ptr, read_info, &imageInfo);
+    read_png(source.c_str(), read_ptr, read_info, &imageInfo);
 
     // We're done reading so we can clean up
     // Find old file size before releasing handle
@@ -1518,8 +1519,8 @@
 
     // Check to see if we're dealing with a 9-patch
     // If we are, process appropriately
-    if (source.getBasePath().getPathExtension() == ".9")  {
-        if (do_9patch(source.string(), &imageInfo) != NO_ERROR) {
+    if (getPathExtension(getBasePath(source)) == ".9")  {
+        if (do_9patch(source.c_str(), &imageInfo) != NO_ERROR) {
             return error;
         }
     }
@@ -1541,9 +1542,9 @@
     }
 
     // Open up our destination file for writing
-    fp = fopen(dest.string(), "wb");
+    fp = fopen(dest.c_str(), "wb");
     if (!fp) {
-        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", dest.string());
+        fprintf(stderr, "%s ERROR: Unable to open PNG file\n", dest.c_str());
         png_destroy_write_struct(&write_ptr, &write_info);
         return error;
     }
@@ -1559,11 +1560,11 @@
     }
 
     // Actually write out to the new png
-    write_png(dest.string(), write_ptr, write_info, imageInfo, bundle);
+    write_png(dest.c_str(), write_ptr, write_info, imageInfo, bundle);
 
     if (bundle->getVerbose()) {
         // Find the size of our new file
-        FILE* reader = fopen(dest.string(), "rb");
+        FILE* reader = fopen(dest.c_str(), "rb");
         fseek(reader, 0, SEEK_END);
         size_t newSize = (size_t)ftell(reader);
         fclose(reader);
@@ -1571,7 +1572,7 @@
         float factor = ((float)newSize)/oldSize;
         int percent = (int)(factor*100);
         printf("  (processed image to cache entry %s: %d%% size of source)\n",
-               dest.string(), percent);
+               dest.c_str(), percent);
     }
 
     //Clean up
@@ -1584,12 +1585,12 @@
 status_t postProcessImage(const Bundle* bundle, const sp<AaptAssets>& assets,
                           ResourceTable* table, const sp<AaptFile>& file)
 {
-    String8 ext(file->getPath().getPathExtension());
+    String8 ext(getPathExtension(file->getPath()));
 
     // At this point, now that we have all the resource data, all we need to
     // do is compile XML files.
-    if (strcmp(ext.string(), ".xml") == 0) {
-        String16 resourceName(parseResourceName(file->getSourceFile().getPathLeaf()));
+    if (strcmp(ext.c_str(), ".xml") == 0) {
+        String16 resourceName(parseResourceName(getPathLeaf(file->getSourceFile())));
         return compileXmlFile(bundle, assets, resourceName, file, table);
     }
 
diff --git a/tools/aapt/Package.cpp b/tools/aapt/Package.cpp
index f06643dc..5e0f87f 100644
--- a/tools/aapt/Package.cpp
+++ b/tools/aapt/Package.cpp
@@ -8,7 +8,9 @@
 #include "OutputSet.h"
 #include "ResourceTable.h"
 #include "ResourceFilter.h"
+#include "Utils.h"
 
+#include <androidfw/PathUtils.h>
 #include <androidfw/misc.h>
 
 #include <utils/Log.h>
@@ -69,39 +71,39 @@
      * If "update" is set, update the contents of the existing archive.
      * Else, if "force" is set, remove the existing archive.
      */
-    FileType fileType = getFileType(outputFile.string());
+    FileType fileType = getFileType(outputFile.c_str());
     if (fileType == kFileTypeNonexistent) {
         // okay, create it below
     } else if (fileType == kFileTypeRegular) {
         if (bundle->getUpdate()) {
             // okay, open it below
         } else if (bundle->getForce()) {
-            if (unlink(outputFile.string()) != 0) {
-                fprintf(stderr, "ERROR: unable to remove '%s': %s\n", outputFile.string(),
+            if (unlink(outputFile.c_str()) != 0) {
+                fprintf(stderr, "ERROR: unable to remove '%s': %s\n", outputFile.c_str(),
                         strerror(errno));
                 goto bail;
             }
         } else {
             fprintf(stderr, "ERROR: '%s' exists (use '-f' to force overwrite)\n",
-                    outputFile.string());
+                    outputFile.c_str());
             goto bail;
         }
     } else {
-        fprintf(stderr, "ERROR: '%s' exists and is not a regular file\n", outputFile.string());
+        fprintf(stderr, "ERROR: '%s' exists and is not a regular file\n", outputFile.c_str());
         goto bail;
     }
 
     if (bundle->getVerbose()) {
         printf("%s '%s'\n", (fileType == kFileTypeNonexistent) ? "Creating" : "Opening",
-                outputFile.string());
+                outputFile.c_str());
     }
 
     status_t status;
     zip = new ZipFile;
-    status = zip->open(outputFile.string(), ZipFile::kOpenReadWrite | ZipFile::kOpenCreate);
+    status = zip->open(outputFile.c_str(), ZipFile::kOpenReadWrite | ZipFile::kOpenCreate);
     if (status != NO_ERROR) {
         fprintf(stderr, "ERROR: unable to open '%s' as Zip file for writing\n",
-                outputFile.string());
+                outputFile.c_str());
         goto bail;
     }
 
@@ -112,7 +114,7 @@
     count = processAssets(bundle, zip, outputSet);
     if (count < 0) {
         fprintf(stderr, "ERROR: unable to process assets while packaging '%s'\n",
-                outputFile.string());
+                outputFile.c_str());
         result = count;
         goto bail;
     }
@@ -124,7 +126,7 @@
     count = processJarFiles(bundle, zip);
     if (count < 0) {
         fprintf(stderr, "ERROR: unable to process jar files while packaging '%s'\n",
-                outputFile.string());
+                outputFile.c_str());
         result = count;
         goto bail;
     }
@@ -169,12 +171,12 @@
     /* anything here? */
     if (zip->getNumEntries() == 0) {
         if (bundle->getVerbose()) {
-            printf("Archive is empty -- removing %s\n", outputFile.getPathLeaf().string());
+            printf("Archive is empty -- removing %s\n", getPathLeaf(outputFile).c_str());
         }
         delete zip;        // close the file so we can remove it in Win32
         zip = NULL;
-        if (unlink(outputFile.string()) != 0) {
-            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string());
+        if (unlink(outputFile.c_str()) != 0) {
+            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.c_str());
         }
     }
 
@@ -187,9 +189,9 @@
         String8 dependencyFile = outputFile;
         dependencyFile.append(".d");
 
-        FILE* fp = fopen(dependencyFile.string(), "a");
+        FILE* fp = fopen(dependencyFile.c_str(), "a");
         // Add this file to the dependency file
-        fprintf(fp, "%s \\\n", outputFile.string());
+        fprintf(fp, "%s \\\n", outputFile.c_str());
         fclose(fp);
     }
 
@@ -199,10 +201,10 @@
     delete zip;        // must close before remove in Win32
     if (result != NO_ERROR) {
         if (bundle->getVerbose()) {
-            printf("Removing %s due to earlier failures\n", outputFile.string());
+            printf("Removing %s due to earlier failures\n", outputFile.c_str());
         }
-        if (unlink(outputFile.string()) != 0) {
-            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.string());
+        if (unlink(outputFile.c_str()) != 0) {
+            fprintf(stderr, "warning: could not unlink '%s'\n", outputFile.c_str());
         }
     }
 
@@ -226,7 +228,7 @@
             fprintf(stderr, "warning: null file being processed.\n");
         } else {
             String8 storagePath(entry.getPath());
-            storagePath.convertToResPath();
+            convertToResPath(storagePath);
             if (!processFile(bundle, zip, storagePath, entry.getFile())) {
                 return UNKNOWN_ERROR;
             }
@@ -267,31 +269,31 @@
     int fileNameLen = storageName.length();
     int excludeExtensionLen = strlen(kExcludeExtension);
     if (fileNameLen > excludeExtensionLen
-            && (0 == strcmp(storageName.string() + (fileNameLen - excludeExtensionLen),
+            && (0 == strcmp(storageName.c_str() + (fileNameLen - excludeExtensionLen),
                             kExcludeExtension))) {
-        fprintf(stderr, "warning: '%s' not added to Zip\n", storageName.string());
+        fprintf(stderr, "warning: '%s' not added to Zip\n", storageName.c_str());
         return true;
     }
 
-    if (strcasecmp(storageName.getPathExtension().string(), ".gz") == 0) {
+    if (strcasecmp(getPathExtension(storageName).c_str(), ".gz") == 0) {
         fromGzip = true;
-        storageName = storageName.getBasePath();
+        storageName = getBasePath(storageName);
     }
 
     if (bundle->getUpdate()) {
-        entry = zip->getEntryByName(storageName.string());
+        entry = zip->getEntryByName(storageName.c_str());
         if (entry != NULL) {
             /* file already exists in archive; there can be only one */
             if (entry->getMarked()) {
                 fprintf(stderr,
                         "ERROR: '%s' exists twice (check for with & w/o '.gz'?)\n",
-                        file->getPrintableSource().string());
+                        file->getPrintableSource().c_str());
                 return false;
             }
             if (!hasData) {
                 const String8& srcName = file->getSourceFile();
                 time_t fileModWhen;
-                fileModWhen = getFileModDate(srcName.string());
+                fileModWhen = getFileModDate(srcName.c_str());
                 if (fileModWhen == (time_t) -1) { // file existence tested earlier,
                     return false;                 //  not expecting an error here
                 }
@@ -299,14 +301,14 @@
                 if (fileModWhen > entry->getModWhen()) {
                     // mark as deleted so add() will succeed
                     if (bundle->getVerbose()) {
-                        printf("      (removing old '%s')\n", storageName.string());
+                        printf("      (removing old '%s')\n", storageName.c_str());
                     }
     
                     zip->remove(entry);
                 } else {
                     // version in archive is newer
                     if (bundle->getVerbose()) {
-                        printf("      (not updating '%s')\n", storageName.string());
+                        printf("      (not updating '%s')\n", storageName.c_str());
                     }
                     entry->setMarked(true);
                     return true;
@@ -321,22 +323,22 @@
     //android_setMinPriority(NULL, ANDROID_LOG_VERBOSE);
 
     if (fromGzip) {
-        result = zip->addGzip(file->getSourceFile().string(), storageName.string(), &entry);
+        result = zip->addGzip(file->getSourceFile().c_str(), storageName.c_str(), &entry);
     } else if (!hasData) {
         /* don't compress certain files, e.g. PNGs */
         int compressionMethod = bundle->getCompressionMethod();
         if (!okayToCompress(bundle, storageName)) {
             compressionMethod = ZipEntry::kCompressStored;
         }
-        result = zip->add(file->getSourceFile().string(), storageName.string(), compressionMethod,
+        result = zip->add(file->getSourceFile().c_str(), storageName.c_str(), compressionMethod,
                             &entry);
     } else {
-        result = zip->add(file->getData(), file->getSize(), storageName.string(),
+        result = zip->add(file->getData(), file->getSize(), storageName.c_str(),
                            file->getCompressionMethod(), &entry);
     }
     if (result == NO_ERROR) {
         if (bundle->getVerbose()) {
-            printf("      '%s'%s", storageName.string(), fromGzip ? " (from .gz)" : "");
+            printf("      '%s'%s", storageName.c_str(), fromGzip ? " (from .gz)" : "");
             if (entry->getCompressionMethod() == ZipEntry::kCompressStored) {
                 printf(" (not compressed)\n");
             } else {
@@ -348,10 +350,10 @@
     } else {
         if (result == ALREADY_EXISTS) {
             fprintf(stderr, "      Unable to add '%s': file already in archive (try '-u'?)\n",
-                    file->getPrintableSource().string());
+                    file->getPrintableSource().c_str());
         } else {
             fprintf(stderr, "      Unable to add '%s': Zip add failed (%d)\n",
-                    file->getPrintableSource().string(), result);
+                    file->getPrintableSource().c_str(), result);
         }
         return false;
     }
@@ -365,14 +367,14 @@
  */
 bool okayToCompress(Bundle* bundle, const String8& pathName)
 {
-    String8 ext = pathName.getPathExtension();
+    String8 ext = getPathExtension(pathName);
     int i;
 
     if (ext.length() == 0)
         return true;
 
     for (i = 0; i < NELEM(kNoCompressExt); i++) {
-        if (strcasecmp(ext.string(), kNoCompressExt[i]) == 0)
+        if (strcasecmp(ext.c_str(), kNoCompressExt[i]) == 0)
             return false;
     }
 
@@ -383,7 +385,7 @@
         if (pos < 0) {
             continue;
         }
-        const char* path = pathName.string();
+        const char* path = pathName.c_str();
         if (strcasecmp(path + pos, str) == 0) {
             return false;
         }
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index dd3ebdb..7e4e186 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -15,9 +15,12 @@
 #include "ResourceTable.h"
 #include "StringPool.h"
 #include "Symbol.h"
+#include "Utils.h"
 #include "WorkQueue.h"
 #include "XMLNode.h"
 
+#include <androidfw/PathUtils.h>
+
 #include <algorithm>
 
 // STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
@@ -57,8 +60,8 @@
 
 String8 parseResourceName(const String8& leaf)
 {
-    const char* firstDot = strchr(leaf.string(), '.');
-    const char* str = leaf.string();
+    const char* firstDot = strchr(leaf.c_str(), '.');
+    const char* str = leaf.c_str();
 
     if (firstDot) {
         return String8(str, firstDot-str);
@@ -132,7 +135,7 @@
             mParams = file->getGroupEntry().toParams();
             if (kIsDebug) {
                 printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n",
-                        group->getPath().string(), mParams.mcc, mParams.mnc,
+                        group->getPath().c_str(), mParams.mcc, mParams.mnc,
                         mParams.language[0] ? mParams.language[0] : '-',
                         mParams.language[1] ? mParams.language[1] : '-',
                         mParams.country[0] ? mParams.country[0] : '-',
@@ -142,17 +145,17 @@
                         mParams.inputFlags, mParams.navigation);
             }
             mPath = "res";
-            mPath.appendPath(file->getGroupEntry().toDirName(mResType));
-            mPath.appendPath(leaf);
+            appendPath(mPath, file->getGroupEntry().toDirName(mResType));
+            appendPath(mPath, leaf);
             mBaseName = parseResourceName(leaf);
             if (mBaseName == "") {
                 fprintf(stderr, "Error: malformed resource filename %s\n",
-                        file->getPrintableSource().string());
+                        file->getPrintableSource().c_str());
                 return UNKNOWN_ERROR;
             }
 
             if (kIsDebug) {
-                printf("file name=%s\n", mBaseName.string());
+                printf("file name=%s\n", mBaseName.c_str());
             }
 
             return NO_ERROR;
@@ -222,7 +225,7 @@
 {
     if (grp->getFiles().size() != 1) {
         fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
-                grp->getFiles().valueAt(0)->getPrintableSource().string());
+                grp->getFiles().valueAt(0)->getPrintableSource().c_str());
     }
 
     sp<AaptFile> file = grp->getFiles().valueAt(0);
@@ -243,20 +246,20 @@
     size_t len;
     if (code != ResXMLTree::START_TAG) {
         fprintf(stderr, "%s:%d: No start tag found\n",
-                file->getPrintableSource().string(), block.getLineNumber());
+                file->getPrintableSource().c_str(), block.getLineNumber());
         return UNKNOWN_ERROR;
     }
-    if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
+    if (strcmp16(block.getElementName(&len), String16("manifest").c_str()) != 0) {
         fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
-                file->getPrintableSource().string(), block.getLineNumber(),
-                String8(block.getElementName(&len)).string());
+                file->getPrintableSource().c_str(), block.getLineNumber(),
+                String8(block.getElementName(&len)).c_str());
         return UNKNOWN_ERROR;
     }
 
     ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
     if (nameIndex < 0) {
         fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
-                file->getPrintableSource().string(), block.getLineNumber());
+                file->getPrintableSource().c_str(), block.getLineNumber());
         return UNKNOWN_ERROR;
     }
 
@@ -264,19 +267,19 @@
 
     ssize_t revisionCodeIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "revisionCode");
     if (revisionCodeIndex >= 0) {
-        bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).string());
+        bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).c_str());
     }
 
     String16 uses_sdk16("uses-sdk");
     while ((code=block.next()) != ResXMLTree::END_DOCUMENT
            && code != ResXMLTree::BAD_DOCUMENT) {
         if (code == ResXMLTree::START_TAG) {
-            if (strcmp16(block.getElementName(&len), uses_sdk16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), uses_sdk16.c_str()) == 0) {
                 ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
                                                              "minSdkVersion");
                 if (minSdkIndex >= 0) {
                     const char16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
-                    const char* minSdk8 = strdup(String8(minSdk16).string());
+                    const char* minSdk8 = strdup(String8(minSdk16).c_str());
                     bundle->setManifestMinSdkVersion(minSdk8);
                 }
             }
@@ -305,23 +308,23 @@
     while ((res=it.next()) == NO_ERROR) {
         if (bundle->getVerbose()) {
             printf("    (new resource id %s from %s)\n",
-                   it.getBaseName().string(), it.getFile()->getPrintableSource().string());
+                   it.getBaseName().c_str(), it.getFile()->getPrintableSource().c_str());
         }
         String16 baseName(it.getBaseName());
-        const char16_t* str = baseName.string();
+        const char16_t* str = baseName.c_str();
         const char16_t* const end = str + baseName.size();
         while (str < end) {
             if (!((*str >= 'a' && *str <= 'z')
                     || (*str >= '0' && *str <= '9')
                     || *str == '_' || *str == '.')) {
                 fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
-                        it.getPath().string());
+                        it.getPath().c_str());
                 hasErrors = true;
             }
             str++;
         }
         String8 resPath = it.getPath();
-        resPath.convertToResPath();
+        convertToResPath(resPath);
         status_t result = table->addEntry(SourcePos(it.getPath(), 0),
                         String16(assets->getPackage()),
                         type16,
@@ -413,7 +416,7 @@
             sp<ResourceTypeSet> set = new ResourceTypeSet();
             if (kIsDebug) {
                 printf("Creating new resource type set for leaf %s with group %s (%p)\n",
-                        leafName.string(), group->getPath().string(), group.get());
+                        leafName.c_str(), group->getPath().c_str(), group.get());
             }
             set->add(leafName, group);
             resources->add(resType, set);
@@ -423,21 +426,21 @@
             if (index < 0) {
                 if (kIsDebug) {
                     printf("Adding to resource type set for leaf %s group %s (%p)\n",
-                            leafName.string(), group->getPath().string(), group.get());
+                            leafName.c_str(), group->getPath().c_str(), group.get());
                 }
                 set->add(leafName, group);
             } else {
                 sp<AaptGroup> existingGroup = set->valueAt(index);
                 if (kIsDebug) {
                     printf("Extending to resource type set for leaf %s group %s (%p)\n",
-                            leafName.string(), group->getPath().string(), group.get());
+                            leafName.c_str(), group->getPath().c_str(), group.get());
                 }
                 for (size_t j=0; j<files.size(); j++) {
                     if (kIsDebug) {
                         printf("Adding file %s in group %s resType %s\n",
-                                files.valueAt(j)->getSourceFile().string(),
-                                files.keyAt(j).toDirName(String8()).string(),
-                                resType.string());
+                                files.valueAt(j)->getSourceFile().c_str(),
+                                files.keyAt(j).toDirName(String8()).c_str(),
+                                resType.c_str());
                     }
                     existingGroup->addFile(files.valueAt(j));
                 }
@@ -455,14 +458,14 @@
     for (int i=0; i<N; i++) {
         const sp<AaptDir>& d = dirs.itemAt(i);
         if (kIsDebug) {
-            printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
-                    d->getLeaf().string());
+            printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().c_str(),
+                    d->getLeaf().c_str());
         }
         collect_files(d, resources);
 
         // don't try to include the res dir
         if (kIsDebug) {
-            printf("Removing dir leaf %s\n", d->getLeaf().string());
+            printf("Removing dir leaf %s\n", d->getLeaf().c_str());
         }
         ass->removeDir(d->getLeaf());
     }
@@ -490,8 +493,8 @@
             int strIdx;
             if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
                 fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
-                        path.string(), parser.getLineNumber(),
-                        String8(parser.getElementName(&len)).string(), attr,
+                        path.c_str(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).c_str(), attr,
                         value.data);
                 return ATTR_NOT_FOUND;
             }
@@ -502,12 +505,12 @@
                 str = pool->stringAt(value.data, &len);
             }
             printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
-                    specFlags, strIdx, str != NULL ? String8(str).string() : "???");
+                    specFlags, strIdx, str != NULL ? String8(str).c_str() : "???");
             #endif
             if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
                 fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
-                        path.string(), parser.getLineNumber(),
-                        String8(parser.getElementName(&len)).string(), attr,
+                        path.c_str(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).c_str(), attr,
                         specFlags);
                 return ATTR_NOT_FOUND;
             }
@@ -515,20 +518,20 @@
         if (value.dataType == Res_value::TYPE_STRING) {
             if (pool == NULL) {
                 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
-                        path.string(), parser.getLineNumber(),
-                        String8(parser.getElementName(&len)).string(), attr);
+                        path.c_str(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).c_str(), attr);
                 return ATTR_NOT_FOUND;
             }
             if ((str = UnpackOptionalString(pool->stringAt(value.data), &len)) == NULL) {
                 fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
-                        path.string(), parser.getLineNumber(),
-                        String8(parser.getElementName(&len)).string(), attr);
+                        path.c_str(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).c_str(), attr);
                 return ATTR_NOT_FOUND;
             }
         } else {
             fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
-                    path.string(), parser.getLineNumber(),
-                    String8(parser.getElementName(&len)).string(), attr,
+                    path.c_str(), parser.getLineNumber(),
+                    String8(parser.getElementName(&len)).c_str(), attr,
                     value.dataType);
             return ATTR_NOT_FOUND;
         }
@@ -546,30 +549,30 @@
                 }
                 if (!okay) {
                     fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
-                            path.string(), parser.getLineNumber(),
-                            String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
+                            path.c_str(), parser.getLineNumber(),
+                            String8(parser.getElementName(&len)).c_str(), attr, (char)str[i]);
                     return (int)i;
                 }
             }
         }
         if (*str == ' ') {
             fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
-                    path.string(), parser.getLineNumber(),
-                    String8(parser.getElementName(&len)).string(), attr);
+                    path.c_str(), parser.getLineNumber(),
+                    String8(parser.getElementName(&len)).c_str(), attr);
             return ATTR_LEADING_SPACES;
         }
         if (len != 0 && str[len-1] == ' ') {
             fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
-                    path.string(), parser.getLineNumber(),
-                    String8(parser.getElementName(&len)).string(), attr);
+                    path.c_str(), parser.getLineNumber(),
+                    String8(parser.getElementName(&len)).c_str(), attr);
             return ATTR_TRAILING_SPACES;
         }
         return ATTR_OKAY;
     }
     if (required) {
         fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
-                path.string(), parser.getLineNumber(),
-                String8(parser.getElementName(&len)).string(), attr);
+                path.c_str(), parser.getLineNumber(),
+                String8(parser.getElementName(&len)).c_str(), attr);
         return ATTR_NOT_FOUND;
     }
     return ATTR_OKAY;
@@ -584,7 +587,7 @@
             ssize_t index = parser.indexOfAttribute(NULL, "id");
             if (index >= 0) {
                 fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
-                        path.string(), parser.getLineNumber());
+                        path.c_str(), parser.getLineNumber());
             }
         }
     }
@@ -618,7 +621,7 @@
             size_t overlayCount = overlaySet->size();
             for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
                 if (bundle->getVerbose()) {
-                    printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string());
+                    printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).c_str());
                 }
                 ssize_t baseIndex = -1;
                 if (baseSet->get() != NULL) {
@@ -638,11 +641,11 @@
                                 baseGroup->getFiles();
                         for (size_t i=0; i < baseFiles.size(); i++) {
                             printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
-                                    baseFiles.keyAt(i).toString().string());
+                                    baseFiles.keyAt(i).toString().c_str());
                         }
                         for (size_t i=0; i < overlayFiles.size(); i++) {
                             printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
-                                    overlayFiles.keyAt(i).toString().string());
+                                    overlayFiles.keyAt(i).toString().c_str());
                         }
                     }
 
@@ -657,16 +660,16 @@
                             if (bundle->getVerbose()) {
                                 printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
                                         (ZD_TYPE) baseFileIndex,
-                                        overlayGroup->getLeaf().string(),
-                                        overlayFiles.keyAt(overlayGroupIndex).toString().string());
+                                        overlayGroup->getLeaf().c_str(),
+                                        overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
                             }
                             baseGroup->removeFile(baseFileIndex);
                         } else {
                             // didn't find a match fall through and add it..
                             if (true || bundle->getVerbose()) {
                                 printf("nothing matches overlay file %s, for flavor %s\n",
-                                        overlayGroup->getLeaf().string(),
-                                        overlayFiles.keyAt(overlayGroupIndex).toString().string());
+                                        overlayGroup->getLeaf().c_str(),
+                                        overlayFiles.keyAt(overlayGroupIndex).toString().c_str());
                             }
                         }
                         baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
@@ -728,7 +731,7 @@
         if (errorOnFailedInsert) {
             fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
                             " cannot insert new value %s.\n",
-                    String8(attr).string(), String8(ns).string(), value);
+                    String8(attr).c_str(), String8(ns).c_str(), value);
             return false;
         }
 
@@ -763,7 +766,7 @@
         // .asdf  .a.b  --> package.asdf package.a.b
         // asdf.adsf --> asdf.asdf
         String8 className;
-        const char* p = name.string();
+        const char* p = name.c_str();
         const char* q = strchr(p, '.');
         if (p == q) {
             className += package;
@@ -776,9 +779,9 @@
             className += name;
         }
         if (kIsDebug) {
-            printf("Qualifying class '%s' to '%s'", name.string(), className.string());
+            printf("Qualifying class '%s' to '%s'", name.c_str(), className.c_str());
         }
-        attr->string.setTo(String16(className));
+        attr->string = String16(className);
     }
 }
 
@@ -810,7 +813,7 @@
   const char* err;
 
   String16 iconPackage, iconType, iconName;
-  if (!ResTable::expandResourceRef(iconRef.string(), iconRef.size(), &iconPackage, &iconType,
+  if (!ResTable::expandResourceRef(iconRef.c_str(), iconRef.size(), &iconPackage, &iconType,
                                    &iconName, NULL, &table->getAssetsPackage(), &err,
                                    &publicOnly)) {
       // Errors will be raised in later XML compilation.
@@ -824,7 +827,7 @@
   }
 
   String16 roundIconPackage, roundIconType, roundIconName;
-  if (!ResTable::expandResourceRef(roundIconRef.string(), roundIconRef.size(), &roundIconPackage,
+  if (!ResTable::expandResourceRef(roundIconRef.c_str(), roundIconRef.size(), &roundIconPackage,
                                    &roundIconType, &roundIconName, NULL, &table->getAssetsPackage(),
                                    &err, &publicOnly)) {
       // Errors will be raised in later XML compilation.
@@ -839,9 +842,9 @@
       return;
   }
 
-  String16 aliasValue = String16(String8::format("@%s:%s/%s", String8(iconPackage).string(),
-                                                 String8(iconType).string(),
-                                                 String8(iconName).string()));
+  String16 aliasValue = String16(String8::format("@%s:%s/%s", String8(iconPackage).c_str(),
+                                                 String8(iconType).c_str(),
+                                                 String8(iconName).c_str()));
 
   // Add an equivalent v26 entry to the roundIcon for each v26 variant of the regular icon.
   const DefaultKeyedVector<ConfigDescription, sp<ResourceTable::Entry>>& configList =
@@ -872,7 +875,7 @@
         const XMLNode::attribute_entry* attr = root->getAttribute(
                 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionCode"));
         if (attr != NULL) {
-            bundle->setVersionCode(strdup(String8(attr->string).string()));
+            bundle->setVersionCode(strdup(String8(attr->string).c_str()));
         }
     }
 
@@ -883,7 +886,7 @@
         const XMLNode::attribute_entry* attr = root->getAttribute(
                 String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName"));
         if (attr != NULL) {
-            bundle->setVersionName(strdup(String8(attr->string).string()));
+            bundle->setVersionName(strdup(String8(attr->string).c_str()));
         }
     }
     
@@ -914,14 +917,14 @@
         const XMLNode::attribute_entry* attr = vers->getAttribute(
                 String16(RESOURCES_ANDROID_NAMESPACE), String16("minSdkVersion"));
         if (attr != NULL) {
-            bundle->setMinSdkVersion(strdup(String8(attr->string).string()));
+            bundle->setMinSdkVersion(strdup(String8(attr->string).c_str()));
         }
     }
 
 
     if (bundle->getCompileSdkVersion() != 0) {
         if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "compileSdkVersion",
-                    String8::format("%d", bundle->getCompileSdkVersion()),
+                    String8::format("%d", bundle->getCompileSdkVersion()).c_str(),
                     errorOnFailedInsert, true)) {
             return UNKNOWN_ERROR;
         }
@@ -929,21 +932,21 @@
 
     if (bundle->getCompileSdkVersionCodename() != "") {
         if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "compileSdkVersionCodename",
-                    bundle->getCompileSdkVersionCodename(), errorOnFailedInsert, true)) {
+                    bundle->getCompileSdkVersionCodename().c_str(), errorOnFailedInsert, true)) {
             return UNKNOWN_ERROR;
         }
     }
 
     if (bundle->getPlatformBuildVersionCode() != "") {
         if (!addTagAttribute(root, "", "platformBuildVersionCode",
-                    bundle->getPlatformBuildVersionCode(), errorOnFailedInsert, true)) {
+                    bundle->getPlatformBuildVersionCode().c_str(), errorOnFailedInsert, true)) {
             return UNKNOWN_ERROR;
         }
     }
 
     if (bundle->getPlatformBuildVersionName() != "") {
         if (!addTagAttribute(root, "", "platformBuildVersionName",
-                    bundle->getPlatformBuildVersionName(), errorOnFailedInsert, true)) {
+                    bundle->getPlatformBuildVersionName().c_str(), errorOnFailedInsert, true)) {
             return UNKNOWN_ERROR;
         }
     }
@@ -968,9 +971,9 @@
             return UNKNOWN_ERROR;
         }
         String8 origPackage(attr->string);
-        attr->string.setTo(String16(manifestPackageNameOverride));
+        attr->string = String16(manifestPackageNameOverride);
         if (kIsDebug) {
-            printf("Overriding package '%s' to be '%s'\n", origPackage.string(),
+            printf("Overriding package '%s' to be '%s'\n", origPackage.c_str(),
                     manifestPackageNameOverride);
         }
 
@@ -1006,7 +1009,7 @@
                 XMLNode::attribute_entry* attr = child->editAttribute(
                         String16(RESOURCES_ANDROID_NAMESPACE), String16("targetPackage"));
                 if (attr != NULL) {
-                    attr->string.setTo(String16(instrumentationPackageNameOverride));
+                    attr->string = String16(instrumentationPackageNameOverride);
                 }
             }
         }
@@ -1071,7 +1074,7 @@
 static ssize_t extractPlatformBuildVersion(const ResTable& table, ResXMLTree& tree, Bundle* bundle) {
     // First check if we should be recording the compileSdkVersion* attributes.
     static const String16 compileSdkVersionName("android:attr/compileSdkVersion");
-    const bool useCompileSdkVersion = table.identifierForName(compileSdkVersionName.string(),
+    const bool useCompileSdkVersion = table.identifierForName(compileSdkVersionName.c_str(),
                                                               compileSdkVersionName.size()) != 0u;
 
     size_t len;
@@ -1207,7 +1210,7 @@
     sp<XMLNode> manifest = XMLNode::newElement(filename, String16(), String16("manifest"));
 
     // Add the 'package' attribute which is set to the package name.
-    const char* packageName = assets->getPackage();
+    const char* packageName = assets->getPackage().c_str();
     const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
     if (manifestPackageNameOverride != NULL) {
         packageName = manifestPackageNameOverride;
@@ -1223,7 +1226,7 @@
     // Add the 'revisionCode' attribute, which is set to the original revisionCode.
     if (bundle->getRevisionCode().size() > 0) {
         if (!addTagAttribute(manifest, RESOURCES_ANDROID_NAMESPACE, "revisionCode",
-                    bundle->getRevisionCode().string(), true, true)) {
+                    bundle->getRevisionCode().c_str(), true, true)) {
             return UNKNOWN_ERROR;
         }
     }
@@ -1270,7 +1273,7 @@
     }
 
     if (kIsDebug) {
-        printf("Creating resources for package %s\n", assets->getPackage().string());
+        printf("Creating resources for package %s\n", assets->getPackage().c_str());
     }
 
     // Set the private symbols package if it was declared.
@@ -1284,7 +1287,7 @@
         packageType = ResourceTable::SharedLibrary;
     } else if (bundle->getExtending()) {
         packageType = ResourceTable::System;
-    } else if (!bundle->getFeatureOfPackage().isEmpty()) {
+    } else if (!bundle->getFeatureOfPackage().empty()) {
         packageType = ResourceTable::AppFeature;
     }
 
@@ -1685,7 +1688,7 @@
         ResourceDirIterator it(fonts, String8("font"));
         while ((err=it.next()) == NO_ERROR) {
             // fonts can be resources other than xml.
-            if (it.getFile()->getPath().getPathExtension() == ".xml") {
+            if (getPathExtension(it.getFile()->getPath()) == ".xml") {
                 String8 src = it.getFile()->getPrintableSource();
                 err = compileXmlFile(bundle, assets, String16(it.getBaseName()),
                         it.getFile(), &table, xmlFlags);
@@ -1715,7 +1718,7 @@
                              workItem.file, &table, xmlCompilationFlags);
 
         if (err == NO_ERROR && workItem.file->hasData()) {
-            assets->addResource(workItem.resPath.getPathLeaf(),
+            assets->addResource(getPathLeaf(workItem.resPath),
                                 workItem.resPath,
                                 workItem.file,
                                 workItem.file->getResourceType());
@@ -1804,7 +1807,7 @@
                     flattenedTable, split->isBase());
             if (err != NO_ERROR) {
                 fprintf(stderr, "Failed to generate resource table for split '%s'\n",
-                        split->getPrintableName().string());
+                        split->getPrintableName().c_str());
                 return err;
             }
             split->addEntry(String8("resources.arsc"), flattenedTable);
@@ -1821,7 +1824,7 @@
                 err = resTable.add(flattenedTable->getData(), flattenedTable->getSize());
                 if (err != NO_ERROR) {
                     fprintf(stderr, "Generated resource table for split '%s' is corrupt.\n",
-                            split->getPrintableName().string());
+                            split->getPrintableName().c_str());
                     return err;
                 }
 
@@ -1849,7 +1852,7 @@
                             if (block < 0) {
                                 hasError = true;
                                 SourcePos().error("%s has no definition for density split '%s'",
-                                        symbol.toString().string(), config.toString().string());
+                                        symbol.toString().c_str(), config.toString().c_str());
 
                                 if (bundle->getVerbose()) {
                                     const Vector<SymbolDefinition>& defs = densityVaryingResources[k];
@@ -1857,7 +1860,7 @@
                                     for (size_t d = 0; d < defCount; d++) {
                                         const SymbolDefinition& def = defs[d];
                                         def.source.error("%s has definition for %s",
-                                                symbol.toString().string(), def.config.toString().string());
+                                                symbol.toString().c_str(), def.config.toString().c_str());
                                     }
 
                                     if (defCount < defs.size()) {
@@ -1880,7 +1883,7 @@
                         generatedManifest, &table);
                 if (err != NO_ERROR) {
                     fprintf(stderr, "Failed to generate AndroidManifest.xml for split '%s'\n",
-                            split->getPrintableName().string());
+                            split->getPrintableName().c_str());
                     return err;
                 }
                 split->addEntry(String8("AndroidManifest.xml"), generatedManifest);
@@ -1960,7 +1963,7 @@
             if (block.getElementNamespace(&len) != NULL) {
                 continue;
             }
-            if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), manifest16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
                                  packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
@@ -1969,10 +1972,10 @@
                                  "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
-                    || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), permission16.c_str()) == 0
+                    || strcmp16(block.getElementName(&len), permission_group16.c_str()) == 0) {
                 const bool isGroup = strcmp16(block.getElementName(&len),
-                        permission_group16.string()) == 0;
+                        permission_group16.c_str()) == 0;
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", isGroup ? packageIdentCharsWithTheStupid
                                  : packageIdentChars, true) != ATTR_OKAY) {
@@ -2002,8 +2005,8 @@
                 const char16_t* id = block.getAttributeStringValue(index, &len);
                 if (id == NULL) {
                     fprintf(stderr, "%s:%d: missing name attribute in element <%s>.\n", 
-                            manifestPath.string(), block.getLineNumber(),
-                            String8(block.getElementName(&len)).string());
+                            manifestPath.c_str(), block.getLineNumber(),
+                            String8(block.getElementName(&len)).c_str());
                     hasErrors = true;
                     break;
                 }
@@ -2038,23 +2041,23 @@
                 if (begins_with_digit || (e != p && *(e-1) != '.')) {
                   fprintf(stderr,
                           "%s:%d: Permission name <%s> is not a valid Java symbol\n",
-                          manifestPath.string(), block.getLineNumber(), idStr.string());
+                          manifestPath.c_str(), block.getLineNumber(), idStr.c_str());
                   hasErrors = true;
                 }
                 syms->addStringSymbol(String8(e), idStr, srcPos);
                 const char16_t* cmt = block.getComment(&len);
                 if (cmt != NULL && *cmt != 0) {
-                    //printf("Comment of %s: %s\n", String8(e).string(),
-                    //        String8(cmt).string());
+                    //printf("Comment of %s: %s\n", String8(e).c_str(),
+                    //        String8(cmt).c_str());
                     syms->appendComment(String8(e), String16(cmt), srcPos);
                 }
                 syms->makeSymbolPublic(String8(e), srcPos);
-            } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), uses_permission16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), instrumentation16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", classIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
@@ -2064,7 +2067,7 @@
                                  packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), application16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", classIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
@@ -2084,7 +2087,7 @@
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), provider16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", classIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
@@ -2104,9 +2107,9 @@
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
-                       || strcmp16(block.getElementName(&len), receiver16.string()) == 0
-                       || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), service16.c_str()) == 0
+                       || strcmp16(block.getElementName(&len), receiver16.c_str()) == 0
+                       || strcmp16(block.getElementName(&len), activity16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
                                  "name", classIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
@@ -2126,14 +2129,14 @@
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
-                       || strcmp16(block.getElementName(&len), category16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), action16.c_str()) == 0
+                       || strcmp16(block.getElementName(&len), category16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "name",
                                  packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), data16.c_str()) == 0) {
                 if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "mimeType",
                                  typeIdentChars, true) != ATTR_OKAY) {
@@ -2144,13 +2147,13 @@
                                  schemeIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), feature_group16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), feature_group16.c_str()) == 0) {
                 int depth = 1;
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                        && code > ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::START_TAG) {
                         depth++;
-                        if (strcmp16(block.getElementName(&len), uses_feature16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), uses_feature16.c_str()) == 0) {
                             ssize_t idx = block.indexOfAttribute(
                                     RESOURCES_ANDROID_NAMESPACE, "required");
                             if (idx < 0) {
@@ -2162,7 +2165,7 @@
                                 fprintf(stderr, "%s:%d: Tag <uses-feature> can not have "
                                         "android:required=\"false\" when inside a "
                                         "<feature-group> tag.\n",
-                                        manifestPath.string(), block.getLineNumber());
+                                        manifestPath.c_str(), block.getLineNumber());
                                 hasErrors = true;
                             }
                         }
@@ -2222,7 +2225,7 @@
 static String8 getSymbolPackage(const String8& symbol, const sp<AaptAssets>& assets, bool pub) {
     ssize_t colon = symbol.find(":", 0);
     if (colon >= 0) {
-        return String8(symbol.string(), colon);
+        return String8(symbol.c_str(), colon);
     }
     return pub ? assets->getPackage() : assets->getSymbolsPrivatePackage();
 }
@@ -2230,7 +2233,7 @@
 static String8 getSymbolName(const String8& symbol) {
     ssize_t colon = symbol.find(":", 0);
     if (colon >= 0) {
-        return String8(symbol.string() + colon + 1);
+        return String8(symbol.c_str() + colon + 1);
     }
     return symbol;
 }
@@ -2245,7 +2248,7 @@
         asym = asym->getNestedSymbols().valueFor(String8("attr"));
         if (asym != NULL) {
             //printf("Got attrs symbols! comment %s=%s\n",
-            //     name.string(), String8(asym->getComment(name)).string());
+            //     name.c_str(), String8(asym->getComment(name)).c_str());
             if (outTypeComment != NULL) {
                 *outTypeComment = asym->getTypeComment(name);
             }
@@ -2276,8 +2279,8 @@
                 "%sfor(int i = 0; i < styleable.%s.length; ++i) {\n"
                 "%sstyleable.%s[i] = (styleable.%s[i] & 0x00ffffff) | (packageId << 24);\n"
                 "%s}\n",
-                indentStr, nclassName.string(),
-                getIndentSpace(indent+1), nclassName.string(), nclassName.string(),
+                indentStr, nclassName.c_str(),
+                getIndentSpace(indent+1), nclassName.c_str(), nclassName.c_str(),
                 indentStr);
     }
 
@@ -2303,8 +2306,8 @@
         String8 flat_name(flattenSymbol(sym.name));
         fprintf(fp,
                 "%s%s.%s = (%s.%s & 0x00ffffff) | (packageId << 24);\n",
-                getIndentSpace(indent), className.string(), flat_name.string(),
-                className.string(), flat_name.string());
+                getIndentSpace(indent), className.c_str(), flat_name.c_str(),
+                className.c_str(), flat_name.c_str());
     }
 
     N = symbols->getNestedSymbols().size();
@@ -2365,12 +2368,12 @@
                 String16 name16(sym.name);
                 uint32_t typeSpecFlags;
                 code = assets->getIncludedResources().identifierForName(
-                    name16.string(), name16.size(),
-                    attr16.string(), attr16.size(),
-                    package16.string(), package16.size(), &typeSpecFlags);
+                    name16.c_str(), name16.size(),
+                    attr16.c_str(), attr16.size(),
+                    package16.c_str(), package16.size(), &typeSpecFlags);
                 if (code == 0) {
                     fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
-                            nclassName.string(), sym.name.string());
+                            nclassName.c_str(), sym.name.c_str());
                     hasErrors = true;
                 }
                 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
@@ -2388,9 +2391,9 @@
         if (comment.size() > 0) {
             String8 cmt(comment);
             ann.preprocessComment(cmt);
-            fprintf(fp, "%s\n", cmt.string());
+            fprintf(fp, "%s\n", cmt.c_str());
         } else {
-            fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.string());
+            fprintf(fp, "Attributes that can be used with a %s.\n", nclassName.c_str());
         }
         bool hasTable = false;
         for (a=0; a<NA; a++) {
@@ -2423,7 +2426,7 @@
                     continue;
                 }
                 if (comment.size() > 0) {
-                    const char16_t* p = comment.string();
+                    const char16_t* p = comment.c_str();
                     while (*p != 0 && *p != '.') {
                         if (*p == '{') {
                             while (*p != 0 && *p != '}') {
@@ -2436,14 +2439,14 @@
                     if (*p == '.') {
                         p++;
                     }
-                    comment = String16(comment.string(), p-comment.string());
+                    comment = String16(comment.c_str(), p-comment.c_str());
                 }
                 fprintf(fp, "%s   <tr><td><code>{@link #%s_%s %s:%s}</code></td><td>%s</td></tr>\n",
-                        indentStr, nclassName.string(),
-                        flattenSymbol(name8).string(),
-                        getSymbolPackage(name8, assets, true).string(),
-                        getSymbolName(name8).string(),
-                        String8(comment).string());
+                        indentStr, nclassName.c_str(),
+                        flattenSymbol(name8).c_str(),
+                        getSymbolPackage(name8, assets, true).c_str(),
+                        getSymbolName(name8).c_str(),
+                        String8(comment).c_str());
             }
         }
         if (hasTable) {
@@ -2457,8 +2460,8 @@
                     continue;
                 }
                 fprintf(fp, "%s   @see #%s_%s\n",
-                        indentStr, nclassName.string(),
-                        flattenSymbol(sym.name).string());
+                        indentStr, nclassName.c_str(),
+                        flattenSymbol(sym.name).c_str());
             }
         }
         fprintf(fp, "%s */\n", getIndentSpace(indent));
@@ -2468,7 +2471,7 @@
         fprintf(fp,
                 "%spublic static final int[] %s = {\n"
                 "%s",
-                indentStr, nclassName.string(),
+                indentStr, nclassName.c_str(),
                 getIndentSpace(indent+1));
 
         for (a=0; a<NA; a++) {
@@ -2503,11 +2506,11 @@
                 uint32_t typeSpecFlags = 0;
                 String16 name16(sym.name);
                 assets->getIncludedResources().identifierForName(
-                    name16.string(), name16.size(),
-                    attr16.string(), attr16.size(),
-                    package16.string(), package16.size(), &typeSpecFlags);
-                //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
-                //    String8(attr16).string(), String8(name16).string(), typeSpecFlags);
+                    name16.c_str(), name16.size(),
+                    attr16.c_str(), attr16.size(),
+                    package16.c_str(), package16.size(), &typeSpecFlags);
+                //printf("%s:%s/%s: 0x%08x\n", String8(package16).c_str(),
+                //    String8(attr16).c_str(), String8(name16).c_str(), typeSpecFlags);
                 const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
 
                 AnnotationProcessor ann;
@@ -2516,20 +2519,20 @@
                     String8 cmt(comment);
                     ann.preprocessComment(cmt);
                     fprintf(fp, "%s  <p>\n%s  @attr description\n", indentStr, indentStr);
-                    fprintf(fp, "%s  %s\n", indentStr, cmt.string());
+                    fprintf(fp, "%s  %s\n", indentStr, cmt.c_str());
                 } else {
                     fprintf(fp,
                             "%s  <p>This symbol is the offset where the {@link %s.R.attr#%s}\n"
                             "%s  attribute's value can be found in the {@link #%s} array.\n",
                             indentStr,
-                            getSymbolPackage(name8, assets, pub).string(),
-                            getSymbolName(name8).string(),
-                            indentStr, nclassName.string());
+                            getSymbolPackage(name8, assets, pub).c_str(),
+                            getSymbolName(name8).c_str(),
+                            indentStr, nclassName.c_str());
                 }
                 if (typeComment.size() > 0) {
                     String8 cmt(typeComment);
                     ann.preprocessComment(cmt);
-                    fprintf(fp, "\n\n%s  %s\n", indentStr, cmt.string());
+                    fprintf(fp, "\n\n%s  %s\n", indentStr, cmt.c_str());
                 }
                 if (comment.size() > 0) {
                     if (pub) {
@@ -2537,16 +2540,16 @@
                                 "%s  <p>This corresponds to the global attribute\n"
                                 "%s  resource symbol {@link %s.R.attr#%s}.\n",
                                 indentStr, indentStr,
-                                getSymbolPackage(name8, assets, true).string(),
-                                getSymbolName(name8).string());
+                                getSymbolPackage(name8, assets, true).c_str(),
+                                getSymbolName(name8).c_str());
                     } else {
                         fprintf(fp,
                                 "%s  <p>This is a private symbol.\n", indentStr);
                     }
                 }
                 fprintf(fp, "%s  @attr name %s:%s\n", indentStr,
-                        getSymbolPackage(name8, assets, pub).string(),
-                        getSymbolName(name8).string());
+                        getSymbolPackage(name8, assets, pub).c_str(),
+                        getSymbolName(name8).c_str());
                 fprintf(fp, "%s*/\n", indentStr);
                 ann.printAnnotations(fp, indentStr);
 
@@ -2556,8 +2559,8 @@
 
                 fprintf(fp,
                         id_format,
-                        indentStr, nclassName.string(),
-                        flattenSymbol(name8).string(), (int)pos);
+                        indentStr, nclassName.c_str(),
+                        flattenSymbol(name8).c_str(), (int)pos);
             }
         }
     }
@@ -2598,12 +2601,12 @@
                 String16 name16(sym.name);
                 uint32_t typeSpecFlags;
                 code = assets->getIncludedResources().identifierForName(
-                    name16.string(), name16.size(),
-                    attr16.string(), attr16.size(),
-                    package16.string(), package16.size(), &typeSpecFlags);
+                    name16.c_str(), name16.size(),
+                    attr16.c_str(), attr16.size(),
+                    package16.c_str(), package16.size(), &typeSpecFlags);
                 if (code == 0) {
                     fprintf(stderr, "ERROR: In <declare-styleable> %s, unable to find attribute %s\n",
-                            nclassName.string(), sym.name.string());
+                            nclassName.c_str(), sym.name.c_str());
                     hasErrors = true;
                 }
                 isPublic = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
@@ -2615,7 +2618,7 @@
 
         NA = idents.size();
 
-        fprintf(fp, "int[] styleable %s {", nclassName.string());
+        fprintf(fp, "int[] styleable %s {", nclassName.c_str());
 
         for (a=0; a<NA; a++) {
             if (a != 0) {
@@ -2645,17 +2648,17 @@
                 uint32_t typeSpecFlags = 0;
                 String16 name16(sym.name);
                 assets->getIncludedResources().identifierForName(
-                    name16.string(), name16.size(),
-                    attr16.string(), attr16.size(),
-                    package16.string(), package16.size(), &typeSpecFlags);
-                //printf("%s:%s/%s: 0x%08x\n", String8(package16).string(),
-                //    String8(attr16).string(), String8(name16).string(), typeSpecFlags);
+                    name16.c_str(), name16.size(),
+                    attr16.c_str(), attr16.size(),
+                    package16.c_str(), package16.size(), &typeSpecFlags);
+                //printf("%s:%s/%s: 0x%08x\n", String8(package16).c_str(),
+                //    String8(attr16).c_str(), String8(name16).c_str(), typeSpecFlags);
                 //const bool pub = (typeSpecFlags&ResTable_typeSpec::SPEC_PUBLIC) != 0;
 
                 fprintf(fp,
                         "int styleable %s_%s %d\n",
-                        nclassName.string(),
-                        flattenSymbol(name8).string(), (int)pos);
+                        nclassName.c_str(),
+                        flattenSymbol(name8).c_str(), (int)pos);
             }
         }
     }
@@ -2670,7 +2673,7 @@
 {
     fprintf(fp, "%spublic %sfinal class %s {\n",
             getIndentSpace(indent),
-            indent != 0 ? "static " : "", className.string());
+            indent != 0 ? "static " : "", className.c_str());
     indent++;
 
     size_t i;
@@ -2699,7 +2702,7 @@
             ann.preprocessComment(cmt);
             fprintf(fp,
                     "%s/** %s\n",
-                    getIndentSpace(indent), cmt.string());
+                    getIndentSpace(indent), cmt.c_str());
         }
         String16 typeComment(sym.typeComment);
         if (typeComment.size() > 0) {
@@ -2708,10 +2711,10 @@
             if (!haveComment) {
                 haveComment = true;
                 fprintf(fp,
-                        "%s/** %s\n", getIndentSpace(indent), cmt.string());
+                        "%s/** %s\n", getIndentSpace(indent), cmt.c_str());
             } else {
                 fprintf(fp,
-                        "%s %s\n", getIndentSpace(indent), cmt.string());
+                        "%s %s\n", getIndentSpace(indent), cmt.c_str());
             }
         }
         if (haveComment) {
@@ -2720,7 +2723,7 @@
         ann.printAnnotations(fp, getIndentSpace(indent));
         fprintf(fp, id_format,
                 getIndentSpace(indent),
-                flattenSymbol(name8).string(), (int)sym.int32Val);
+                flattenSymbol(name8).c_str(), (int)sym.int32Val);
     }
 
     for (i=0; i<N; i++) {
@@ -2740,13 +2743,13 @@
             fprintf(fp,
                     "%s/** %s\n"
                      "%s */\n",
-                    getIndentSpace(indent), cmt.string(),
+                    getIndentSpace(indent), cmt.c_str(),
                     getIndentSpace(indent));
         }
         ann.printAnnotations(fp, getIndentSpace(indent));
         fprintf(fp, "%spublic static final String %s=\"%s\";\n",
                 getIndentSpace(indent),
-                flattenSymbol(name8).string(), sym.stringVal.string());
+                flattenSymbol(name8).c_str(), sym.stringVal.c_str());
     }
 
     sp<AaptSymbols> styleableSymbols;
@@ -2805,8 +2808,8 @@
 
         String8 name8(sym.name);
         fprintf(fp, "int %s %s 0x%08x\n",
-                className.string(),
-                flattenSymbol(name8).string(), (int)sym.int32Val);
+                className.c_str(),
+                flattenSymbol(name8).c_str(), (int)sym.int32Val);
     }
 
     N = symbols->getNestedSymbols().size();
@@ -2844,32 +2847,32 @@
 
         if (bundle->getMakePackageDirs()) {
             const String8& pkg(package);
-            const char* last = pkg.string();
+            const char* last = pkg.c_str();
             const char* s = last-1;
             do {
                 s++;
                 if (s > last && (*s == '.' || *s == 0)) {
                     String8 part(last, s-last);
-                    dest.appendPath(part);
+                    appendPath(dest, part);
 #ifdef _WIN32
-                    _mkdir(dest.string());
+                    _mkdir(dest.c_str());
 #else
-                    mkdir(dest.string(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
+                    mkdir(dest.c_str(), S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP);
 #endif
                     last = s+1;
                 }
             } while (*s);
         }
-        dest.appendPath(className);
+        appendPath(dest, className);
         dest.append(".java");
-        FILE* fp = fopen(dest.string(), "w+");
+        FILE* fp = fopen(dest.c_str(), "w+");
         if (fp == NULL) {
             fprintf(stderr, "ERROR: Unable to open class file %s: %s\n",
-                    dest.string(), strerror(errno));
+                    dest.c_str(), strerror(errno));
             return UNKNOWN_ERROR;
         }
         if (bundle->getVerbose()) {
-            printf("  Writing symbols for class %s.\n", className.string());
+            printf("  Writing symbols for class %s.\n", className.c_str());
         }
 
         fprintf(fp,
@@ -2880,7 +2883,7 @@
             " * should not be modified by hand.\n"
             " */\n"
             "\n"
-            "package %s;\n\n", package.string());
+            "package %s;\n\n", package.c_str());
 
         status_t err = writeSymbolClass(fp, assets, includePrivate, symbols,
                 className, 0, bundle->getNonConstantId(), emitCallback);
@@ -2891,17 +2894,17 @@
 
         if (textSymbolsDest != NULL && R == className) {
             String8 textDest(textSymbolsDest);
-            textDest.appendPath(className);
+            appendPath(textDest, className);
             textDest.append(".txt");
 
-            FILE* fp = fopen(textDest.string(), "w+");
+            FILE* fp = fopen(textDest.c_str(), "w+");
             if (fp == NULL) {
                 fprintf(stderr, "ERROR: Unable to open text symbol file %s: %s\n",
-                        textDest.string(), strerror(errno));
+                        textDest.c_str(), strerror(errno));
                 return UNKNOWN_ERROR;
             }
             if (bundle->getVerbose()) {
-                printf("  Writing text symbols for class %s.\n", className.string());
+                printf("  Writing text symbols for class %s.\n", className.c_str());
             }
 
             status_t err = writeTextSymbolClass(fp, assets, includePrivate, symbols,
@@ -2917,10 +2920,10 @@
         if (bundle->getGenDependencies() && R == className) {
             // Add this R.java to the dependency file
             String8 dependencyFile(bundle->getRClassDir());
-            dependencyFile.appendPath("R.java.d");
+            appendPath(dependencyFile, "R.java.d");
 
-            FILE *fp = fopen(dependencyFile.string(), "a");
-            fprintf(fp,"%s \\\n", dest.string());
+            FILE *fp = fopen(dependencyFile.c_str(), "a");
+            fprintf(fp,"%s \\\n", dest.c_str());
             fclose(fp);
         }
     }
@@ -2956,7 +2959,7 @@
         // asdf     --> package.asdf
         // .asdf  .a.b  --> package.asdf package.a.b
         // asdf.adsf --> asdf.asdf
-        const char* p = className.string();
+        const char* p = className.c_str();
         const char* q = strchr(p, '.');
         if (p == q) {
             className = pkg;
@@ -3023,7 +3026,7 @@
 
     if (assGroup->getFiles().size() != 1) {
         fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
-                assGroup->getFiles().valueAt(0)->getPrintableSource().string());
+                assGroup->getFiles().valueAt(0)->getPrintableSource().c_str());
     }
 
     assFile = assGroup->getFiles().valueAt(0);
@@ -3048,7 +3051,7 @@
         }
         depth++;
         String8 tag(tree.getElementName(&len));
-        // printf("Depth %d tag %s\n", depth, tag.string());
+        // printf("Depth %d tag %s\n", depth, tag.c_str());
         bool keepTag = false;
         if (depth == 1) {
             if (tag != "manifest") {
@@ -3065,7 +3068,7 @@
                         "http://schemas.android.com/apk/res/android",
                         "backupAgent", &error);
                 if (agent.length() > 0) {
-                    addProguardKeepRule(keep, agent, pkg.string(),
+                    addProguardKeepRule(keep, agent, pkg.c_str(),
                             assFile->getPrintableSource(), tree.getLineNumber());
                 }
 
@@ -3073,7 +3076,7 @@
                     defaultProcess = AaptXml::getAttribute(tree,
                             "http://schemas.android.com/apk/res/android", "process", &error);
                     if (error != "") {
-                        fprintf(stderr, "ERROR: %s\n", error.string());
+                        fprintf(stderr, "ERROR: %s\n", error.c_str());
                         return -1;
                     }
                 }
@@ -3089,7 +3092,7 @@
                     String8 componentProcess = AaptXml::getAttribute(tree,
                             "http://schemas.android.com/apk/res/android", "process", &error);
                     if (error != "") {
-                        fprintf(stderr, "ERROR: %s\n", error.string());
+                        fprintf(stderr, "ERROR: %s\n", error.c_str());
                         return -1;
                     }
 
@@ -3103,14 +3106,14 @@
             String8 name = AaptXml::getAttribute(tree,
                     "http://schemas.android.com/apk/res/android", "name", &error);
             if (error != "") {
-                fprintf(stderr, "ERROR: %s\n", error.string());
+                fprintf(stderr, "ERROR: %s\n", error.c_str());
                 return -1;
             }
 
             keepTag = name.length() > 0;
 
             if (keepTag) {
-                addProguardKeepRule(keep, name, pkg.string(),
+                addProguardKeepRule(keep, name, pkg.c_str(),
                         assFile->getPrintableSource(), tree.getLineNumber());
             }
         }
@@ -3143,7 +3146,7 @@
 
     tree.restart();
 
-    if (!startTags.isEmpty()) {
+    if (!startTags.empty()) {
         bool haveStart = false;
         while ((code=tree.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
             if (code != ResXMLTree::START_TAG) {
@@ -3170,7 +3173,7 @@
         String8 tag(tree.getElementName(&len));
 
         // If there is no '.', we'll assume that it's one of the built in names.
-        if (strchr(tag.string(), '.')) {
+        if (strchr(tag.c_str(), '.')) {
             addProguardKeepRule(keep, tag, NULL,
                     layoutFile->getPrintableSource(), tree.getLineNumber());
         } else if (tagAttrPairs != NULL) {
@@ -3183,8 +3186,8 @@
                     ssize_t attrIndex = tree.indexOfAttribute(nsAttr.ns, nsAttr.attr);
                     if (attrIndex < 0) {
                         // fprintf(stderr, "%s:%d: <%s> does not have attribute %s:%s.\n",
-                        //        layoutFile->getPrintableSource().string(), tree.getLineNumber(),
-                        //        tag.string(), nsAttr.ns, nsAttr.attr);
+                        //        layoutFile->getPrintableSource().c_str(), tree.getLineNumber(),
+                        //        tag.c_str(), nsAttr.ns, nsAttr.attr);
                     } else {
                         size_t len;
                         addProguardKeepRule(keep,
@@ -3242,7 +3245,7 @@
 
     // tag:attribute pairs that should be checked in transition files.
     KeyedVector<String8, Vector<NamespaceAttributePair> > kTransitionTagAttrPairs;
-    addTagAttrPair(&kTransitionTagAttrPairs, kTransition.string(), NULL, kClass);
+    addTagAttrPair(&kTransitionTagAttrPairs, kTransition.c_str(), NULL, kClass);
     addTagAttrPair(&kTransitionTagAttrPairs, "pathMotion", NULL, kClass);
 
     const Vector<sp<AaptDir> >& dirs = assets->resDirs();
@@ -3252,16 +3255,16 @@
         const String8& dirName = d->getLeaf();
         Vector<String8> startTags;
         const KeyedVector<String8, Vector<NamespaceAttributePair> >* tagAttrPairs = NULL;
-        if ((dirName == String8("layout")) || (strncmp(dirName.string(), "layout-", 7) == 0)) {
+        if ((dirName == String8("layout")) || (strncmp(dirName.c_str(), "layout-", 7) == 0)) {
             tagAttrPairs = &kLayoutTagAttrPairs;
-        } else if ((dirName == String8("xml")) || (strncmp(dirName.string(), "xml-", 4) == 0)) {
+        } else if ((dirName == String8("xml")) || (strncmp(dirName.c_str(), "xml-", 4) == 0)) {
             startTags.add(String8("PreferenceScreen"));
             startTags.add(String8("preference-headers"));
             tagAttrPairs = &kXmlTagAttrPairs;
-        } else if ((dirName == String8("menu")) || (strncmp(dirName.string(), "menu-", 5) == 0)) {
+        } else if ((dirName == String8("menu")) || (strncmp(dirName.c_str(), "menu-", 5) == 0)) {
             startTags.add(String8("menu"));
             tagAttrPairs = NULL;
-        } else if (dirName == kTransition || (strncmp(dirName.string(), kTransitionPrefix.string(),
+        } else if (dirName == kTransition || (strncmp(dirName.c_str(), kTransitionPrefix.c_str(),
                         kTransitionPrefix.size()) == 0)) {
             tagAttrPairs = &kTransitionTagAttrPairs;
         } else {
@@ -3307,9 +3310,9 @@
         const SortedVector<String8>& locations = rules.valueAt(i);
         const size_t M = locations.size();
         for (size_t j=0; j<M; j++) {
-            fprintf(fp, "# %s\n", locations.itemAt(j).string());
+            fprintf(fp, "# %s\n", locations.itemAt(j).c_str());
         }
-        fprintf(fp, "%s\n\n", rules.keyAt(i).string());
+        fprintf(fp, "%s\n\n", rules.keyAt(i).c_str());
     }
     fclose(fp);
 
@@ -3366,7 +3369,7 @@
     status_t deps = -1;
     for (size_t file_i = 0; file_i < files->size(); ++file_i) {
         // Add the full file path to the dependency file
-        fprintf(fp, "%s \\\n", files->itemAt(file_i).string());
+        fprintf(fp, "%s \\\n", files->itemAt(file_i).c_str());
         deps++;
     }
     return deps;
diff --git a/tools/aapt/ResourceFilter.cpp b/tools/aapt/ResourceFilter.cpp
index ed06f60..cc8dce7e 100644
--- a/tools/aapt/ResourceFilter.cpp
+++ b/tools/aapt/ResourceFilter.cpp
@@ -32,7 +32,7 @@
             // only specify locale in the standard 'en_US' format.
             val.writeTo(&entry.first);
         } else if (!AaptConfig::parse(part, &entry.first)) {
-            fprintf(stderr, "Invalid configuration: %s\n", part.string());
+            fprintf(stderr, "Invalid configuration: %s\n", part.c_str());
             return UNKNOWN_ERROR;
         }
 
@@ -43,7 +43,7 @@
 
         // Ignore any densities. Those are best handled in --preferred-density
         if ((entry.second & ResTable_config::CONFIG_DENSITY) != 0) {
-            fprintf(stderr, "warning: ignoring flag -c %s. Use --preferred-density instead.\n", entry.first.toString().string());
+            fprintf(stderr, "warning: ignoring flag -c %s. Use --preferred-density instead.\n", entry.first.toString().c_str());
             entry.first.density = 0;
             entry.second &= ~ResTable_config::CONFIG_DENSITY;
         }
@@ -148,7 +148,7 @@
     mConfigs.clear();
     for (size_t i = 0; i < configStrs.size(); i++) {
         if (!AaptConfig::parse(configStrs[i], &config)) {
-            fprintf(stderr, "Invalid configuration: %s\n", configStrs[i].string());
+            fprintf(stderr, "Invalid configuration: %s\n", configStrs[i].c_str());
             return UNKNOWN_ERROR;
         }
         mConfigs.insert(config);
diff --git a/tools/aapt/ResourceIdCache.cpp b/tools/aapt/ResourceIdCache.cpp
index 8835fb0..1c7788d 100644
--- a/tools/aapt/ResourceIdCache.cpp
+++ b/tools/aapt/ResourceIdCache.cpp
@@ -37,7 +37,7 @@
 
 static uint32_t hash(const android::String16& hashableString) {
     uint32_t hash = 5381;
-    const char16_t* str = hashableString.string();
+    const char16_t* str = hashableString.c_str();
     while (int c = *str++) hash = hashround(hash, c);
     return hash;
 }
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 47750fc..620e272 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -11,8 +11,10 @@
 #include "ResourceFilter.h"
 #include "ResourceIdCache.h"
 #include "SdkConstants.h"
+#include "Utils.h"
 
 #include <algorithm>
+#include <androidfw/PathUtils.h>
 #include <androidfw/ResourceTypes.h>
 #include <utils/ByteOrder.h>
 #include <utils/TypeHelpers.h>
@@ -82,7 +84,7 @@
         sp<AaptDir> resDir = assets->getDirs().valueFor(String8("res"));
         sp<AaptDir> dir = resDir->getDirs().valueFor(target->getGroupEntry().toDirName(
                 target->getResourceType()));
-        dir->removeFile(target->getPath().getPathLeaf());
+        dir->removeFile(getPathLeaf(target->getPath()));
         return NO_ERROR;
     }
 
@@ -361,10 +363,10 @@
     ssize_t typeIdx = block.indexOfAttribute(NULL, "format");
     if (typeIdx >= 0) {
         String16 typeStr = String16(block.getAttributeStringValue(typeIdx, &len));
-        attr.type = parse_flags(typeStr.string(), typeStr.size(), gFormatFlags);
+        attr.type = parse_flags(typeStr.c_str(), typeStr.size(), gFormatFlags);
         if (attr.type == 0) {
             attr.sourcePos.error("Tag <attr> 'format' attribute value \"%s\" not valid\n",
-                    String8(typeStr).string());
+                    String8(typeStr).c_str());
             attr.hasErrors = true;
         }
         attr.createIfNeeded(outTable);
@@ -374,14 +376,14 @@
         attr.createIfNeeded(outTable);
     }
 
-    //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).string(), attr.type);
+    //printf("Attribute %s: type=0x%08x\n", String8(attr.ident).c_str(), attr.type);
 
     ssize_t minIdx = block.indexOfAttribute(NULL, "min");
     if (minIdx >= 0) {
         String16 val = String16(block.getAttributeStringValue(minIdx, &len));
-        if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
+        if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
             attr.sourcePos.error("Tag <attr> 'min' attribute must be a number, not \"%s\"\n",
-                    String8(val).string());
+                    String8(val).c_str());
             attr.hasErrors = true;
         }
         attr.createIfNeeded(outTable);
@@ -397,9 +399,9 @@
     ssize_t maxIdx = block.indexOfAttribute(NULL, "max");
     if (maxIdx >= 0) {
         String16 val = String16(block.getAttributeStringValue(maxIdx, &len));
-        if (!ResTable::stringToInt(val.string(), val.size(), NULL)) {
+        if (!ResTable::stringToInt(val.c_str(), val.size(), NULL)) {
             attr.sourcePos.error("Tag <attr> 'max' attribute must be a number, not \"%s\"\n",
-                    String8(val).string());
+                    String8(val).c_str());
             attr.hasErrors = true;
         }
         attr.createIfNeeded(outTable);
@@ -422,7 +424,7 @@
         uint32_t l10n_required = parse_flags(str, len, l10nRequiredFlags, &error);
         if (error) {
             attr.sourcePos.error("Tag <attr> 'localization' attribute value \"%s\" not valid\n",
-                    String8(str).string());
+                    String8(str).c_str());
             attr.hasErrors = true;
         }
         attr.createIfNeeded(outTable);
@@ -442,14 +444,14 @@
     while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
         if (code == ResXMLTree::START_TAG) {
             uint32_t localType = 0;
-            if (strcmp16(block.getElementName(&len), enum16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), enum16.c_str()) == 0) {
                 localType = ResTable_map::TYPE_ENUM;
-            } else if (strcmp16(block.getElementName(&len), flag16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), flag16.c_str()) == 0) {
                 localType = ResTable_map::TYPE_FLAGS;
             } else {
                 SourcePos(in->getPrintableSource(), block.getLineNumber())
                         .error("Tag <%s> can not appear inside <attr>, only <enum> or <flag>\n",
-                        String8(block.getElementName(&len)).string());
+                        String8(block.getElementName(&len)).c_str());
                 return UNKNOWN_ERROR;
             }
 
@@ -505,11 +507,11 @@
                         .error("A 'value' attribute is required for <enum> or <flag>\n");
                 attr.hasErrors = true;
             }
-            if (!attr.hasErrors && !ResTable::stringToInt(value.string(), value.size(), NULL)) {
+            if (!attr.hasErrors && !ResTable::stringToInt(value.c_str(), value.size(), NULL)) {
                 SourcePos(in->getPrintableSource(), block.getLineNumber())
                         .error("Tag <enum> or <flag> 'value' attribute must be a number,"
                         " not \"%s\"\n",
-                        String8(value).string());
+                        String8(value).c_str());
                 attr.hasErrors = true;
             }
 
@@ -546,21 +548,21 @@
                 }
             }
         } else if (code == ResXMLTree::END_TAG) {
-            if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
                 break;
             }
             if ((attr.type&ResTable_map::TYPE_ENUM) != 0) {
-                if (strcmp16(block.getElementName(&len), enum16.string()) != 0) {
+                if (strcmp16(block.getElementName(&len), enum16.c_str()) != 0) {
                     SourcePos(in->getPrintableSource(), block.getLineNumber())
                             .error("Found tag </%s> where </enum> is expected\n",
-                            String8(block.getElementName(&len)).string());
+                            String8(block.getElementName(&len)).c_str());
                     return UNKNOWN_ERROR;
                 }
             } else {
-                if (strcmp16(block.getElementName(&len), flag16.string()) != 0) {
+                if (strcmp16(block.getElementName(&len), flag16.c_str()) != 0) {
                     SourcePos(in->getPrintableSource(), block.getLineNumber())
                             .error("Found tag </%s> where </flag> is expected\n",
-                            String8(block.getElementName(&len)).string());
+                            String8(block.getElementName(&len)).c_str());
                     return UNKNOWN_ERROR;
                 }
             }
@@ -606,7 +608,7 @@
 
     String16 str;
     Vector<StringPool::entry_style_span> spans;
-    err = parseStyledString(bundle, in->getPrintableSource().string(),
+    err = parseStyledString(bundle, in->getPrintableSource().c_str(),
                             block, item16, &str, &spans, isFormatted,
                             pseudolocalize);
     if (err != NO_ERROR) {
@@ -619,10 +621,10 @@
                 config.language[0], config.language[1],
                 config.country[0], config.country[1],
                 config.orientation, config.density,
-                String8(parentIdent).string(),
-                String8(ident).string(),
-                String8(itemIdent).string(),
-                String8(str).string());
+                String8(parentIdent).c_str(),
+                String8(ident).c_str(),
+                String8(itemIdent).c_str(),
+                String8(str).c_str());
     }
 
     err = outTable->addBag(SourcePos(in->getPrintableSource(), block->getLineNumber()),
@@ -636,8 +638,8 @@
  * haystack, false otherwise.
  */
 bool isInProductList(const String16& needle, const String16& haystack) {
-    const char16_t *needle2 = needle.string();
-    const char16_t *haystack2 = haystack.string();
+    const char16_t *needle2 = needle.c_str();
+    const char16_t *haystack2 = haystack.c_str();
     size_t needlesize = needle.size();
 
     while (*haystack2 != '\0') {
@@ -703,7 +705,7 @@
 
     String16 str;
     Vector<StringPool::entry_style_span> spans;
-    err = parseStyledString(bundle, in->getPrintableSource().string(), block,
+    err = parseStyledString(bundle, in->getPrintableSource().c_str(), block,
                             curTag, &str, curIsStyled ? &spans : NULL,
                             isFormatted, pseudolocalize);
 
@@ -730,7 +732,7 @@
          */
 
         if (bundleProduct[0] == '\0') {
-            if (strcmp16(String16("default").string(), product.string()) != 0) {
+            if (strcmp16(String16("default").c_str(), product.c_str()) != 0) {
                 /*
                  * This string has a product other than 'default'. Do not add it,
                  * but record it so that if we do not see the same string with
@@ -750,7 +752,7 @@
 
             if (isInProductList(product, String16(bundleProduct))) {
                 ;
-            } else if (strcmp16(String16("default").string(), product.string()) == 0 &&
+            } else if (strcmp16(String16("default").c_str(), product.c_str()) == 0 &&
                        !outTable->hasBagOrEntry(myPackage, curType, ident, config)) {
                 ;
             } else {
@@ -764,7 +766,7 @@
                 config.language[0], config.language[1],
                 config.country[0], config.country[1],
                 config.orientation, config.density,
-                String8(ident).string(), String8(str).string());
+                String8(ident).c_str(), String8(str).c_str());
     }
 
     err = outTable->addEntry(SourcePos(in->getPrintableSource(), block->getLineNumber()),
@@ -847,7 +849,7 @@
     bool hasErrors = false;
 
     bool fileIsTranslatable = true;
-    if (strstr(in->getPrintableSource().string(), "donottranslate") != NULL) {
+    if (strstr(in->getPrintableSource().c_str(), "donottranslate") != NULL) {
         fileIsTranslatable = false;
     }
 
@@ -869,9 +871,9 @@
                 "No start tag found\n");
         return UNKNOWN_ERROR;
     }
-    if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
+    if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
-                "Invalid start tag %s\n", String8(block.getElementName(&len)).string());
+                "Invalid start tag %s\n", String8(block.getElementName(&len)).c_str());
         return UNKNOWN_ERROR;
     }
 
@@ -900,7 +902,7 @@
         SourcePos(in->getPrintableSource(), 0).warning(
                 "Resource file %s is skipped as pseudolocalization"
                 " was done automatically.",
-                in->getPrintableSource().string());
+                in->getPrintableSource().c_str());
         return NO_ERROR;
     }
 
@@ -917,29 +919,29 @@
             bool curIsFormatted = fileIsTranslatable;
             bool localHasErrors = false;
 
-            if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
+            if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                         && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                         && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
             
                 String16 type;
@@ -965,7 +967,7 @@
                     Res_value identValue;
                     if (!ResTable::stringToInt(identStr, len, &identValue)) {
                         srcPos.error("Given 'id' attribute is not an integer: %s\n",
-                                String8(block.getAttributeStringValue(identIdx, &len)).string());
+                                String8(block.getAttributeStringValue(identIdx, &len)).c_str());
                         hasErrors = localHasErrors = true;
                     } else {
                         ident = identValue.data;
@@ -1004,14 +1006,14 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), public16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), public16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
             
                 String16 type;
@@ -1037,7 +1039,7 @@
                     Res_value startValue;
                     if (!ResTable::stringToInt(startStr, len, &startValue)) {
                         srcPos.error("Given 'start' attribute is not an integer: %s\n",
-                                String8(block.getAttributeStringValue(startIdx, &len)).string());
+                                String8(block.getAttributeStringValue(startIdx, &len)).c_str());
                         hasErrors = localHasErrors = true;
                     } else {
                         start = startValue.data;
@@ -1057,7 +1059,7 @@
                     Res_value endValue;
                     if (!ResTable::stringToInt(endStr, len, &endValue)) {
                         srcPos.error("Given 'end' attribute is not an integer: %s\n",
-                                String8(block.getAttributeStringValue(endIdx, &len)).string());
+                                String8(block.getAttributeStringValue(endIdx, &len)).c_str());
                         hasErrors = localHasErrors = true;
                     } else {
                         end = endValue.data;
@@ -1114,14 +1116,14 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), public_padding16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), public_padding16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
                 String16 pkg;
                 ssize_t pkgIdx = block.indexOfAttribute(NULL, "package");
                 if (pkgIdx < 0) {
@@ -1144,14 +1146,14 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), private_symbols16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), private_symbols16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
             
                 String16 type;
@@ -1186,7 +1188,7 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), java_symbol16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), java_symbol16.c_str()) == 0) {
                             break;
                         }
                     }
@@ -1194,7 +1196,7 @@
                 continue;
 
 
-            } else if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
             
                 String16 typeName;
@@ -1217,14 +1219,14 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), add_resource16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), add_resource16.c_str()) == 0) {
                             break;
                         }
                     }
                 }
                 continue;
                 
-            } else if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
                 SourcePos srcPos(in->getPrintableSource(), block.getLineNumber());
                                 
                 String16 ident;
@@ -1258,30 +1260,30 @@
 
                 while ((code=block.next()) != ResXMLTree::END_DOCUMENT && code != ResXMLTree::BAD_DOCUMENT) {
                     if (code == ResXMLTree::START_TAG) {
-                        if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
                             while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                                    && code != ResXMLTree::BAD_DOCUMENT) {
                                 if (code == ResXMLTree::END_TAG) {
-                                    if (strcmp16(block.getElementName(&len), skip16.string()) == 0) {
+                                    if (strcmp16(block.getElementName(&len), skip16.c_str()) == 0) {
                                         break;
                                     }
                                 }
                             }
                             continue;
-                        } else if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
+                        } else if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
                             while ((code=block.next()) != ResXMLTree::END_DOCUMENT
                                    && code != ResXMLTree::BAD_DOCUMENT) {
                                 if (code == ResXMLTree::END_TAG) {
-                                    if (strcmp16(block.getElementName(&len), eat_comment16.string()) == 0) {
+                                    if (strcmp16(block.getElementName(&len), eat_comment16.c_str()) == 0) {
                                         break;
                                     }
                                 }
                             }
                             continue;
-                        } else if (strcmp16(block.getElementName(&len), attr16.string()) != 0) {
+                        } else if (strcmp16(block.getElementName(&len), attr16.c_str()) != 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                     "Tag <%s> can not appear inside <declare-styleable>, only <attr>\n",
-                                    String8(block.getElementName(&len)).string());
+                                    String8(block.getElementName(&len)).c_str());
                             return UNKNOWN_ERROR;
                         }
 
@@ -1297,30 +1299,30 @@
                             SourcePos srcPos(String8(in->getPrintableSource()), block.getLineNumber());
                             symbols->addSymbol(String8(itemIdent), 0, srcPos);
                             symbols->appendComment(String8(itemIdent), comment, srcPos);
-                            //printf("Attribute %s comment: %s\n", String8(itemIdent).string(),
-                            //     String8(comment).string());
+                            //printf("Attribute %s comment: %s\n", String8(itemIdent).c_str(),
+                            //     String8(comment).c_str());
                         }
                     } else if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), declare_styleable16.string()) == 0) {
+                        if (strcmp16(block.getElementName(&len), declare_styleable16.c_str()) == 0) {
                             break;
                         }
 
                         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                 "Found tag </%s> where </attr> is expected\n",
-                                String8(block.getElementName(&len)).string());
+                                String8(block.getElementName(&len)).c_str());
                         return UNKNOWN_ERROR;
                     }
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), attr16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), attr16.c_str()) == 0) {
                 err = compileAttribute(in, block, myPackage, outTable, NULL);
                 if (err != NO_ERROR) {
                     hasErrors = true;
                 }
                 continue;
 
-            } else if (strcmp16(block.getElementName(&len), item16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), item16.c_str()) == 0) {
                 curTag = &item16;
                 ssize_t attri = block.indexOfAttribute(NULL, "type");
                 if (attri >= 0) {
@@ -1333,12 +1335,12 @@
                     if (formatIdx >= 0) {
                         String16 formatStr = String16(block.getAttributeStringValue(
                                 formatIdx, &len));
-                        curFormat = parse_flags(formatStr.string(), formatStr.size(),
+                        curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
                                                 gFormatFlags);
                         if (curFormat == 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                     "Tag <item> 'format' attribute value \"%s\" not valid\n",
-                                    String8(formatStr).string());
+                                    String8(formatStr).c_str());
                             hasErrors = localHasErrors = true;
                         }
                     }
@@ -1348,7 +1350,7 @@
                     hasErrors = localHasErrors = true;
                 }
                 curIsStyled = true;
-            } else if (strcmp16(block.getElementName(&len), string16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), string16.c_str()) == 0) {
                 // Note the existence and locale of every string we process
                 char rawLocale[RESTABLE_MAX_LOCALE_LEN];
                 curParams.getBcp47Locale(rawLocale);
@@ -1361,12 +1363,12 @@
                 for (size_t i = 0; i < n; i++) {
                     size_t length;
                     const char16_t* attr = block.getAttributeName(i, &length);
-                    if (strcmp16(attr, name16.string()) == 0) {
-                        name.setTo(block.getAttributeStringValue(i, &length));
-                    } else if (strcmp16(attr, translatable16.string()) == 0) {
-                        translatable.setTo(block.getAttributeStringValue(i, &length));
-                    } else if (strcmp16(attr, formatted16.string()) == 0) {
-                        formatted.setTo(block.getAttributeStringValue(i, &length));
+                    if (strcmp16(attr, name16.c_str()) == 0) {
+                        name = String16(block.getAttributeStringValue(i, &length));
+                    } else if (strcmp16(attr, translatable16.c_str()) == 0) {
+                        translatable = String16(block.getAttributeStringValue(i, &length));
+                    } else if (strcmp16(attr, formatted16.c_str()) == 0) {
+                        formatted = String16(block.getAttributeStringValue(i, &length));
                     }
                 }
                 
@@ -1380,8 +1382,8 @@
                         if (locale.size() > 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).warning(
                                     "string '%s' marked untranslatable but exists in locale '%s'\n",
-                                    String8(name).string(),
-                                    locale.string());
+                                    String8(name).c_str(),
+                                    locale.c_str());
                             // hasErrors = localHasErrors = true;
                         } else {
                             // Intentionally empty block:
@@ -1407,31 +1409,31 @@
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_STRING;
                 curIsStyled = true;
                 curIsPseudolocalizable = fileIsTranslatable && (translatable != false16);
-            } else if (strcmp16(block.getElementName(&len), drawable16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), drawable16.c_str()) == 0) {
                 curTag = &drawable16;
                 curType = drawable16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
-            } else if (strcmp16(block.getElementName(&len), color16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), color16.c_str()) == 0) {
                 curTag = &color16;
                 curType = color16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_COLOR;
-            } else if (strcmp16(block.getElementName(&len), bool16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), bool16.c_str()) == 0) {
                 curTag = &bool16;
                 curType = bool16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_BOOLEAN;
-            } else if (strcmp16(block.getElementName(&len), integer16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), integer16.c_str()) == 0) {
                 curTag = &integer16;
                 curType = integer16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
-            } else if (strcmp16(block.getElementName(&len), dimen16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), dimen16.c_str()) == 0) {
                 curTag = &dimen16;
                 curType = dimen16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_DIMENSION;
-            } else if (strcmp16(block.getElementName(&len), fraction16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), fraction16.c_str()) == 0) {
                 curTag = &fraction16;
                 curType = fraction16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_FRACTION;
-            } else if (strcmp16(block.getElementName(&len), bag16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), bag16.c_str()) == 0) {
                 curTag = &bag16;
                 curIsBag = true;
                 ssize_t attri = block.indexOfAttribute(NULL, "type");
@@ -1442,16 +1444,16 @@
                             "A 'type' attribute is required for <bag>\n");
                     hasErrors = localHasErrors = true;
                 }
-            } else if (strcmp16(block.getElementName(&len), style16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), style16.c_str()) == 0) {
                 curTag = &style16;
                 curType = style16;
                 curIsBag = true;
-            } else if (strcmp16(block.getElementName(&len), plurals16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), plurals16.c_str()) == 0) {
                 curTag = &plurals16;
                 curType = plurals16;
                 curIsBag = true;
                 curIsPseudolocalizable = fileIsTranslatable;
-            } else if (strcmp16(block.getElementName(&len), array16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), array16.c_str()) == 0) {
                 curTag = &array16;
                 curType = array16;
                 curIsBag = true;
@@ -1460,16 +1462,16 @@
                 if (formatIdx >= 0) {
                     String16 formatStr = String16(block.getAttributeStringValue(
                             formatIdx, &len));
-                    curFormat = parse_flags(formatStr.string(), formatStr.size(),
+                    curFormat = parse_flags(formatStr.c_str(), formatStr.size(),
                                             gFormatFlags);
                     if (curFormat == 0) {
                         SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                 "Tag <array> 'format' attribute value \"%s\" not valid\n",
-                                String8(formatStr).string());
+                                String8(formatStr).c_str());
                         hasErrors = localHasErrors = true;
                     }
                 }
-            } else if (strcmp16(block.getElementName(&len), string_array16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), string_array16.c_str()) == 0) {
                 // Check whether these strings need valid formats.
                 // (simplified form of what string16 does above)
                 bool isTranslatable = false;
@@ -1480,14 +1482,14 @@
                 for (size_t i = 0; i < n; i++) {
                     size_t length;
                     const char16_t* attr = block.getAttributeName(i, &length);
-                    if (strcmp16(attr, formatted16.string()) == 0) {
+                    if (strcmp16(attr, formatted16.c_str()) == 0) {
                         const char16_t* value = block.getAttributeStringValue(i, &length);
-                        if (strcmp16(value, false16.string()) == 0) {
+                        if (strcmp16(value, false16.c_str()) == 0) {
                             curIsFormatted = false;
                         }
-                    } else if (strcmp16(attr, translatable16.string()) == 0) {
+                    } else if (strcmp16(attr, translatable16.c_str()) == 0) {
                         const char16_t* value = block.getAttributeStringValue(i, &length);
-                        if (strcmp16(value, false16.string()) == 0) {
+                        if (strcmp16(value, false16.c_str()) == 0) {
                             isTranslatable = false;
                         }
                     }
@@ -1499,7 +1501,7 @@
                 curIsBag = true;
                 curIsBagReplaceOnOverwrite = true;
                 curIsPseudolocalizable = isTranslatable && fileIsTranslatable;
-            } else if (strcmp16(block.getElementName(&len), integer_array16.string()) == 0) {
+            } else if (strcmp16(block.getElementName(&len), integer_array16.c_str()) == 0) {
                 curTag = &integer_array16;
                 curType = array16;
                 curFormat = ResTable_map::TYPE_REFERENCE|ResTable_map::TYPE_INTEGER;
@@ -1508,7 +1510,7 @@
             } else {
                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                         "Found tag %s where item is expected\n",
-                        String8(block.getElementName(&len)).string());
+                        String8(block.getElementName(&len)).c_str());
                 return UNKNOWN_ERROR;
             }
 
@@ -1519,7 +1521,7 @@
             } else {
                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                         "A 'name' attribute is required for <%s>\n",
-                        String8(*curTag).string());
+                        String8(*curTag).c_str());
                 hasErrors = localHasErrors = true;
             }
 
@@ -1540,7 +1542,7 @@
                 } else {
                     ssize_t sep = ident.findLast('.');
                     if (sep >= 0) {
-                        parentIdent.setTo(ident, sep);
+                        parentIdent = String16(ident, sep);
                     }
                 }
 
@@ -1560,11 +1562,11 @@
                         && code != ResXMLTree::BAD_DOCUMENT) {
 
                     if (code == ResXMLTree::START_TAG) {
-                        if (strcmp16(block.getElementName(&len), item16.string()) != 0) {
+                        if (strcmp16(block.getElementName(&len), item16.c_str()) != 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                     "Tag <%s> can not appear inside <%s>, only <item>\n",
-                                    String8(block.getElementName(&len)).string(),
-                                    String8(*curTag).string());
+                                    String8(block.getElementName(&len)).c_str(),
+                                    String8(*curTag).c_str());
                             return UNKNOWN_ERROR;
                         }
 
@@ -1647,11 +1649,11 @@
                             hasErrors = localHasErrors = true;
                         }
                     } else if (code == ResXMLTree::END_TAG) {
-                        if (strcmp16(block.getElementName(&len), curTag->string()) != 0) {
+                        if (strcmp16(block.getElementName(&len), curTag->c_str()) != 0) {
                             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                                     "Found tag </%s> where </%s> is expected\n",
-                                    String8(block.getElementName(&len)).string(),
-                                    String8(*curTag).string());
+                                    String8(block.getElementName(&len)).c_str(),
+                                    String8(*curTag).c_str());
                             return UNKNOWN_ERROR;
                         }
                         break;
@@ -1700,9 +1702,9 @@
 
 #if 0
             if (comment.size() > 0) {
-                printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).string(),
-                       String8(curType).string(), String8(ident).string(),
-                       String8(comment).string());
+                printf("Comment for @%s:%s/%s: %s\n", String8(myPackage).c_str(),
+                       String8(curType).c_str(), String8(ident).c_str(),
+                       String8(comment).c_str());
             }
 #endif
             if (!localHasErrors) {
@@ -1710,9 +1712,9 @@
             }
         }
         else if (code == ResXMLTree::END_TAG) {
-            if (strcmp16(block.getElementName(&len), resources16.string()) != 0) {
+            if (strcmp16(block.getElementName(&len), resources16.c_str()) != 0) {
                 SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
-                        "Unexpected end tag %s\n", String8(block.getElementName(&len)).string());
+                        "Unexpected end tag %s\n", String8(block.getElementName(&len)).c_str());
                 return UNKNOWN_ERROR;
             }
         }
@@ -1724,7 +1726,7 @@
             }
             SourcePos(in->getPrintableSource(), block.getLineNumber()).error(
                     "Found text \"%s\" where item tag is expected\n",
-                    String8(block.getText(&len)).string());
+                    String8(block.getText(&len)).c_str());
             return UNKNOWN_ERROR;
         }
     }
@@ -1740,13 +1742,13 @@
                 const char* bundleProduct =
                         (bundle->getProduct() == NULL) ? "" : bundle->getProduct();
                 fprintf(stderr, "In resource file %s: %s\n",
-                        in->getPrintableSource().string(),
-                        curParams.toString().string());
+                        in->getPrintableSource().c_str(),
+                        curParams.toString().c_str());
 
                 fprintf(stderr, "\t%s '%s' does not match product %s.\n"
                         "\tYou may have forgotten to include a 'default' product variant"
                         " of the resource.\n",
-                        String8(p.type).string(), String8(p.ident).string(),
+                        String8(p.type).c_str(), String8(p.ident).c_str(),
                         bundleProduct[0] == 0 ? "default" : bundleProduct);
                 return UNKNOWN_ERROR;
             }
@@ -1812,17 +1814,17 @@
     mTypeIdOffset = findLargestTypeIdForPackage(assets->getIncludedResources(), mAssetsPackage);
 
     const String8& featureAfter = bundle->getFeatureAfterPackage();
-    if (!featureAfter.isEmpty()) {
+    if (!featureAfter.empty()) {
         AssetManager featureAssetManager;
         if (!featureAssetManager.addAssetPath(featureAfter, NULL)) {
             fprintf(stderr, "ERROR: Feature package '%s' not found.\n",
-                    featureAfter.string());
+                    featureAfter.c_str());
             return UNKNOWN_ERROR;
         }
 
         const ResTable& featureTable = featureAssetManager.getResources(false);
         mTypeIdOffset = std::max(mTypeIdOffset,
-                findLargestTypeIdForPackage(featureTable, mAssetsPackage)); 
+                findLargestTypeIdForPackage(featureTable, mAssetsPackage));
     }
 
     return NO_ERROR;
@@ -1835,13 +1837,13 @@
                                   const uint32_t ident)
 {
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         sourcePos.error("Error declaring public resource %s/%s for included package %s\n",
-                String8(type).string(), String8(name).string(),
-                String8(package).string());
+                String8(type).c_str(), String8(name).c_str(),
+                String8(package).c_str());
         return UNKNOWN_ERROR;
     }
 
@@ -1864,12 +1866,12 @@
                                  const bool overwrite)
 {
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         sourcePos.error("Resource entry %s/%s is already defined in package %s.",
-                String8(type).string(), String8(name).string(), String8(package).string());
+                String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
         return UNKNOWN_ERROR;
     }
     
@@ -1899,12 +1901,12 @@
     // Check for adding entries in other packages...  for now we do
     // nothing.  We need to do the right thing here to support skinning.
     uint32_t rid = mAssets->getIncludedResources()
-    .identifierForName(name.string(), name.size(),
-                       type.string(), type.size(),
-                       package.string(), package.size());
+    .identifierForName(name.c_str(), name.size(),
+                       type.c_str(), type.size(),
+                       package.c_str(), package.size());
     if (rid != 0) {
         sourcePos.error("Resource entry %s/%s is already defined in package %s.",
-                String8(type).string(), String8(name).string(), String8(package).string());
+                String8(type).c_str(), String8(name).c_str(), String8(package).c_str());
         return UNKNOWN_ERROR;
     }
 
@@ -1921,7 +1923,7 @@
         }
         if (!canAdd) {
             sourcePos.error("Resource does not already exist in overlay at '%s'; use <add-resource> to add.\n",
-                            String8(name).string());
+                            String8(name).c_str());
             return UNKNOWN_ERROR;
         }
     }
@@ -1959,9 +1961,9 @@
     // Check for adding entries in other packages...  for now we do
     // nothing.  We need to do the right thing here to support skinning.
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         return NO_ERROR;
     }
@@ -1969,7 +1971,7 @@
 #if 0
     if (name == String16("left")) {
         printf("Adding bag left: file=%s, line=%d, type=%s\n",
-               sourcePos.file.striing(), sourcePos.line, String8(type).string());
+               sourcePos.file.striing(), sourcePos.line, String8(type).c_str());
     }
 #endif
     sp<Entry> e = getEntry(package, type, name, sourcePos, replace, params);
@@ -1996,9 +1998,9 @@
 {
     // First look for this in the included resources...
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         return true;
     }
@@ -2022,9 +2024,9 @@
 {
     // First look for this in the included resources...
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size());
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size());
     if (rid != 0) {
         return true;
     }
@@ -2051,7 +2053,7 @@
                                   const String16* defPackage)
 {
     String16 package, type, name;
-    if (!ResTable::expandResourceRef(ref.string(), ref.size(), &package, &type, &name,
+    if (!ResTable::expandResourceRef(ref.c_str(), ref.size(), &package, &type, &name,
                 defType, defPackage ? defPackage:&mAssetsPackage, NULL)) {
         return false;
     }
@@ -2115,17 +2117,17 @@
 
     // First look for this in the included resources...
     uint32_t rid = mAssets->getIncludedResources()
-            .identifierForName(name.string(), name.size(),
-                               attr16.string(), attr16.size(),
-                               package.string(), package.size());
+            .identifierForName(name.c_str(), name.size(),
+                               attr16.c_str(), attr16.size(),
+                               package.c_str(), package.size());
     if (rid != 0) {
-        source.error("Attribute \"%s\" has already been defined", String8(name).string());
+        source.error("Attribute \"%s\" has already been defined", String8(name).c_str());
         return false;
     }
 
     sp<ResourceTable::Entry> entry = getEntry(package, attr16, name, source, false);
     if (entry == NULL) {
-        source.error("Failed to create entry attr/%s", String8(name).string());
+        source.error("Failed to create entry attr/%s", String8(name).c_str());
         return false;
     }
 
@@ -2146,7 +2148,7 @@
                 formatItem.value != formatValue16) {
             source.error("Attribute \"%s\" already defined with incompatible format.\n"
                          "%s:%d: Original attribute defined here.",
-                         String8(name).string(), formatItem.sourcePos.file.string(),
+                         String8(name).c_str(), formatItem.sourcePos.file.c_str(),
                          formatItem.sourcePos.line);
             return false;
         }
@@ -2207,9 +2209,9 @@
     // First look for this in the included resources...
     uint32_t specFlags = 0;
     uint32_t rid = mAssets->getIncludedResources()
-        .identifierForName(name.string(), name.size(),
-                           type.string(), type.size(),
-                           package.string(), package.size(),
+        .identifierForName(name.c_str(), name.size(),
+                           type.c_str(), type.size(),
+                           package.c_str(), package.size(),
                            &specFlags);
     if (rid != 0) {
         if (onlyPublic && (specFlags & ResTable_typeSpec::SPEC_PUBLIC) == 0) {
@@ -2253,27 +2255,27 @@
     String16 package, type, name;
     bool refOnlyPublic = true;
     if (!ResTable::expandResourceRef(
-        ref.string(), ref.size(), &package, &type, &name,
+        ref.c_str(), ref.size(), &package, &type, &name,
         defType, defPackage ? defPackage:&mAssetsPackage,
         outErrorMsg, &refOnlyPublic)) {
         if (kIsDebug) {
-            printf("Expanding resource: ref=%s\n", String8(ref).string());
+            printf("Expanding resource: ref=%s\n", String8(ref).c_str());
             printf("Expanding resource: defType=%s\n",
-                    defType ? String8(*defType).string() : "NULL");
+                    defType ? String8(*defType).c_str() : "NULL");
             printf("Expanding resource: defPackage=%s\n",
-                    defPackage ? String8(*defPackage).string() : "NULL");
-            printf("Expanding resource: ref=%s\n", String8(ref).string());
+                    defPackage ? String8(*defPackage).c_str() : "NULL");
+            printf("Expanding resource: ref=%s\n", String8(ref).c_str());
             printf("Expanded resource: p=%s, t=%s, n=%s, res=0\n",
-                    String8(package).string(), String8(type).string(),
-                    String8(name).string());
+                    String8(package).c_str(), String8(type).c_str(),
+                    String8(name).c_str());
         }
         return 0;
     }
     uint32_t res = getResId(package, type, name, onlyPublic && refOnlyPublic);
     if (kIsDebug) {
         printf("Expanded resource: p=%s, t=%s, n=%s, res=%d\n",
-                String8(package).string(), String8(type).string(),
-                String8(name).string(), res);
+                String8(package).c_str(), String8(type).c_str(),
+                String8(name).c_str(), res);
     }
     if (res == 0) {
         if (outErrorMsg)
@@ -2284,7 +2286,7 @@
 
 bool ResourceTable::isValidResourceName(const String16& s)
 {
-    const char16_t* p = s.string();
+    const char16_t* p = s.c_str();
     bool first = true;
     while (*p) {
         if ((*p >= 'a' && *p <= 'z')
@@ -2315,7 +2317,7 @@
     if (style == NULL || style->size() == 0) {
         // Text is not styled so it can be any type...  let's figure it out.
         res = mAssets->getIncludedResources()
-            .stringToValue(outValue, &finalStr, str.string(), str.size(), preserveSpaces,
+            .stringToValue(outValue, &finalStr, str.c_str(), str.size(), preserveSpaces,
                             coerceType, attrID, NULL, &mAssetsPackage, this,
                            accessorCookie, attrType);
     } else {
@@ -2344,7 +2346,7 @@
             if (kIsDebug) {
                 printf("Adding to pool string style #%zu config %s: %s\n",
                         style != NULL ? style->size() : 0U,
-                        configStr.string(), String8(finalStr).string());
+                        configStr.c_str(), String8(finalStr).c_str());
             }
             if (style != NULL && style->size() > 0) {
                 outValue->data = pool->add(finalStr, *style, configTypeName, config);
@@ -2368,8 +2370,8 @@
 uint32_t ResourceTable::getCustomResource(
     const String16& package, const String16& type, const String16& name) const
 {
-    //printf("getCustomResource: %s %s %s\n", String8(package).string(),
-    //       String8(type).string(), String8(name).string());
+    //printf("getCustomResource: %s %s %s\n", String8(package).c_str(),
+    //       String8(type).c_str(), String8(name).c_str());
     sp<Package> p = mPackages.valueFor(package);
     if (p == NULL) return 0;
     sp<Type> t = p->getTypes().valueFor(type);
@@ -2400,7 +2402,7 @@
 
     if (mAssetsPackage != package) {
         mCurrentXmlPos.error("creating resource for external package %s: %s/%s.",
-                String8(package).string(), String8(type).string(), String8(name).string());
+                String8(package).c_str(), String8(type).c_str(), String8(name).c_str());
         if (package == String16("android")) {
             mCurrentXmlPos.printf("did you mean to use @+id instead of @+android:id?");
         }
@@ -2427,7 +2429,7 @@
     Res_value value;
     if (getItemValue(attrID, ResTable_map::ATTR_TYPE, &value)) {
         //printf("getAttributeType #%08x (%s): #%08x\n", attrID,
-        //       String8(getEntry(attrID)->getName()).string(), value.data);
+        //       String8(getEntry(attrID)->getName()).c_str(), value.data);
         *outType = value.data;
         return true;
     }
@@ -2481,7 +2483,7 @@
         vsnprintf(buf, sizeof(buf), fmt, ap);
         va_end(ap);
         ac->sourcePos.error("Error: %s (at '%s' with value '%s').\n",
-                            buf, ac->attr.string(), ac->value.string());
+                            buf, ac->attr.c_str(), ac->value.c_str());
     }
 }
 
@@ -2493,7 +2495,7 @@
         const size_t N = e->getBag().size();
         for (size_t i=0; i<N; i++) {
             const String16& key = e->getBag().keyAt(i);
-            if (key.size() > 0 && key.string()[0] != '^') {
+            if (key.size() > 0 && key.c_str()[0] != '^') {
                 outKeys->add(key);
             }
         }
@@ -2506,14 +2508,14 @@
     uint32_t attrID, const char16_t* name, size_t nameLen,
     Res_value* outValue)
 {
-    //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).string());
+    //printf("getAttributeEnum #%08x %s\n", attrID, String8(name, nameLen).c_str());
     String16 nameStr(name, nameLen);
     sp<const Entry> e = getEntry(attrID);
     if (e != NULL) {
         const size_t N = e->getBag().size();
         for (size_t i=0; i<N; i++) {
-            //printf("Comparing %s to %s\n", String8(name, nameLen).string(),
-            //       String8(e->getBag().keyAt(i)).string());
+            //printf("Comparing %s to %s\n", String8(name, nameLen).c_str(),
+            //       String8(e->getBag().keyAt(i)).c_str());
             if (e->getBag().keyAt(i) == nameStr) {
                 return getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, outValue);
             }
@@ -2529,7 +2531,7 @@
     outValue->dataType = Res_value::TYPE_INT_HEX;
     outValue->data = 0;
 
-    //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).string());
+    //printf("getAttributeFlags #%08x %s\n", attrID, String8(name, nameLen).c_str());
     String16 nameStr(name, nameLen);
     sp<const Entry> e = getEntry(attrID);
     if (e != NULL) {
@@ -2546,8 +2548,8 @@
             String16 nameStr(start, pos-start);
             size_t i;
             for (i=0; i<N; i++) {
-                //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).string(),
-                //       String8(e->getBag().keyAt(i)).string());
+                //printf("Comparing \"%s\" to \"%s\"\n", String8(nameStr).c_str(),
+                //       String8(e->getBag().keyAt(i)).c_str());
                 if (e->getBag().keyAt(i) == nameStr) {
                     Res_value val;
                     bool got = getItemValue(attrID, e->getBag().valueAt(i).bagKeyId, &val);
@@ -2753,7 +2755,7 @@
                         if (mHasDefaultLocalization.find(c->getName())
                                 == mHasDefaultLocalization.end()) {
                             // printf("Skip symbol [%08x] %s\n", rid,
-                            //          String8(c->getName()).string());
+                            //          String8(c->getName()).c_str());
                             continue;
                         }
                     }
@@ -2763,7 +2765,7 @@
                     String16 comment(c->getComment());
                     typeSymbols->appendComment(String8(c->getName()), comment, c->getPos());
                     //printf("Type symbol [%08x] %s comment: %s\n", rid,
-                    //        String8(c->getName()).string(), String8(comment).string());
+                    //        String8(c->getName()).c_str(), String8(comment).c_str());
                     comment = c->getTypeComment();
                     typeSymbols->appendTypeComment(String8(c->getName()), comment);
                 }
@@ -2809,10 +2811,10 @@
         // Look for strings with no default localization
         if (configSrcMap.count(defaultLocale) == 0) {
             SourcePos().warning("string '%s' has no default translation.",
-                    String8(nameIter.first).string());
+                    String8(nameIter.first).c_str());
             if (mBundle->getVerbose()) {
                 for (const auto& locale : configSrcMap) {
-                    locale.second.printf("locale %s found", locale.first.string());
+                    locale.second.printf("locale %s found", locale.first.c_str());
                 }
             }
             // !!! TODO: throw an error here in some circumstances
@@ -2820,7 +2822,7 @@
 
         // Check that all requested localizations are present for this string
         if (mBundle->getConfigurations().size() > 0 && mBundle->getRequireLocalization()) {
-            const char* allConfigs = mBundle->getConfigurations().string();
+            const char* allConfigs = mBundle->getConfigurations().c_str();
             const char* start = allConfigs;
             const char* comma;
 
@@ -2830,10 +2832,10 @@
                 String8 config;
                 comma = strchr(start, ',');
                 if (comma != NULL) {
-                    config.setTo(start, comma - start);
+                    config = String8(start, comma - start);
                     start = comma + 1;
                 } else {
-                    config.setTo(start);
+                    config = start;
                 }
 
                 if (!locale.initFromFilterString(config)) {
@@ -2847,7 +2849,7 @@
                         // requiring a specific regional localization [e.g. de_DE] but there is an
                         // available string in the generic language localization [e.g. de];
                         // consider that string to have fulfilled the localization requirement.
-                        String8 region(config.string(), 2);
+                        String8 region(config.c_str(), 2);
                         if (configSrcMap.find(region) == configSrcMap.end() &&
                                 configSrcMap.count(defaultLocale) == 0) {
                             missingConfigs.insert(config);
@@ -2859,12 +2861,12 @@
             if (!missingConfigs.empty()) {
                 String8 configStr;
                 for (const auto& iter : missingConfigs) {
-                    configStr.appendFormat(" %s", iter.string());
+                    configStr.appendFormat(" %s", iter.c_str());
                 }
                 SourcePos().warning("string '%s' is missing %u required localizations:%s",
-                        String8(nameIter.first).string(),
+                        String8(nameIter.first).c_str(),
                         (unsigned int)missingConfigs.size(),
-                        configStr.string());
+                        configStr.c_str());
             }
         }
     }
@@ -3021,7 +3023,7 @@
         header->header.type = htods(RES_TABLE_PACKAGE_TYPE);
         header->header.headerSize = htods(sizeof(*header));
         header->id = htodl(static_cast<uint32_t>(p->getAssignedId()));
-        strcpy16_htod(header->name, p->getName().string());
+        strcpy16_htod(header->name, p->getName().c_str());
 
         // Write the string blocks.
         const size_t typeStringsStart = data->getSize();
@@ -3061,7 +3063,7 @@
             sp<Type> t = p->getTypes().valueFor(typeName);
             LOG_ALWAYS_FATAL_IF(t == NULL && typeName != String16("<empty>"),
                                 "Type name %s not found",
-                                String8(typeName).string());
+                                String8(typeName).c_str());
             if (t == NULL) {
                 continue;
             }
@@ -3251,7 +3253,7 @@
 
             // If we're building splits, then each invocation of the flattening
             // step will have 'missing' entries. Don't warn/error for this case.
-            if (bundle->getSplitConfigurations().isEmpty()) {
+            if (bundle->getSplitConfigurations().empty()) {
                 bool missing_entry = false;
                 const char* log_prefix = bundle->getErrorOnMissingConfigEntry() ?
                         "error" : "warning";
@@ -3260,7 +3262,7 @@
                         sp<ConfigList> c = t->getOrderedConfigs().itemAt(i);
                         if (c != NULL) {
                             fprintf(stderr, "%s: no entries written for %s/%s (0x%08zx)\n", log_prefix,
-                                    String8(typeName).string(), String8(c->getName()).string(),
+                                    String8(typeName).c_str(), String8(c->getName()).c_str(),
                                     Res_MAKEID(p->getAssignedId() - 1, ti, i));
                         }
                         missing_entry = true;
@@ -3359,7 +3361,7 @@
             sp<Package> libPackage = libs[i];
             if (kIsDebug) {
                 fprintf(stderr, "  Entry %s -> 0x%02x\n",
-                        String8(libPackage->getName()).string(),
+                        String8(libPackage->getName()).c_str(),
                         (uint8_t)libPackage->getAssignedId());
             }
 
@@ -3367,7 +3369,7 @@
                     entryStart, sizeof(ResTable_lib_entry));
             memset(entry, 0, sizeof(*entry));
             entry->packageId = htodl(libPackage->getAssignedId());
-            strcpy16_htod(entry->packageName, libPackage->getName().string());
+            strcpy16_htod(entry->packageName, libPackage->getName().c_str());
         }
     }
     return NO_ERROR;
@@ -3435,13 +3437,13 @@
                         const SourcePos& pos = c->getEntries().valueAt(k)->getPos();
                         if (pos.file != "") {
                             fprintf(fp,"  <!-- Declared at %s:%d -->\n",
-                                    pos.file.string(), pos.line);
+                                    pos.file.c_str(), pos.line);
                         }
                     }
                 }
                 fprintf(fp, "  <public type=\"%s\" name=\"%s\" id=\"0x%08x\" />\n",
-                        String8(t->getName()).string(),
-                        String8(c->getName()).string(),
+                        String8(t->getName()).c_str(),
+                        String8(c->getName()).c_str(),
                         getResId(pkg, t, c->getEntryIndex()));
             }
         }
@@ -3501,8 +3503,8 @@
     }
     sourcePos.error("Resource entry %s is already defined as a single item.\n"
                     "%s:%d: Originally defined here.\n",
-                    String8(mName).string(),
-                    mItem.sourcePos.file.string(), mItem.sourcePos.line);
+                    String8(mName).c_str(),
+                    mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
     return UNKNOWN_ERROR;
 }
 
@@ -3517,21 +3519,21 @@
     if (mType == TYPE_BAG) {
         if (mBag.size() == 0) {
             sourcePos.error("Resource entry %s is already defined as a bag.",
-                    String8(mName).string());
+                    String8(mName).c_str());
         } else {
             const Item& item(mBag.valueAt(0));
             sourcePos.error("Resource entry %s is already defined as a bag.\n"
                             "%s:%d: Originally defined here.\n",
-                            String8(mName).string(),
-                            item.sourcePos.file.string(), item.sourcePos.line);
+                            String8(mName).c_str(),
+                            item.sourcePos.file.c_str(), item.sourcePos.line);
         }
         return UNKNOWN_ERROR;
     }
     if ( (mType != TYPE_UNKNOWN) && (overwrite == false) ) {
         sourcePos.error("Resource entry %s is already defined.\n"
                         "%s:%d: Originally defined here.\n",
-                        String8(mName).string(),
-                        mItem.sourcePos.file.string(), mItem.sourcePos.line);
+                        String8(mName).c_str(),
+                        mItem.sourcePos.file.c_str(), mItem.sourcePos.line);
         return UNKNOWN_ERROR;
     }
 
@@ -3562,12 +3564,12 @@
             const Item& item(mBag.valueAt(origKey));
             sourcePos.error("Resource entry %s already has bag item %s.\n"
                     "%s:%d: Originally defined here.\n",
-                    String8(mName).string(), String8(key).string(),
-                    item.sourcePos.file.string(), item.sourcePos.line);
+                    String8(mName).c_str(), String8(key).c_str(),
+                    item.sourcePos.file.c_str(), item.sourcePos.line);
             return UNKNOWN_ERROR;
         }
         //printf("Replacing %s with %s\n",
-        //       String8(mBag.valueFor(key).value).string(), String8(value).string());
+        //       String8(mBag.valueFor(key).value).c_str(), String8(value).c_str());
         mBag.replaceValueFor(key, item);
     }
 
@@ -3611,8 +3613,8 @@
                 String16 value("false");
                 if (kIsDebug) {
                     fprintf(stderr, "Generating %s:id/%s\n",
-                            String8(package).string(),
-                            String8(key).string());
+                            String8(package).c_str(),
+                            String8(key).c_str());
                 }
                 status_t err = table->addEntry(SourcePos(String8("<generated>"), 0), package,
                                                id16, key, value);
@@ -3624,10 +3626,10 @@
 
 #if 1
 //             fprintf(stderr, "ERROR: Bag attribute '%s' has not been defined.\n",
-//                     String8(key).string());
+//                     String8(key).c_str());
 //             const Item& item(mBag.valueAt(i));
 //             fprintf(stderr, "Referenced from file %s line %d\n",
-//                     item.sourcePos.file.string(), item.sourcePos.line);
+//                     item.sourcePos.file.c_str(), item.sourcePos.line);
 //             return UNKNOWN_ERROR;
 #else
             char numberStr[16];
@@ -3660,7 +3662,7 @@
             mParentId = table->getResId(mParent, &style16, NULL, &errorMsg);
             if (mParentId == 0) {
                 mPos.error("Error retrieving parent for item: %s '%s'.\n",
-                        errorMsg, String8(mParent).string());
+                        errorMsg, String8(mParent).c_str());
                 hasErrors = true;
             }
         }
@@ -3670,11 +3672,11 @@
             Item& it = mBag.editValueAt(i);
             it.bagKeyId = table->getResId(key,
                     it.isId ? &id16 : &attr16, NULL, &errorMsg);
-            //printf("Bag key of %s: #%08x\n", String8(key).string(), it.bagKeyId);
+            //printf("Bag key of %s: #%08x\n", String8(key).c_str(), it.bagKeyId);
             if (it.bagKeyId == 0) {
                 it.sourcePos.error("Error: %s: %s '%s'.\n", errorMsg,
-                        String8(it.isId ? id16 : attr16).string(),
-                        String8(key).string());
+                        String8(it.isId ? id16 : attr16).c_str(),
+                        String8(key).c_str());
                 hasErrors = true;
             }
         }
@@ -3709,7 +3711,7 @@
         }
     } else {
         mPos.error("Error: entry %s is not a single item or a bag.\n",
-                   String8(mName).string());
+                   String8(mName).c_str());
         return UNKNOWN_ERROR;
     }
     return NO_ERROR;
@@ -3732,7 +3734,7 @@
         }
     } else {
         mPos.error("Error: entry %s is not a single item or a bag.\n",
-                   String8(mName).string());
+                   String8(mName).c_str());
         return UNKNOWN_ERROR;
     }
     return NO_ERROR;
@@ -3768,7 +3770,7 @@
         par.data = htodl(it.parsedValue.data);
         #if 0
         printf("Writing item (%s): type=%d, data=0x%x, res0=0x%x\n",
-               String8(mName).string(), it.parsedValue.dataType,
+               String8(mName).c_str(), it.parsedValue.dataType,
                it.parsedValue.data, par.res0);
         #endif
         err = data->writeData(&par, it.parsedValue.size);
@@ -3852,7 +3854,7 @@
     int32_t entryIdx = Res_GETENTRY(ident);
     if (entryIdx < 0) {
         sourcePos.error("Public resource %s/%s has an invalid 0 identifier (0x%08x).\n",
-                String8(mName).string(), String8(name).string(), ident);
+                String8(mName).c_str(), String8(name).c_str(), ident);
         return UNKNOWN_ERROR;
     }
     #endif
@@ -3863,7 +3865,7 @@
         if (mPublicIndex > 0 && mPublicIndex != typeIdx) {
             sourcePos.error("Public resource %s/%s has conflicting type codes for its"
                     " public identifiers (0x%x vs 0x%x).\n",
-                    String8(mName).string(), String8(name).string(),
+                    String8(mName).c_str(), String8(name).c_str(),
                     mPublicIndex, typeIdx);
             return UNKNOWN_ERROR;
         }
@@ -3882,8 +3884,8 @@
             sourcePos.error("Public resource %s/%s has conflicting public identifiers"
                     " (0x%08x vs 0x%08x).\n"
                     "%s:%d: Originally defined here.\n",
-                    String8(mName).string(), String8(name).string(), p.ident, ident,
-                    p.sourcePos.file.string(), p.sourcePos.line);
+                    String8(mName).c_str(), String8(name).c_str(), p.ident, ident,
+                    p.sourcePos.file.c_str(), p.sourcePos.line);
             return UNKNOWN_ERROR;
         }
     }
@@ -3909,7 +3911,7 @@
         if (overlay && !autoAddOverlay && mCanAddEntries.indexOf(entry) < 0) {
             sourcePos.error("Resource at %s appears in overlay but not"
                             " in the base package; use <add-resource> to add.\n",
-                            String8(entry).string());
+                            String8(entry).c_str());
             return NULL;
         }
         c = new ConfigList(entry, sourcePos);
@@ -3931,7 +3933,7 @@
                 printf("New entry at %s:%d: imsi:%d/%d lang:%c%c cnt:%c%c "
                     "orien:%d touch:%d density:%d key:%d inp:%d nav:%d sz:%dx%d "
                     "sw%ddp w%ddp h%ddp layout:%d\n",
-                      sourcePos.file.string(), sourcePos.line,
+                      sourcePos.file.c_str(), sourcePos.line,
                       config->mcc, config->mnc,
                       config->language[0] ? config->language[0] : '-',
                       config->language[1] ? config->language[1] : '-',
@@ -3951,7 +3953,7 @@
                       config->screenLayout);
             } else {
                 printf("New entry at %s:%d: NULL config\n",
-                        sourcePos.file.string(), sourcePos.line);
+                        sourcePos.file.c_str(), sourcePos.line);
             }
         }
         e = new Entry(entry, sourcePos);
@@ -4032,11 +4034,11 @@
         const Public& p = mPublic.valueAt(j);
         int32_t idx = Res_GETENTRY(p.ident);
         //printf("Looking for entry \"%s\"/\"%s\" (0x%08x) in %d...\n",
-        //       String8(mName).string(), String8(name).string(), p.ident, N);
+        //       String8(mName).c_str(), String8(name).c_str(), p.ident, N);
         bool found = false;
         for (i=0; i<N; i++) {
             sp<ConfigList> e = origOrder.itemAt(i);
-            //printf("#%d: \"%s\"\n", i, String8(e->getName()).string());
+            //printf("#%d: \"%s\"\n", i, String8(e->getName()).c_str());
             if (e->getName() == name) {
                 if (idx >= (int32_t)mOrderedConfigs.size()) {
                     mOrderedConfigs.resize(idx + 1);
@@ -4056,10 +4058,10 @@
                     p.sourcePos.error("Multiple entry names declared for public entry"
                             " identifier 0x%x in type %s (%s vs %s).\n"
                             "%s:%d: Originally defined here.",
-                            idx+1, String8(mName).string(),
-                            String8(oe->getName()).string(),
-                            String8(name).string(),
-                            oe->getPublicSourcePos().file.string(),
+                            idx+1, String8(mName).c_str(),
+                            String8(oe->getName()).c_str(),
+                            String8(name).c_str(),
+                            oe->getPublicSourcePos().file.c_str(),
                             oe->getPublicSourcePos().line);
                     hasError = true;
                 }
@@ -4068,7 +4070,7 @@
 
         if (!found) {
             p.sourcePos.error("Public symbol %s/%s declared here is not defined.",
-                    String8(mName).string(), String8(name).string());
+                    String8(mName).c_str(), String8(name).c_str());
             hasError = true;
         }
     }
@@ -4189,9 +4191,9 @@
                 t->getFirstPublicSourcePos().error("Multiple type names declared for public type"
                         " identifier 0x%x (%s vs %s).\n"
                         "%s:%d: Originally defined here.",
-                        idx, String8(ot->getName()).string(),
-                        String8(t->getName()).string(),
-                        ot->getFirstPublicSourcePos().file.string(),
+                        idx, String8(ot->getName()).c_str(),
+                        String8(t->getName()).c_str(),
+                        ot->getFirstPublicSourcePos().file.c_str(),
                         ot->getFirstPublicSourcePos().line);
                 return UNKNOWN_ERROR;
             }
@@ -4399,8 +4401,8 @@
         const Item& it = e->getBag().valueAt(i);
         if (it.bagKeyId == 0) {
             fprintf(stderr, "warning: ID not yet assigned to '%s' in bag '%s'\n",
-                    String8(e->getName()).string(),
-                    String8(e->getBag().keyAt(i)).string());
+                    String8(e->getName()).c_str(),
+                    String8(e->getBag().keyAt(i)).c_str());
         }
         if (it.bagKeyId == attrID) {
             return &it;
@@ -4427,8 +4429,8 @@
                 }
             }
             fprintf(stderr, "warning: Circular reference detected in key '%s' of bag '%s'\n",
-                    String8(e->getName()).string(),
-                    String8(e->getBag().keyAt(i)).string());
+                    String8(e->getName()).c_str(),
+                    String8(e->getBag().keyAt(i)).c_str());
             return false;
         }
         item->evaluating = true;
@@ -4436,7 +4438,7 @@
         if (kIsDebug) {
             if (res) {
                 printf("getItemValue of #%08x[#%08x] (%s): type=#%08x, data=#%08x\n",
-                       resID, attrID, String8(getEntry(resID)->getName()).string(),
+                       resID, attrID, String8(getEntry(resID)->getName()).c_str(),
                        outValue->dataType, outValue->data);
             } else {
                 printf("getItemValue of #%08x[#%08x]: failed\n",
@@ -4713,10 +4715,10 @@
                         entriesToAdd[i].value->getPos()
                                 .printf("using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
                                         entriesToAdd[i].key.sdkVersion,
-                                        String8(p->getName()).string(),
-                                        String8(t->getName()).string(),
-                                        String8(entriesToAdd[i].value->getName()).string(),
-                                        entriesToAdd[i].key.toString().string());
+                                        String8(p->getName()).c_str(),
+                                        String8(t->getName()).c_str(),
+                                        String8(entriesToAdd[i].value->getName()).c_str(),
+                                        entriesToAdd[i].key.toString().c_str());
                     }
 
                     sp<Entry> newEntry = t->getEntry(c->getName(),
@@ -4801,9 +4803,9 @@
     sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
             AaptGroupEntry(newConfig), target->getResourceType());
     String8 resPath = String8::format("res/%s/%s.xml",
-            newFile->getGroupEntry().toDirName(target->getResourceType()).string(),
-            String8(resourceName).string());
-    resPath.convertToResPath();
+            newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
+            String8(resourceName).c_str());
+    convertToResPath(resPath);
 
     // Add a resource table entry.
     addEntry(SourcePos(),
@@ -4857,7 +4859,7 @@
 
     Vector<sp<XMLNode> > nodesToVisit;
     nodesToVisit.push(root);
-    while (!nodesToVisit.isEmpty()) {
+    while (!nodesToVisit.empty()) {
         sp<XMLNode> node = nodesToVisit.top();
         nodesToVisit.pop();
 
@@ -4893,10 +4895,10 @@
                 if (bundle->getVerbose()) {
                     SourcePos(node->getFilename(), node->getStartLineNumber()).printf(
                             "removing attribute %s%s%s from <%s>",
-                            String8(attr.ns).string(),
+                            String8(attr.ns).c_str(),
                             (attr.ns.size() == 0 ? "" : ":"),
-                            String8(attr.name).string(),
-                            String8(node->getElementName()).string());
+                            String8(attr.name).c_str(),
+                            String8(node->getElementName()).c_str());
                 }
                 node->removeAttribute(i);
                 i--;
@@ -4925,19 +4927,19 @@
         sp<AaptFile> newFile = new AaptFile(target->getSourceFile(),
                 AaptGroupEntry(newConfig), target->getResourceType());
         String8 resPath = String8::format("res/%s/%s.xml",
-                newFile->getGroupEntry().toDirName(target->getResourceType()).string(),
-                String8(resourceName).string());
-        resPath.convertToResPath();
+                newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
+                String8(resourceName).c_str());
+        convertToResPath(resPath);
 
         // Add a resource table entry.
         if (bundle->getVerbose()) {
             SourcePos(target->getSourceFile(), -1).printf(
                     "using v%d attributes; synthesizing resource %s:%s/%s for configuration %s.",
                     newConfig.sdkVersion,
-                    mAssets->getPackage().string(),
-                    newFile->getResourceType().string(),
-                    String8(resourceName).string(),
-                    newConfig.toString().string());
+                    mAssets->getPackage().c_str(),
+                    newFile->getResourceType().c_str(),
+                    String8(resourceName).c_str(),
+                    newConfig.toString().c_str());
         }
 
         addEntry(SourcePos(),
@@ -5114,8 +5116,8 @@
         sp<XMLNode> nestedRoot = findOnlyChildElement(child);
         if (nestedRoot == NULL) {
             source.error("<%s:%s> must have exactly one child element",
-                         String8(child->getElementNamespace()).string(),
-                         String8(child->getElementName()).string());
+                         String8(child->getElementNamespace()).c_str(),
+                         String8(child->getElementName()).c_str());
             return UNKNOWN_ERROR;
         }
 
@@ -5130,7 +5132,7 @@
         // Parse the attribute name.
         const char* errorMsg = NULL;
         String16 attrPackage, attrType, attrName;
-        bool result = ResTable::expandResourceRef(attr->string.string(),
+        bool result = ResTable::expandResourceRef(attr->string.c_str(),
                                                   attr->string.size(),
                                                   &attrPackage, &attrType, &attrName,
                                                   &kAttr16, &kAssetPackage16,
@@ -5156,11 +5158,11 @@
             // This child element will be extracted into its own resource file.
             // Generate a name and path for it from its parent.
             nestedResourceName = String8::format("%s_%d",
-                        String8(resourceName).string(), suffix++);
+                        String8(resourceName).c_str(), suffix++);
             nestedResourcePath = String8::format("res/%s/%s.xml",
                         target->getGroupEntry().toDirName(target->getResourceType())
-                                               .string(),
-                        nestedResourceName.string());
+                                               .c_str(),
+                        nestedResourceName.c_str());
 
             // Lookup or create the entry for this name.
             sp<Entry> entry = getEntry(kAssetPackage16,
@@ -5187,20 +5189,20 @@
 
         if (bundle->getVerbose()) {
             source.printf("generating nested resource %s:%s/%s",
-                    mAssets->getPackage().string(), target->getResourceType().string(),
-                    nestedResourceName.string());
+                    mAssets->getPackage().c_str(), target->getResourceType().c_str(),
+                    nestedResourceName.c_str());
         }
 
         // Build the attribute reference and assign it to the parent.
         String16 nestedResourceRef = String16(String8::format("@%s:%s/%s",
-                    mAssets->getPackage().string(), target->getResourceType().string(),
-                    nestedResourceName.string()));
+                    mAssets->getPackage().c_str(), target->getResourceType().c_str(),
+                    nestedResourceName.c_str()));
 
         String16 attrNs = buildNamespace(attrPackage);
         if (parent->getAttribute(attrNs, attrName) != NULL) {
             SourcePos(parent->getFilename(), parent->getStartLineNumber())
                     .error("parent of nested resource already defines attribute '%s:%s'",
-                           String8(attrPackage).string(), String8(attrName).string());
+                           String8(attrPackage).c_str(), String8(attrName).c_str());
             return UNKNOWN_ERROR;
         }
 
diff --git a/tools/aapt/SourcePos.cpp b/tools/aapt/SourcePos.cpp
index 3864320..354a65c 100644
--- a/tools/aapt/SourcePos.cpp
+++ b/tools/aapt/SourcePos.cpp
@@ -78,14 +78,14 @@
         break;
     }
     
-    if (!this->file.isEmpty()) {
+    if (!this->file.empty()) {
         if (this->line >= 0) {
-            fprintf(to, "%s:%d: %s%s\n", this->file.string(), this->line, type, this->error.string());
+            fprintf(to, "%s:%d: %s%s\n", this->file.c_str(), this->line, type, this->error.c_str());
         } else {
-            fprintf(to, "%s: %s%s\n", this->file.string(), type, this->error.string());
+            fprintf(to, "%s: %s%s\n", this->file.c_str(), type, this->error.c_str());
         }
     } else {
-        fprintf(to, "%s%s\n", type, this->error.string());
+        fprintf(to, "%s%s\n", type, this->error.c_str());
     }
 }
 
diff --git a/tools/aapt/StringPool.cpp b/tools/aapt/StringPool.cpp
index 6cacd32..1af8d6f 100644
--- a/tools/aapt/StringPool.cpp
+++ b/tools/aapt/StringPool.cpp
@@ -67,7 +67,7 @@
     const size_t NS = pool->size();
     for (size_t s=0; s<NS; s++) {
         auto str = pool->string8ObjectAt(s);
-        printf("String #" ZD ": %s\n", (ZD_TYPE) s, (str.has_value() ? str->string() : ""));
+        printf("String #" ZD ": %s\n", (ZD_TYPE) s, (str.has_value() ? str->c_str() : ""));
     }
 }
 
@@ -139,7 +139,7 @@
     if (eidx < 0) {
         eidx = mEntries.add(entry(value));
         if (eidx < 0) {
-            fprintf(stderr, "Failure adding string %s\n", String8(value).string());
+            fprintf(stderr, "Failure adding string %s\n", String8(value).c_str());
             return eidx;
         }
     }
@@ -148,7 +148,7 @@
         entry& ent = mEntries.editItemAt(eidx);
         if (kIsDebug) {
             printf("*** adding config type name %s, was %s\n",
-                    configTypeName->string(), ent.configTypeName.string());
+                    configTypeName->c_str(), ent.configTypeName.c_str());
         }
         if (ent.configTypeName.size() <= 0) {
             ent.configTypeName = *configTypeName;
@@ -166,7 +166,7 @@
             if (cmp >= 0) {
                 if (cmp > 0) {
                     if (kIsDebug) {
-                        printf("*** inserting config: %s\n", config->toString().string());
+                        printf("*** inserting config: %s\n", config->toString().c_str());
                     }
                     ent.configs.insertAt(*config, addPos);
                 }
@@ -175,7 +175,7 @@
         }
         if (addPos >= ent.configs.size()) {
             if (kIsDebug) {
-                printf("*** adding config: %s\n", config->toString().string());
+                printf("*** adding config: %s\n", config->toString().c_str());
             }
             ent.configs.add(*config);
         }
@@ -195,7 +195,7 @@
 
     if (kIsDebug) {
         printf("Adding string %s to pool: pos=%zd eidx=%zd vidx=%zd\n",
-                String8(value).string(), pos, eidx, vidx);
+                String8(value).c_str(), pos, eidx, vidx);
     }
 
     return pos;
@@ -286,13 +286,13 @@
 
     for (size_t i=0; i<N; i++) {
         printf("#%d was %d: %s\n", i, newPosToOriginalPos[i],
-                mEntries[mEntryArray[newPosToOriginalPos[i]]].makeConfigsString().string());
+                mEntries[mEntryArray[newPosToOriginalPos[i]]].makeConfigsString().c_str());
         entries.add(mEntries[mEntryArray[i]]);
     }
 
     for (size_t i=0; i<entries.size(); i++) {
         printf("Sorted config #%d: %s\n", i,
-                entries[i].makeConfigsString().string());
+                entries[i].makeConfigsString().c_str());
     }
 #endif
 
@@ -363,8 +363,8 @@
     printf("FINAL SORTED STRING CONFIGS:\n");
     for (size_t i=0; i<mEntries.size(); i++) {
         const entry& ent = mEntries[i];
-        printf("#" ZD " %s: %s\n", (ZD_TYPE)i, ent.makeConfigsString().string(),
-                String8(ent.value).string());
+        printf("#" ZD " %s: %s\n", (ZD_TYPE)i, ent.makeConfigsString().c_str(),
+                String8(ent.value).c_str());
     }
 #endif
 }
@@ -415,7 +415,7 @@
             ssize_t idx = add(span.name, true);
             if (idx < 0) {
                 fprintf(stderr, "Error adding span for style tag '%s'\n",
-                        String8(span.name).string());
+                        String8(span.name).c_str());
                 return idx;
             }
             span.span.name.index = (uint32_t)idx;
@@ -472,13 +472,13 @@
 
             ENCODE_LENGTH(strings, sizeof(uint8_t), encSize)
 
-            strncpy((char*)strings, encStr, encSize+1);
+            strncpy((char*)strings, encStr.c_str(), encSize + 1);
         } else {
             char16_t* strings = (char16_t*)dat;
 
             ENCODE_LENGTH(strings, sizeof(char16_t), strSize)
 
-            strcpy16_htod(strings, ent.value);
+            strcpy16_htod(strings, ent.value.c_str());
         }
 
         strPos += totalSize;
@@ -571,7 +571,7 @@
         if (kIsDebug) {
             printf("Writing entry #%zu: \"%s\" ent=%zu off=%zu\n",
                     i,
-                    String8(ent.value).string(),
+                    String8(ent.value).c_str(),
                     mEntryArray[i],
                     ent.offset);
         }
@@ -591,8 +591,8 @@
     const Vector<size_t>* indices = offsetsForString(val);
     ssize_t res = indices != NULL && indices->size() > 0 ? indices->itemAt(0) : -1;
     if (kIsDebug) {
-        printf("Offset for string %s: %zd (%s)\n", String8(val).string(), res,
-                res >= 0 ? String8(mEntries[mEntryArray[res]].value).string() : String8());
+        printf("Offset for string %s: %zd (%s)\n", String8(val).c_str(), res,
+               res >= 0 ? String8(mEntries[mEntryArray[res]].value).c_str() : "");
     }
     return res;
 }
diff --git a/tools/aapt/Symbol.h b/tools/aapt/Symbol.h
index e157541..de1d60c 100644
--- a/tools/aapt/Symbol.h
+++ b/tools/aapt/Symbol.h
@@ -68,9 +68,9 @@
 
 android::String8 Symbol::toString() const {
     return android::String8::format("%s:%s/%s (0x%08x)",
-            android::String8(package).string(),
-            android::String8(type).string(),
-            android::String8(name).string(),
+            android::String8(package).c_str(),
+            android::String8(type).c_str(),
+            android::String8(name).c_str(),
             (int) id);
 }
 
diff --git a/tools/aapt/Utils.cpp b/tools/aapt/Utils.cpp
new file mode 100644
index 0000000..946916a
--- /dev/null
+++ b/tools/aapt/Utils.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2005 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 "Utils.h"
+
+#include <utils/Compat.h>
+
+// Separator used by resource paths. This is not platform dependent contrary
+// to OS_PATH_SEPARATOR.
+#define RES_PATH_SEPARATOR '/'
+
+using android::String8;
+
+void convertToResPath([[maybe_unused]] String8& s) {
+#if OS_PATH_SEPARATOR != RES_PATH_SEPARATOR
+    size_t len = s.length();
+    if (len > 0) {
+        char* buf = s.lockBuffer(len);
+        for (char* end = buf + len; buf < end; ++buf) {
+            if (*buf == OS_PATH_SEPARATOR) *buf = RES_PATH_SEPARATOR;
+        }
+        s.unlockBuffer(len);
+    }
+#endif
+}
+
+String8 walkPath(const String8& path, String8* outRemains) {
+    const char* cp;
+    const char* const str = path.c_str();
+    const char* buf = str;
+
+    cp = strchr(buf, OS_PATH_SEPARATOR);
+    if (cp == buf) {
+        // don't include a leading '/'.
+        buf = buf + 1;
+        cp = strchr(buf, OS_PATH_SEPARATOR);
+    }
+
+    if (cp == nullptr) {
+        String8 res = buf != str ? String8(buf) : path;
+        if (outRemains) *outRemains = String8();
+        return res;
+    }
+
+    String8 res(buf, cp - buf);
+    if (outRemains) *outRemains = String8(cp + 1);
+    return res;
+}
diff --git a/tools/aapt/Utils.h b/tools/aapt/Utils.h
new file mode 100644
index 0000000..f0d6979
--- /dev/null
+++ b/tools/aapt/Utils.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2005 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.
+ */
+
+#pragma once
+
+// This file contains cruft that used to be in libutils' String8, that's only
+// used for aapt.
+
+#include <utils/String8.h>
+
+// Converts all separators in this string to /, the default path
+// separator.
+// If the default OS separator is backslash, this converts all
+// backslashes to slashes, in-place. Otherwise it does nothing.
+void convertToResPath(android::String8&);
+
+/**
+ * Retrieve the front (root dir) component.  Optionally also return the
+ * remaining components.
+ *
+ * "/tmp/foo/bar.c" --> "tmp" (remain = "foo/bar.c")
+ * "/tmp" --> "tmp" (remain = "")
+ * "bar.c" --> "bar.c" (remain = "")
+ */
+android::String8 walkPath(const android::String8& path, android::String8* outRemains = nullptr);
diff --git a/tools/aapt/XMLNode.cpp b/tools/aapt/XMLNode.cpp
index 69392d6..1a648c0 100644
--- a/tools/aapt/XMLNode.cpp
+++ b/tools/aapt/XMLNode.cpp
@@ -66,14 +66,14 @@
 
 String16 getNamespaceResourcePackage(const String16& appPackage, const String16& namespaceUri, bool* outIsPublic)
 {
-    //printf("%s starts with %s?\n", String8(namespaceUri).string(),
-    //       String8(RESOURCES_PREFIX).string());
+    //printf("%s starts with %s?\n", String8(namespaceUri).c_str(),
+    //       String8(RESOURCES_PREFIX).c_str());
     size_t prefixSize;
     bool isPublic = true;
     if(namespaceUri.startsWith(RESOURCES_PREFIX_AUTO_PACKAGE)) {
         if (kIsDebug) {
-            printf("Using default application package: %s -> %s\n", String8(namespaceUri).string(),
-                   String8(appPackage).string());
+            printf("Using default application package: %s -> %s\n", String8(namespaceUri).c_str(),
+                   String8(appPackage).c_str());
         }
         isPublic = true;
         return appPackage;
@@ -88,7 +88,7 @@
     }
 
     //printf("YES!\n");
-    //printf("namespace: %s\n", String8(String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize)).string());
+    //printf("namespace: %s\n", String8(String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize)).c_str());
     if (outIsPublic) *outIsPublic = isPublic;
     return String16(namespaceUri, namespaceUri.size()-prefixSize, prefixSize);
 }
@@ -97,7 +97,7 @@
                                ResXMLTree* inXml,
                                const String16& str16)
 {
-    const char16_t* str = str16.string();
+    const char16_t* str = str16.c_str();
     const char16_t* p = str;
     const char16_t* end = str + str16.size();
 
@@ -223,7 +223,7 @@
             String16 text(inXml->getText(&len));
             if (firstTime && text.size() > 0) {
                 firstTime = false;
-                if (text.string()[0] == '@') {
+                if (text.c_str()[0] == '@') {
                     // If this is a resource reference, don't do the pseudoloc.
                     pseudolocalize = NO_PSEUDOLOCALIZATION;
                     pseudo.setMethod(pseudolocalize);
@@ -263,7 +263,7 @@
                 {
                     SourcePos(String8(fileName), inXml->getLineNumber()).error(
                             "Found unsupported XLIFF tag <%s>\n",
-                            element8.string());
+                            element8.c_str());
                     return UNKNOWN_ERROR;
                 }
 moveon:
@@ -272,14 +272,14 @@
 
             if (outSpans == NULL) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error(
-                        "Found style tag <%s> where styles are not allowed\n", element8.string());
+                        "Found style tag <%s> where styles are not allowed\n", element8.c_str());
                 return UNKNOWN_ERROR;
             }
 
-            if (!ResTable::collectString(outString, curString.string(),
+            if (!ResTable::collectString(outString, curString.c_str(),
                                          curString.size(), false, &errorMsg, true)) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
-                        errorMsg, String8(curString).string());
+                        errorMsg, String8(curString).c_str());
                 return UNKNOWN_ERROR;
             }
             rawString.append(curString);
@@ -295,7 +295,7 @@
                 str = inXml->getAttributeStringValue(ai, &len);
                 span.name.append(str, len);
             }
-            //printf("Span: %s\n", String8(span.name).string());
+            //printf("Span: %s\n", String8(span.name).c_str());
             span.span.firstChar = span.span.lastChar = outString->size();
             spanStack.push(span);
 
@@ -311,21 +311,21 @@
                 xliffDepth--;
                 continue;
             }
-            if (!ResTable::collectString(outString, curString.string(),
+            if (!ResTable::collectString(outString, curString.c_str(),
                                          curString.size(), false, &errorMsg, true)) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error("%s (in %s)\n",
-                        errorMsg, String8(curString).string());
+                        errorMsg, String8(curString).c_str());
                 return UNKNOWN_ERROR;
             }
             rawString.append(curString);
             curString = String16();
 
             if (spanStack.size() == 0) {
-                if (strcmp16(inXml->getElementName(&len), endTag.string()) != 0) {
+                if (strcmp16(inXml->getElementName(&len), endTag.c_str()) != 0) {
                     SourcePos(String8(fileName), inXml->getLineNumber()).error(
                             "Found tag %s where <%s> close is expected\n",
-                            String8(inXml->getElementName(&len)).string(),
-                            String8(endTag).string());
+                            String8(inXml->getElementName(&len)).c_str(),
+                            String8(endTag).c_str());
                     return UNKNOWN_ERROR;
                 }
                 break;
@@ -334,15 +334,15 @@
             String16 spanTag;
             ssize_t semi = span.name.findFirst(';');
             if (semi >= 0) {
-                spanTag.setTo(span.name.string(), semi);
+                spanTag = String16(span.name.c_str(), semi);
             } else {
-                spanTag.setTo(span.name);
+                spanTag = span.name;
             }
-            if (strcmp16(inXml->getElementName(&len), spanTag.string()) != 0) {
+            if (strcmp16(inXml->getElementName(&len), spanTag.c_str()) != 0) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error(
                         "Found close tag %s where close tag %s is expected\n",
-                        String8(inXml->getElementName(&len)).string(),
-                        String8(spanTag).string());
+                        String8(inXml->getElementName(&len)).c_str(),
+                        String8(spanTag).c_str());
                 return UNKNOWN_ERROR;
             }
             bool empty = true;
@@ -363,7 +363,7 @@
             if (0 && empty) {
                 fprintf(stderr, "%s:%d: warning: empty '%s' span found in text '%s'\n",
                         fileName, inXml->getLineNumber(),
-                        String8(spanTag).string(), String8(*outString).string());
+                        String8(spanTag).c_str(), String8(*outString).c_str());
 
             }
         } else if (code == ResXMLTree::START_NAMESPACE) {
@@ -380,11 +380,11 @@
 
     if (outSpans != NULL && outSpans->size() > 0) {
         if (curString.size() > 0) {
-            if (!ResTable::collectString(outString, curString.string(),
+            if (!ResTable::collectString(outString, curString.c_str(),
                                          curString.size(), false, &errorMsg, true)) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).error(
                         "%s (in %s)\n",
-                        errorMsg, String8(curString).string());
+                        errorMsg, String8(curString).c_str());
                 return UNKNOWN_ERROR;
             }
         }
@@ -393,7 +393,7 @@
         // later as part of the overall type conversion.  Return to the
         // client the raw unprocessed text.
         rawString.append(curString);
-        outString->setTo(rawString);
+        *outString = rawString;
     }
 
     return NO_ERROR;
@@ -450,10 +450,10 @@
             String8 elemNs = build_namespace(namespaces, ns16);
             const char16_t* com16 = block->getComment(&len);
             if (com16) {
-                printf("%s <!-- %s -->\n", prefix.string(), String8(com16).string());
+                printf("%s <!-- %s -->\n", prefix.c_str(), String8(com16).c_str());
             }
-            printf("%sE: %s%s (line=%d)\n", prefix.string(), elemNs.string(),
-                   String8(block->getElementName(&len)).string(),
+            printf("%sE: %s%s (line=%d)\n", prefix.c_str(), elemNs.c_str(),
+                   String8(block->getElementName(&len)).c_str(),
                    block->getLineNumber());
             int N = block->getAttributeCount();
             depth++;
@@ -463,11 +463,11 @@
                 ns16 = block->getAttributeNamespace(i, &len);
                 String8 ns = build_namespace(namespaces, ns16);
                 String8 name(block->getAttributeName(i, &len));
-                printf("%sA: ", prefix.string());
+                printf("%sA: ", prefix.c_str());
                 if (res) {
-                    printf("%s%s(0x%08x)", ns.string(), name.string(), res);
+                    printf("%s%s(0x%08x)", ns.c_str(), name.c_str(), res);
                 } else {
-                    printf("%s%s", ns.string(), name.string());
+                    printf("%s%s", ns.c_str(), name.c_str());
                 }
                 Res_value value;
                 block->getAttributeValue(i, &value);
@@ -480,14 +480,14 @@
                 } else if (value.dataType == Res_value::TYPE_STRING) {
                     printf("=\"%s\"",
                             ResTable::normalizeForOutput(String8(block->getAttributeStringValue(i,
-                                        &len)).string()).string());
+                                        &len)).c_str()).c_str());
                 } else {
                     printf("=(type 0x%x)0x%x", (int)value.dataType, (int)value.data);
                 }
                 const char16_t* val = block->getAttributeStringValue(i, &len);
                 if (val != NULL) {
-                    printf(" (Raw: \"%s\")", ResTable::normalizeForOutput(String8(val).string()).
-                            string());
+                    printf(" (Raw: \"%s\")", ResTable::normalizeForOutput(String8(val).c_str()).
+                            c_str());
                 }
                 printf("\n");
             }
@@ -509,8 +509,8 @@
             }
             ns.uri = String8(block->getNamespaceUri(&len));
             namespaces.push(ns);
-            printf("%sN: %s=%s\n", prefix.string(), ns.prefix.string(),
-                    ns.uri.string());
+            printf("%sN: %s=%s\n", prefix.c_str(), ns.prefix.c_str(),
+                    ns.uri.c_str());
             depth++;
         } else if (code == ResXMLTree::END_NAMESPACE) {
             if (--depth < 0) {
@@ -529,19 +529,19 @@
             if (ns.prefix != pr) {
                 prefix = make_prefix(depth);
                 printf("%s*** BAD END NS PREFIX: found=%s, expected=%s\n",
-                        prefix.string(), pr.string(), ns.prefix.string());
+                        prefix.c_str(), pr.c_str(), ns.prefix.c_str());
             }
             String8 uri = String8(block->getNamespaceUri(&len));
             if (ns.uri != uri) {
                 prefix = make_prefix(depth);
                 printf("%s *** BAD END NS URI: found=%s, expected=%s\n",
-                        prefix.string(), uri.string(), ns.uri.string());
+                        prefix.c_str(), uri.c_str(), ns.uri.c_str());
             }
             namespaces.pop();
         } else if (code == ResXMLTree::TEXT) {
             size_t len;
-            printf("%sC: \"%s\"\n", prefix.string(),
-                    ResTable::normalizeForOutput(String8(block->getText(&len)).string()).string());
+            printf("%sC: \"%s\"\n", prefix.c_str(),
+                    ResTable::normalizeForOutput(String8(block->getText(&len)).c_str()).c_str());
         }
     }
 
@@ -559,7 +559,7 @@
     root->removeWhitespace(stripAll, cDataTags);
 
     if (kIsDebug) {
-        printf("Input XML from %s:\n", (const char*)file->getPrintableSource());
+        printf("Input XML from %s:\n", file->getPrintableSource().c_str());
         root->print();
     }
     sp<AaptFile> rsc = new AaptFile(String8(), AaptGroupEntry(), String8());
@@ -583,7 +583,7 @@
 sp<XMLNode> XMLNode::parse(const sp<AaptFile>& file)
 {
     char buf[16384];
-    int fd = open(file->getSourceFile().string(), O_RDONLY | O_BINARY);
+    int fd = open(file->getSourceFile().c_str(), O_RDONLY | O_BINARY);
     if (fd < 0) {
         SourcePos(file->getSourceFile(), -1).error("Unable to open file for read: %s",
                 strerror(errno));
@@ -875,9 +875,9 @@
     }
     if (kIsDebug) {
         printf("Elem %s %s=\"%s\": set res id = 0x%08x\n",
-                String8(getElementName()).string(),
-                String8(mAttributes.itemAt(attrIdx).name).string(),
-                String8(mAttributes.itemAt(attrIdx).string).string(),
+                String8(getElementName()).c_str(),
+                String8(mAttributes.itemAt(attrIdx).name).c_str(),
+                String8(mAttributes.itemAt(attrIdx).string).c_str(),
                 resId);
     }
     mAttributes.editItemAt(attrIdx).nameResId = resId;
@@ -915,7 +915,7 @@
 
 void XMLNode::removeWhitespace(bool stripAll, const char** cDataTags)
 {
-    //printf("Removing whitespace in %s\n", String8(mElementName).string());
+    //printf("Removing whitespace in %s\n", String8(mElementName).c_str());
     size_t N = mChildren.size();
     if (cDataTags) {
         String8 tag(mElementName);
@@ -931,13 +931,13 @@
         sp<XMLNode> node = mChildren.itemAt(i);
         if (node->getType() == TYPE_CDATA) {
             // This is a CDATA node...
-            const char16_t* p = node->mChars.string();
+            const char16_t* p = node->mChars.c_str();
             while (*p != 0 && *p < 128 && isspace(*p)) {
                 p++;
             }
             //printf("Space ends at %d in \"%s\"\n",
-            //       (int)(p-node->mChars.string()),
-            //       String8(node->mChars).string());
+            //       (int)(p-node->mChars.c_str()),
+            //       String8(node->mChars).c_str());
             if (*p == 0) {
                 if (stripAll) {
                     // Remove this node!
@@ -949,18 +949,18 @@
                 }
             } else {
                 // Compact leading/trailing whitespace.
-                const char16_t* e = node->mChars.string()+node->mChars.size()-1;
+                const char16_t* e = node->mChars.c_str()+node->mChars.size()-1;
                 while (e > p && *e < 128 && isspace(*e)) {
                     e--;
                 }
-                if (p > node->mChars.string()) {
+                if (p > node->mChars.c_str()) {
                     p--;
                 }
-                if (e < (node->mChars.string()+node->mChars.size()-1)) {
+                if (e < (node->mChars.c_str()+node->mChars.size()-1)) {
                     e++;
                 }
-                if (p > node->mChars.string() ||
-                    e < (node->mChars.string()+node->mChars.size()-1)) {
+                if (p > node->mChars.c_str() ||
+                    e < (node->mChars.c_str()+node->mChars.size()-1)) {
                     String16 tmp(p, e-p+1);
                     node->mChars = tmp;
                 }
@@ -986,14 +986,14 @@
             table->setCurrentXmlPos(SourcePos(mFilename, getStartLineNumber()));
             if (!assets->getIncludedResources()
                     .stringToValue(&e.value, &e.string,
-                                  e.string.string(), e.string.size(), true, true,
+                                  e.string.c_str(), e.string.size(), true, true,
                                   e.nameResId, NULL, &defPackage, table, &ac)) {
                 hasErrors = true;
             }
             if (kIsDebug) {
                 printf("Attr %s: type=0x%x, str=%s\n",
-                        String8(e.name).string(), e.value.dataType,
-                        String8(e.string).string());
+                        String8(e.name).c_str(), e.value.dataType,
+                        String8(e.string).c_str());
             }
         }
     }
@@ -1023,30 +1023,30 @@
             String16 pkg(getNamespaceResourcePackage(String16(assets->getPackage()), e.ns, &nsIsPublic));
             if (kIsDebug) {
                 printf("Elem %s %s=\"%s\": namespace(%s) %s ===> %s\n",
-                        String8(getElementName()).string(),
-                        String8(e.name).string(),
-                        String8(e.string).string(),
-                        String8(e.ns).string(),
+                        String8(getElementName()).c_str(),
+                        String8(e.name).c_str(),
+                        String8(e.string).c_str(),
+                        String8(e.ns).c_str(),
                         (nsIsPublic) ? "public" : "private",
-                        String8(pkg).string());
+                        String8(pkg).c_str());
             }
             if (pkg.size() <= 0) continue;
             uint32_t res = table != NULL
                 ? table->getResId(e.name, &attr, &pkg, &errorMsg, nsIsPublic)
                 : assets->getIncludedResources().
-                    identifierForName(e.name.string(), e.name.size(),
-                                      attr.string(), attr.size(),
-                                      pkg.string(), pkg.size());
+                    identifierForName(e.name.c_str(), e.name.size(),
+                                      attr.c_str(), attr.size(),
+                                      pkg.c_str(), pkg.size());
             if (res != 0) {
                 if (kIsDebug) {
                     printf("XML attribute name %s: resid=0x%08x\n",
-                            String8(e.name).string(), res);
+                            String8(e.name).c_str(), res);
                 }
                 setAttributeResID(i, res);
             } else {
                 SourcePos(mFilename, getStartLineNumber()).error(
                         "No resource identifier found for attribute '%s' in package '%s'\n",
-                        String8(e.name).string(), String8(pkg).string());
+                        String8(e.name).c_str(), String8(pkg).c_str());
                 hasErrors = true;
             }
         }
@@ -1137,7 +1137,7 @@
     if (kPrintStringMetrics) {
         fprintf(stderr, "**** total xml size: %zu / %zu%% strings (in %s)\n",
                 dest->getSize(), (stringPool->getSize()*100)/dest->getSize(),
-                dest->getPath().string());
+                dest->getPath().c_str());
     }
 
     return NO_ERROR;
@@ -1155,8 +1155,8 @@
         if (elemNs.size() > 0) {
             elemNs.append(":");
         }
-        printf("%s E: %s%s", prefix.string(),
-               elemNs.string(), String8(getElementName()).string());
+        printf("%s E: %s%s", prefix.c_str(),
+               elemNs.c_str(), String8(getElementName()).c_str());
         int N = mAttributes.size();
         for (i=0; i<N; i++) {
             ssize_t idx = mAttributeOrder.valueAt(i);
@@ -1171,21 +1171,21 @@
                 attrNs.append(":");
             }
             if (attr.nameResId) {
-                printf("%s%s(0x%08x)", attrNs.string(),
-                       String8(attr.name).string(), attr.nameResId);
+                printf("%s%s(0x%08x)", attrNs.c_str(),
+                       String8(attr.name).c_str(), attr.nameResId);
             } else {
-                printf("%s%s", attrNs.string(), String8(attr.name).string());
+                printf("%s%s", attrNs.c_str(), String8(attr.name).c_str());
             }
-            printf("=%s", String8(attr.string).string());
+            printf("=%s", String8(attr.string).c_str());
         }
         printf("\n");
     } else if (getType() == TYPE_NAMESPACE) {
-        printf("%s N: %s=%s\n", prefix.string(),
+        printf("%s N: %s=%s\n", prefix.c_str(),
                getNamespacePrefix().size() > 0
-                    ? String8(getNamespacePrefix()).string() : "<DEF>",
-               String8(getNamespaceUri()).string());
+                    ? String8(getNamespacePrefix()).c_str() : "<DEF>",
+               String8(getNamespaceUri()).c_str());
     } else {
-        printf("%s C: \"%s\"\n", prefix.string(), String8(getCData()).string());
+        printf("%s C: \"%s\"\n", prefix.c_str(), String8(getCData()).c_str());
     }
     int N = mChildren.size();
     for (i=0; i<N; i++) {
@@ -1258,7 +1258,7 @@
 XMLNode::characterData(void *userData, const XML_Char *s, int len)
 {
     if (kIsDebugParse) {
-        printf("CDATA: \"%s\"\n", String8(s, len).string());
+        printf("CDATA: \"%s\"\n", String8(s, len).c_str());
     }
     ParseState* st = (ParseState*)userData;
     sp<XMLNode> node = NULL;
@@ -1423,7 +1423,7 @@
                 idx = outPool->add(attr.name);
                 if (kIsDebug) {
                     printf("Adding attr %s (resid 0x%08x) to pool: idx=%zd\n",
-                            String8(attr.name).string(), id, idx);
+                            String8(attr.name).c_str(), id, idx);
                 }
                 if (id != 0) {
                     while ((ssize_t)outResIds->size() <= idx) {
@@ -1434,7 +1434,7 @@
             }
             attr.namePoolIdx = idx;
             if (kIsDebug) {
-                printf("String %s offset=0x%08zd\n", String8(attr.name).string(), idx);
+                printf("String %s offset=0x%08zd\n", String8(attr.name).c_str(), idx);
             }
         }
     }
@@ -1488,7 +1488,7 @@
         node.comment.index = htodl(
             mComment.size() > 0 ? strings.offsetForString(mComment) : -1);
         //if (mComment.size() > 0) {
-        //  printf("Flattening comment: %s\n", String8(mComment).string());
+        //  printf("Flattening comment: %s\n", String8(mComment).c_str());
         //}
     } else {
         node.comment.index = htodl((uint32_t)-1);
diff --git a/tools/aapt/ZipEntry.cpp b/tools/aapt/ZipEntry.cpp
index 5339285..6886993 100644
--- a/tools/aapt/ZipEntry.cpp
+++ b/tools/aapt/ZipEntry.cpp
@@ -18,6 +18,8 @@
 // Access to entries in a Zip archive.
 //
 
+#define _POSIX_THREAD_SAFE_FUNCTIONS // For mingw localtime_r().
+
 #define LOG_TAG "zip"
 
 #include "ZipEntry.h"
@@ -337,39 +339,26 @@
 /*
  * Set the CDE/LFH timestamp from UNIX time.
  */
-void ZipEntry::setModWhen(time_t when)
-{
-#if !defined(_WIN32)
-    struct tm tmResult;
-#endif
-    time_t even;
-    unsigned short zdate, ztime;
-
-    struct tm* ptm;
-
+void ZipEntry::setModWhen(time_t when) {
     /* round up to an even number of seconds */
-    even = (time_t)(((unsigned long)(when) + 1) & (~1));
+    time_t even = (time_t)(((unsigned long)(when) + 1) & (~1));
 
     /* expand */
-#if !defined(_WIN32)
-    ptm = localtime_r(&even, &tmResult);
-#else
-    ptm = localtime(&even);
-#endif
+    struct tm tmResult;
+    struct tm* ptm = localtime_r(&even, &tmResult);
 
     int year;
     year = ptm->tm_year;
     if (year < 80)
         year = 80;
 
-    zdate = (year - 80) << 9 | (ptm->tm_mon+1) << 5 | ptm->tm_mday;
-    ztime = ptm->tm_hour << 11 | ptm->tm_min << 5 | ptm->tm_sec >> 1;
+    unsigned short zdate = (year - 80) << 9 | (ptm->tm_mon + 1) << 5 | ptm->tm_mday;
+    unsigned short ztime = ptm->tm_hour << 11 | ptm->tm_min << 5 | ptm->tm_sec >> 1;
 
     mCDE.mLastModFileTime = mLFH.mLastModFileTime = ztime;
     mCDE.mLastModFileDate = mLFH.mLastModFileDate = zdate;
 }
 
-
 /*
  * ===========================================================================
  *      ZipEntry::LocalFileHeader
diff --git a/tools/aapt/pseudolocalize.cpp b/tools/aapt/pseudolocalize.cpp
index 4e8dcb1..fc2ed98 100644
--- a/tools/aapt/pseudolocalize.cpp
+++ b/tools/aapt/pseudolocalize.cpp
@@ -42,7 +42,7 @@
   size_t depth = mLastDepth;
   size_t lastpos, pos;
   const size_t length= text.size();
-  const char16_t* str = text.string();
+  const char16_t* str = text.c_str();
   bool escaped = false;
   for (lastpos = pos = 0; pos < length; pos++) {
     char16_t c = str[pos];
@@ -181,7 +181,7 @@
 
 static String16 pseudo_generate_expansion(const unsigned int length) {
     String16 result = k_expansion_string;
-    const char16_t* s = result.string();
+    const char16_t* s = result.c_str();
     if (result.size() < length) {
         result += String16(" ");
         result += pseudo_generate_expansion(length - result.size());
@@ -237,7 +237,7 @@
  */
 String16 PseudoMethodAccent::text(const String16& source)
 {
-    const char16_t* s = source.string();
+    const char16_t* s = source.c_str();
     String16 result;
     const size_t I = source.size();
     bool lastspace = true;
@@ -357,7 +357,7 @@
 
 String16 PseudoMethodBidi::text(const String16& source)
 {
-    const char16_t* s = source.string();
+    const char16_t* s = source.c_str();
     String16 result;
     bool lastspace = true;
     bool space = true;
diff --git a/tools/aapt/tests/AaptGroupEntry_test.cpp b/tools/aapt/tests/AaptGroupEntry_test.cpp
index bf5ca59..8621e9b 100644
--- a/tools/aapt/tests/AaptGroupEntry_test.cpp
+++ b/tools/aapt/tests/AaptGroupEntry_test.cpp
@@ -24,7 +24,7 @@
 
 static ::testing::AssertionResult TestParse(AaptGroupEntry& entry, const String8& dirName,
         String8* outType) {
-    if (entry.initFromDirName(dirName, outType)) {
+    if (entry.initFromDirName(dirName.c_str(), outType)) {
         return ::testing::AssertionSuccess() << dirName << " was successfully parsed";
     }
     return ::testing::AssertionFailure() << dirName << " could not be parsed";
diff --git a/tools/aapt2/Debug.cpp b/tools/aapt2/Debug.cpp
index f47d66e..3fa3900 100644
--- a/tools/aapt2/Debug.cpp
+++ b/tools/aapt2/Debug.cpp
@@ -445,7 +445,7 @@
   const size_t NS = pool->size();
   for (size_t s=0; s<NS; s++) {
     auto str = pool->string8ObjectAt(s);
-    printer->Print(StringPrintf("String #%zd : %s\n", s, str.has_value() ? str->string() : ""));
+    printer->Print(StringPrintf("String #%zd : %s\n", s, str.has_value() ? str->c_str() : ""));
   }
 }
 
diff --git a/tools/aapt2/DominatorTree_test.cpp b/tools/aapt2/DominatorTree_test.cpp
index 52949da..087f456 100644
--- a/tools/aapt2/DominatorTree_test.cpp
+++ b/tools/aapt2/DominatorTree_test.cpp
@@ -51,8 +51,7 @@
   void VisitConfig(const DominatorTree::Node* node, const int indent) {
     auto config_string = node->value()->config.toString();
     buffer_ << std::string(indent, ' ')
-            << (config_string.isEmpty() ? "<default>" : config_string)
-            << std::endl;
+            << (config_string.empty() ? "<default>" : config_string.c_str()) << std::endl;
   }
 
   void VisitNode(const DominatorTree::Node* node, const int indent) {
diff --git a/tools/aapt2/OWNERS b/tools/aapt2/OWNERS
index 4f655e5..55bab7d 100644
--- a/tools/aapt2/OWNERS
+++ b/tools/aapt2/OWNERS
@@ -1,4 +1,4 @@
 set noparent
-toddke@google.com
 zyy@google.com
-patb@google.com
\ No newline at end of file
+patb@google.com
+markpun@google.com
diff --git a/tools/aapt2/cmd/Util.cpp b/tools/aapt2/cmd/Util.cpp
index 3244fb8..73a8d68 100644
--- a/tools/aapt2/cmd/Util.cpp
+++ b/tools/aapt2/cmd/Util.cpp
@@ -213,7 +213,7 @@
   }
   std::vector<std::string> sanitized_config_names;
   for (const auto &config : constraints.configs) {
-    sanitized_config_names.push_back(MakePackageSafeName(config.toString().string()));
+    sanitized_config_names.push_back(MakePackageSafeName(config.toString().c_str()));
   }
   split_name << "config." << util::Joiner(sanitized_config_names, "_");
 
diff --git a/tools/aapt2/compile/InlineXmlFormatParser.h b/tools/aapt2/compile/InlineXmlFormatParser.h
index 4300023..3a5161b 100644
--- a/tools/aapt2/compile/InlineXmlFormatParser.h
+++ b/tools/aapt2/compile/InlineXmlFormatParser.h
@@ -21,8 +21,8 @@
 #include <vector>
 
 #include "android-base/macros.h"
-
 #include "process/IResourceTableConsumer.h"
+#include "xml/XmlDom.h"
 
 namespace aapt {
 
diff --git a/tools/aapt2/dump/DumpManifest.cpp b/tools/aapt2/dump/DumpManifest.cpp
index 9828b97..f93949b 100644
--- a/tools/aapt2/dump/DumpManifest.cpp
+++ b/tools/aapt2/dump/DumpManifest.cpp
@@ -116,9 +116,7 @@
 
 class ManifestExtractor {
  public:
-
-  explicit ManifestExtractor(LoadedApk* apk, DumpManifestOptions& options)
-      : apk_(apk), options_(options) { }
+  explicit ManifestExtractor(LoadedApk* apk, DumpManifestOptions& options);
 
   class Element {
    public:
@@ -387,7 +385,7 @@
   DumpManifestOptions& options_;
 
  private:
-  std::unique_ptr<CommonFeatureGroup> commonFeatureGroup_ = util::make_unique<CommonFeatureGroup>();
+  std::unique_ptr<CommonFeatureGroup> commonFeatureGroup_;
   std::map<std::string, ConfigDescription> locales_;
   std::map<uint16_t, ConfigDescription> densities_;
   std::vector<Element*> parent_stack_;
@@ -1970,6 +1968,12 @@
   }
 }
 
+// Define this constructor after the CommonFeatureGroup class definition to avoid errors with using
+// std::unique_ptr on an incomplete type.
+ManifestExtractor::ManifestExtractor(LoadedApk* apk, DumpManifestOptions& options)
+    : apk_(apk), options_(options), commonFeatureGroup_(util::make_unique<CommonFeatureGroup>()) {
+}
+
 bool ManifestExtractor::Dump(text::Printer* printer, IDiagnostics* diag) {
   // Load the manifest
   std::unique_ptr<xml::XmlResource> doc = apk_->LoadXml("AndroidManifest.xml", diag);
diff --git a/tools/aapt2/format/binary/BinaryResourceParser.cpp b/tools/aapt2/format/binary/BinaryResourceParser.cpp
index c65c550..5ed8487 100644
--- a/tools/aapt2/format/binary/BinaryResourceParser.cpp
+++ b/tools/aapt2/format/binary/BinaryResourceParser.cpp
@@ -450,7 +450,7 @@
   const size_t count = entries.size();
   for (size_t i = 0; i < count; i++) {
     table_->included_packages_[entries.valueAt(i)] =
-        util::Utf16ToUtf8(StringPiece16(entries.keyAt(i).string()));
+        util::Utf16ToUtf8(StringPiece16(entries.keyAt(i).c_str()));
   }
   return true;
 }
diff --git a/tools/hiddenapi/OWNERS b/tools/hiddenapi/OWNERS
index afbeef5..dc82aac 100644
--- a/tools/hiddenapi/OWNERS
+++ b/tools/hiddenapi/OWNERS
@@ -1,5 +1,4 @@
 # compat-team@ for changes to hiddenapi files
-andreionea@google.com
 mathewi@google.com
 satayev@google.com
 
diff --git a/tools/lint/common/Android.bp b/tools/lint/common/Android.bp
index 898f88b..8bfbfe5 100644
--- a/tools/lint/common/Android.bp
+++ b/tools/lint/common/Android.bp
@@ -27,3 +27,30 @@
     libs: ["lint_api"],
     kotlincflags: ["-Xjvm-default=all"],
 }
+
+java_defaults {
+    name: "AndroidLintCheckerTestDefaults",
+    srcs: ["checks/src/test/java/**/*.kt"],
+    static_libs: [
+        "junit",
+        "lint",
+        "lint_tests",
+    ],
+    test_options: {
+        unit_test: true,
+        tradefed_options: [
+            {
+                // lint bundles in some classes that were built with older versions
+                // of libraries, and no longer load. Since tradefed tries to load
+                // all classes in the jar to look for tests, it crashes loading them.
+                // Exclude these classes from tradefed's search.
+                name: "exclude-paths",
+                value: "org/apache",
+            },
+            {
+                name: "exclude-paths",
+                value: "META-INF",
+            },
+        ],
+    },
+}
diff --git a/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/AidlImplementationDetector.kt b/tools/lint/common/src/main/java/com/google/android/lint/aidl/AidlImplementationDetector.kt
similarity index 100%
rename from tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/AidlImplementationDetector.kt
rename to tools/lint/common/src/main/java/com/google/android/lint/aidl/AidlImplementationDetector.kt
diff --git a/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/Constants.kt b/tools/lint/common/src/main/java/com/google/android/lint/aidl/Constants.kt
similarity index 100%
rename from tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/Constants.kt
rename to tools/lint/common/src/main/java/com/google/android/lint/aidl/Constants.kt
diff --git a/tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionUtils.kt b/tools/lint/common/src/main/java/com/google/android/lint/aidl/EnforcePermissionUtils.kt
similarity index 100%
rename from tools/lint/global/checks/src/main/java/com/google/android/lint/aidl/EnforcePermissionUtils.kt
rename to tools/lint/common/src/main/java/com/google/android/lint/aidl/EnforcePermissionUtils.kt
diff --git a/tools/lint/fix/Android.bp b/tools/lint/fix/Android.bp
index 43f2122..ddacf57 100644
--- a/tools/lint/fix/Android.bp
+++ b/tools/lint/fix/Android.bp
@@ -25,6 +25,11 @@
     name: "lint_fix",
     main: "soong_lint_fix.py",
     srcs: ["soong_lint_fix.py"],
+    version: {
+        py3: {
+            embedded_launcher: true,
+        },
+    },
 }
 
 python_library_host {
diff --git a/tools/lint/fix/soong_lint_fix.py b/tools/lint/fix/soong_lint_fix.py
index cd4d778d..2e82beb 100644
--- a/tools/lint/fix/soong_lint_fix.py
+++ b/tools/lint/fix/soong_lint_fix.py
@@ -14,6 +14,7 @@
 
 import argparse
 import json
+import functools
 import os
 import shutil
 import subprocess
@@ -28,56 +29,75 @@
 PATH_PREFIX = "out/soong/.intermediates"
 PATH_SUFFIX = "android_common/lint"
 FIX_ZIP = "suggested-fixes.zip"
+MODULE_JAVA_DEPS = "out/soong/module_bp_java_deps.json"
 
-class SoongLintFix:
+
+class SoongModule:
+    """A Soong module to lint.
+
+    The constructor takes the name of the module (for example,
+    "framework-minus-apex"). find() must be called to extract the intermediate
+    module path from Soong's module-info.json
     """
-    This class creates a command line tool that will
-    apply lint fixes to the platform via the necessary
-    combination of soong and shell commands.
+    def __init__(self, name):
+        self._name = name
 
-    It breaks up these operations into a few "private" methods
-    that are intentionally exposed so experimental code can tweak behavior.
+    def find(self, module_info):
+        """Finds the module in the loaded module_info.json."""
+        if self._name not in module_info:
+            raise Exception(f"Module {self._name} not found!")
 
-    The entry point, `run`, will apply lint fixes using the
-    intermediate `suggested-fixes` directory that soong creates during its
-    invocation of lint.
+        partial_path = module_info[self._name]["path"][0]
+        print(f"Found module {partial_path}/{self._name}.")
+        self._path = f"{PATH_PREFIX}/{partial_path}/{self._name}/{PATH_SUFFIX}"
 
-    Basic usage:
-    ```
-    from soong_lint_fix import SoongLintFix
+    def find_java_deps(self, module_java_deps):
+        """Finds the dependencies of a Java module in the loaded module_bp_java_deps.json.
 
-    SoongLintFix().run()
-    ```
+        Returns:
+            A list of module names.
+        """
+        if self._name not in module_java_deps:
+            raise Exception(f"Module {self._name} not found!")
+
+        return module_java_deps[self._name]["dependencies"]
+
+    @property
+    def name(self):
+        return self._name
+
+    @property
+    def path(self):
+        return self._path
+
+    @property
+    def lint_report(self):
+        return f"{self._path}/lint-report.txt"
+
+    @property
+    def suggested_fixes(self):
+        return f"{self._path}/{FIX_ZIP}"
+
+
+class SoongLintWrapper:
     """
-    def __init__(self):
-        self._parser = _setup_parser()
-        self._args = None
+    This class wraps the necessary calls to Soong and/or shell commands to lint
+    platform modules and apply suggested fixes if desired.
+
+    It breaks up these operations into a few methods that are available to
+    sub-classes (see SoongLintFix for an example).
+    """
+    def __init__(self, check=None, lint_module=None):
+        self._check = check
+        self._lint_module = lint_module
         self._kwargs = None
-        self._path = None
-        self._target = None
-
-
-    def run(self, additional_setup=None, custom_fix=None):
-        """
-        Run the script
-        """
-        self._setup()
-        self._find_module()
-        self._lint()
-
-        if not self._args.no_fix:
-            self._fix()
-
-        if self._args.print:
-            self._print()
 
     def _setup(self):
-        self._args = self._parser.parse_args()
         env = os.environ.copy()
-        if self._args.check:
-            env["ANDROID_LINT_CHECK"] = self._args.check
-        if self._args.lint_module:
-            env["ANDROID_LINT_CHECK_EXTRA_MODULES"] = self._args.lint_module
+        if self._check:
+            env["ANDROID_LINT_CHECK"] = self._check
+        if self._lint_module:
+            env["ANDROID_LINT_CHECK_EXTRA_MODULES"] = self._lint_module
 
         self._kwargs = {
             "env": env,
@@ -87,9 +107,10 @@
 
         os.chdir(ANDROID_BUILD_TOP)
 
-
-    def _find_module(self):
-        print("Refreshing soong modules...")
+    @functools.cached_property
+    def _module_info(self):
+        """Returns the JSON content of module-info.json."""
+        print("Refreshing Soong modules...")
         try:
             os.mkdir(ANDROID_PRODUCT_OUT)
         except OSError:
@@ -98,47 +119,122 @@
         print("done.")
 
         with open(f"{ANDROID_PRODUCT_OUT}/module-info.json") as f:
-            module_info = json.load(f)
+            return json.load(f)
 
-        if self._args.module not in module_info:
-            sys.exit(f"Module {self._args.module} not found!")
+    def _find_module(self, module_name):
+        """Returns a SoongModule from a module name.
 
-        module_path = module_info[self._args.module]["path"][0]
-        print(f"Found module {module_path}/{self._args.module}.")
+        Ensures that the module is known to Soong.
+        """
+        module = SoongModule(module_name)
+        module.find(self._module_info)
+        return module
 
-        self._path = f"{PATH_PREFIX}/{module_path}/{self._args.module}/{PATH_SUFFIX}"
-        self._target = f"{self._path}/lint-report.txt"
+    def _find_modules(self, module_names):
+        modules = []
+        for module_name in module_names:
+            modules.append(self._find_module(module_name))
+        return modules
 
+    @functools.cached_property
+    def _module_java_deps(self):
+        """Returns the JSON content of module_bp_java_deps.json."""
+        print("Refreshing Soong Java deps...")
+        subprocess.call(f"{SOONG_UI} --make-mode {MODULE_JAVA_DEPS}", **self._kwargs)
+        print("done.")
 
-    def _lint(self):
+        with open(f"{MODULE_JAVA_DEPS}") as f:
+            return json.load(f)
+
+    def _find_module_java_deps(self, module):
+        """Returns a list a dependencies for a module.
+
+        Args:
+            module: A SoongModule.
+
+        Returns:
+            A list of SoongModule.
+        """
+        deps = []
+        dep_names = module.find_java_deps(self._module_java_deps)
+        for dep_name in dep_names:
+            dep = SoongModule(dep_name)
+            dep.find(self._module_info)
+            deps.append(dep)
+        return deps
+
+    def _lint(self, modules):
         print("Cleaning up any old lint results...")
-        try:
-            os.remove(f"{self._target}")
-            os.remove(f"{self._path}/{FIX_ZIP}")
-        except FileNotFoundError:
-            pass
+        for module in modules:
+            try:
+                os.remove(f"{module.lint_report}")
+                os.remove(f"{module.suggested_fixes}")
+            except FileNotFoundError:
+                pass
         print("done.")
 
-        print(f"Generating {self._target}")
-        subprocess.call(f"{SOONG_UI} --make-mode {self._target}", **self._kwargs)
+        target = " ".join([ module.lint_report for module in modules ])
+        print(f"Generating {target}")
+        subprocess.call(f"{SOONG_UI} --make-mode {target}", **self._kwargs)
         print("done.")
 
-
-    def _fix(self):
-        print("Copying suggested fixes to the tree...")
-        with zipfile.ZipFile(f"{self._path}/{FIX_ZIP}") as zip:
-            for name in zip.namelist():
-                if name.startswith("out") or not name.endswith(".java"):
-                    continue
-                with zip.open(name) as src, open(f"{ANDROID_BUILD_TOP}/{name}", "wb") as dst:
-                    shutil.copyfileobj(src, dst)
+    def _fix(self, modules):
+        for module in modules:
+            print(f"Copying suggested fixes for {module.name} to the tree...")
+            with zipfile.ZipFile(f"{module.suggested_fixes}") as zip:
+                for name in zip.namelist():
+                    if name.startswith("out") or not name.endswith(".java"):
+                        continue
+                    with zip.open(name) as src, open(f"{ANDROID_BUILD_TOP}/{name}", "wb") as dst:
+                        shutil.copyfileobj(src, dst)
             print("done.")
 
+    def _print(self, modules):
+        for module in modules:
+            print(f"### lint-report.txt {module.name} ###", end="\n\n")
+            with open(module.lint_report, "r") as f:
+                print(f.read())
 
-    def _print(self):
-        print("### lint-report.txt ###", end="\n\n")
-        with open(self._target, "r") as f:
-            print(f.read())
+
+class SoongLintFix(SoongLintWrapper):
+    """
+    Basic usage:
+    ```
+    from soong_lint_fix import SoongLintFix
+
+    opts = SoongLintFixOptions()
+    opts.parse_args()
+    SoongLintFix(opts).run()
+    ```
+    """
+    def __init__(self, opts):
+        super().__init__(check=opts.check, lint_module=opts.lint_module)
+        self._opts = opts
+
+    def run(self):
+        self._setup()
+        modules = self._find_modules(self._opts.modules)
+        self._lint(modules)
+
+        if not self._opts.no_fix:
+            self._fix(modules)
+
+        if self._opts.print:
+            self._print(modules)
+
+
+class SoongLintFixOptions:
+    """Options for SoongLintFix"""
+
+    def __init__(self):
+        self.modules = []
+        self.check = None
+        self.lint_module = None
+        self.no_fix = False
+        self.print = False
+
+    def parse_args(self, args=None):
+        _setup_parser().parse_args(args, self)
 
 
 def _setup_parser():
@@ -151,7 +247,8 @@
         **Gotcha**: You must have run `source build/envsetup.sh` and `lunch` first.
         """, formatter_class=argparse.RawTextHelpFormatter)
 
-    parser.add_argument('module',
+    parser.add_argument('modules',
+                        nargs='+',
                         help='The soong build module to run '
                              '(e.g. framework-minus-apex or services.core.unboosted)')
 
@@ -170,4 +267,6 @@
     return parser
 
 if __name__ == "__main__":
-    SoongLintFix().run()
\ No newline at end of file
+    opts = SoongLintFixOptions()
+    opts.parse_args()
+    SoongLintFix(opts).run()
diff --git a/tools/lint/framework/Android.bp b/tools/lint/framework/Android.bp
index 30a6daa..5acdf43 100644
--- a/tools/lint/framework/Android.bp
+++ b/tools/lint/framework/Android.bp
@@ -37,28 +37,9 @@
 
 java_test_host {
     name: "AndroidFrameworkLintCheckerTest",
+    defaults: ["AndroidLintCheckerTestDefaults"],
     srcs: ["checks/src/test/java/**/*.kt"],
     static_libs: [
         "AndroidFrameworkLintChecker",
-        "junit",
-        "lint",
-        "lint_tests",
     ],
-    test_options: {
-        unit_test: true,
-        tradefed_options: [
-            {
-                // lint bundles in some classes that were built with older versions
-                // of libraries, and no longer load. Since tradefed tries to load
-                // all classes in the jar to look for tests, it crashes loading them.
-                // Exclude these classes from tradefed's search.
-                name: "exclude-paths",
-                value: "org/apache",
-            },
-            {
-                name: "exclude-paths",
-                value: "META-INF",
-            },
-        ],
-    },
 }
diff --git a/tools/lint/global/Android.bp b/tools/lint/global/Android.bp
index bedb7bd..3e74171 100644
--- a/tools/lint/global/Android.bp
+++ b/tools/lint/global/Android.bp
@@ -38,28 +38,9 @@
 
 java_test_host {
     name: "AndroidGlobalLintCheckerTest",
+    defaults: ["AndroidLintCheckerTestDefaults"],
     srcs: ["checks/src/test/java/**/*.kt"],
     static_libs: [
         "AndroidGlobalLintChecker",
-        "junit",
-        "lint",
-        "lint_tests",
     ],
-    test_options: {
-        unit_test: true,
-        tradefed_options: [
-            {
-                // lint bundles in some classes that were built with older versions
-                // of libraries, and no longer load. Since tradefed tries to load
-                // all classes in the jar to look for tests, it crashes loading them.
-                // Exclude these classes from tradefed's search.
-                name: "exclude-paths",
-                value: "org/apache",
-            },
-            {
-                name: "exclude-paths",
-                value: "META-INF",
-            },
-        ],
-    },
 }
diff --git a/tools/lint/global/integration_tests/Android.bp b/tools/lint/global/integration_tests/Android.bp
new file mode 100644
index 0000000..ca96559
--- /dev/null
+++ b/tools/lint/global/integration_tests/Android.bp
@@ -0,0 +1,40 @@
+// Copyright (C) 2023 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.
+
+java_library {
+    name: "AndroidGlobalLintTestNoAidl",
+    srcs: ["TestNoAidl/**/*.java"],
+    libs: [
+        "framework-annotations-lib",
+    ],
+    lint: {
+        // It is expected that lint returns an error when processing this
+        // library. Silence it here, the lint output is verified in tests.py.
+        suppress_exit_code: true,
+    },
+}
+
+python_test_host {
+    name: "AndroidGlobalLintCheckerIntegrationTest",
+    srcs: ["tests.py"],
+    main: "tests.py",
+    data: [
+        ":AndroidGlobalLintTestNoAidl{.lint}",
+    ],
+    version: {
+        py3: {
+            embedded_launcher: true,
+        },
+    },
+}
diff --git a/tools/lint/global/integration_tests/TestNoAidl/TestNoAidl.java b/tools/lint/global/integration_tests/TestNoAidl/TestNoAidl.java
new file mode 100644
index 0000000..0015f95
--- /dev/null
+++ b/tools/lint/global/integration_tests/TestNoAidl/TestNoAidl.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2023 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.google.android.lint.integration_tests;
+
+import android.annotation.EnforcePermission;
+
+/**
+ * A class that use the annotation but does not rely on AIDL.
+ */
+class TestNoAidl {
+
+    @EnforcePermission("INTERNET")
+    void myMethod() {
+    }
+
+}
diff --git a/tools/lint/global/integration_tests/tests.py b/tools/lint/global/integration_tests/tests.py
new file mode 100644
index 0000000..fc3eeb4
--- /dev/null
+++ b/tools/lint/global/integration_tests/tests.py
@@ -0,0 +1,34 @@
+# Copyright 2023 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.
+
+import pkgutil
+import unittest
+import xml.etree.ElementTree
+
+class TestLinterReports(unittest.TestCase):
+    """Integration tests for the linters used by @EnforcePermission."""
+
+    def test_no_aidl(self):
+        report = pkgutil.get_data("lint", "lint-report.xml").decode()
+        issues = xml.etree.ElementTree.fromstring(report)
+        self.assertEqual(issues.tag, "issues")
+        self.assertEqual(len(issues), 1)
+
+        issue = issues[0]
+        self.assertEqual(issue.attrib["id"], "MisusingEnforcePermissionAnnotation")
+        self.assertEqual(issue.attrib["severity"], "Error")
+
+
+if __name__ == '__main__':
+    unittest.main(verbosity=2)
diff --git a/tools/lint/utils/Android.bp b/tools/lint/utils/Android.bp
new file mode 100644
index 0000000..439c86d
--- /dev/null
+++ b/tools/lint/utils/Android.bp
@@ -0,0 +1,51 @@
+// Copyright (C) 2023 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 {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "frameworks_base_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    default_applicable_licenses: ["frameworks_base_license"],
+}
+
+java_library_host {
+    name: "AndroidUtilsLintChecker",
+    srcs: ["checks/src/main/java/**/*.kt"],
+    plugins: ["auto_service_plugin"],
+    libs: [
+        "auto_service_annotations",
+        "lint_api",
+    ],
+    static_libs: [
+        "AndroidCommonLint",
+    ],
+    kotlincflags: ["-Xjvm-default=all"],
+}
+
+java_test_host {
+    name: "AndroidUtilsLintCheckerTest",
+    defaults: ["AndroidLintCheckerTestDefaults"],
+    srcs: ["checks/src/test/java/**/*.kt"],
+    static_libs: [
+        "AndroidUtilsLintChecker",
+    ],
+}
+
+python_binary_host {
+    name: "enforce_permission_counter",
+    srcs: ["enforce_permission_counter.py"],
+    libs: ["soong_lint_fix"],
+}
diff --git a/tools/lint/utils/checks/src/main/java/com/google/android/lint/AndroidUtilsIssueRegistry.kt b/tools/lint/utils/checks/src/main/java/com/google/android/lint/AndroidUtilsIssueRegistry.kt
new file mode 100644
index 0000000..fa61c42
--- /dev/null
+++ b/tools/lint/utils/checks/src/main/java/com/google/android/lint/AndroidUtilsIssueRegistry.kt
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2023 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.google.android.lint
+
+import com.android.tools.lint.client.api.IssueRegistry
+import com.android.tools.lint.client.api.Vendor
+import com.android.tools.lint.detector.api.CURRENT_API
+import com.google.android.lint.aidl.AnnotatedAidlCounter
+import com.google.auto.service.AutoService
+
+@AutoService(IssueRegistry::class)
+@Suppress("UnstableApiUsage")
+class AndroidUtilsIssueRegistry : IssueRegistry() {
+    override val issues = listOf(
+        AnnotatedAidlCounter.ISSUE_ANNOTATED_AIDL_COUNTER,
+    )
+
+    override val api: Int
+        get() = CURRENT_API
+
+    override val minApi: Int
+        get() = 8
+
+    override val vendor: Vendor = Vendor(
+        vendorName = "Android",
+        feedbackUrl = "http://b/issues/new?component=315013",
+        contact = "tweek@google.com"
+    )
+}
diff --git a/tools/lint/utils/checks/src/main/java/com/google/android/lint/aidl/AnnotatedAidlCounter.kt b/tools/lint/utils/checks/src/main/java/com/google/android/lint/aidl/AnnotatedAidlCounter.kt
new file mode 100644
index 0000000..f0ec3f4
--- /dev/null
+++ b/tools/lint/utils/checks/src/main/java/com/google/android/lint/aidl/AnnotatedAidlCounter.kt
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2023 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.google.android.lint.aidl
+
+import com.android.tools.lint.detector.api.Category
+import com.android.tools.lint.detector.api.Context
+import com.android.tools.lint.detector.api.Implementation
+import com.android.tools.lint.detector.api.Issue
+import com.android.tools.lint.detector.api.JavaContext
+import com.android.tools.lint.detector.api.Location
+import com.android.tools.lint.detector.api.Scope
+import com.android.tools.lint.detector.api.Severity
+import org.jetbrains.uast.UBlockExpression
+import org.jetbrains.uast.UMethod
+
+import java.util.TreeMap
+
+/**
+ *  Count the number of AIDL interfaces. Reports the number of annotated and
+ *  non-annotated methods.
+ */
+@Suppress("UnstableApiUsage")
+class AnnotatedAidlCounter : AidlImplementationDetector() {
+
+    private data class Stat(
+        var unannotated: Int = 0,
+        var enforced: Int = 0,
+        var notRequired: Int = 0,
+    )
+
+    private var packagesStats: TreeMap<String, Stat> = TreeMap<String, Stat>()
+
+    override fun visitAidlMethod(
+            context: JavaContext,
+            node: UMethod,
+            interfaceName: String,
+            body: UBlockExpression
+    ) {
+        val packageName = context.uastFile?.packageName ?: "<unknown>"
+        var packageStat = packagesStats.getOrDefault(packageName, Stat())
+        when {
+            node.hasAnnotation(ANNOTATION_ENFORCE_PERMISSION) -> packageStat.enforced += 1
+            node.hasAnnotation(ANNOTATION_REQUIRES_NO_PERMISSION) -> packageStat.notRequired += 1
+            else -> packageStat.unannotated += 1
+        }
+        packagesStats.put(packageName, packageStat)
+        // context.driver.client.log(null, "%s.%s#%s".format(packageName, interfaceName, node.name))
+    }
+
+    override fun afterCheckRootProject(context: Context) {
+        var total = Stat()
+        for ((packageName, stat) in packagesStats) {
+            context.client.log(null, "package $packageName => $stat")
+            total.unannotated += stat.unannotated
+            total.enforced += stat.enforced
+            total.notRequired += stat.notRequired
+        }
+        val location = Location.create(context.project.dir)
+        context.report(
+            ISSUE_ANNOTATED_AIDL_COUNTER,
+            location,
+            "module ${context.project.name} => $total"
+        )
+    }
+
+    companion object {
+
+        @JvmField
+        val ISSUE_ANNOTATED_AIDL_COUNTER = Issue.create(
+                id = "AnnotatedAidlCounter",
+                briefDescription = "Statistics on the number of annotated AIDL methods.",
+                explanation = "",
+                category = Category.SECURITY,
+                priority = 5,
+                severity = Severity.INFORMATIONAL,
+                implementation = Implementation(
+                        AnnotatedAidlCounter::class.java,
+                        Scope.JAVA_FILE_SCOPE
+                ),
+        )
+    }
+}
diff --git a/tools/lint/utils/checks/src/test/java/com/google/android/lint/aidl/AnnotatedAidlCounterTest.kt b/tools/lint/utils/checks/src/test/java/com/google/android/lint/aidl/AnnotatedAidlCounterTest.kt
new file mode 100644
index 0000000..692b7da
--- /dev/null
+++ b/tools/lint/utils/checks/src/test/java/com/google/android/lint/aidl/AnnotatedAidlCounterTest.kt
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2023 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.google.android.lint.aidl
+
+import com.android.tools.lint.checks.infrastructure.LintDetectorTest
+import com.android.tools.lint.checks.infrastructure.TestFile
+import com.android.tools.lint.checks.infrastructure.TestLintTask
+import com.android.tools.lint.detector.api.Detector
+import com.android.tools.lint.detector.api.Issue
+
+@Suppress("UnstableApiUsage")
+class AnnotatedAidlCounterTest : LintDetectorTest() {
+    override fun getDetector(): Detector = AnnotatedAidlCounter()
+
+    override fun getIssues(): List<Issue> = listOf(
+        AnnotatedAidlCounter.ISSUE_ANNOTATED_AIDL_COUNTER,
+    )
+
+    override fun lint(): TestLintTask = super.lint().allowMissingSdk(true)
+
+    /** No issue scenario */
+
+    fun testDoesNotDetectIssuesCorrectAnnotationOnMethod() {
+        lint().files(java(
+            """
+            package test.pkg;
+            import android.annotation.EnforcePermission;
+            public class TestClass2 extends IFooMethod.Stub {
+                @Override
+                @EnforcePermission(android.Manifest.permission.READ_PHONE_STATE)
+                public void testMethod() {}
+            }
+            """).indented(),
+                *stubs
+        )
+        .run()
+        .expect("""
+        app: Information: module app => Stat(unannotated=0, enforced=1, notRequired=0) [AnnotatedAidlCounter]
+        0 errors, 0 warnings
+        """)
+    }
+
+    // A service with permission annotation on the method.
+    private val interfaceIFooMethodStub: TestFile = java(
+        """
+        public interface IFooMethod extends android.os.IInterface {
+         public static abstract class Stub extends android.os.Binder implements IFooMethod {}
+          @android.annotation.EnforcePermission(android.Manifest.permission.READ_PHONE_STATE)
+          public void testMethod();
+        }
+        """
+    ).indented()
+
+    // A service without any permission annotation.
+    private val interfaceIBarStub: TestFile = java(
+        """
+        public interface IBar extends android.os.IInterface {
+         public static abstract class Stub extends android.os.Binder implements IBar {
+            @Override
+            public void testMethod() {}
+          }
+          public void testMethod();
+        }
+        """
+    ).indented()
+
+    private val manifestPermissionStub: TestFile = java(
+        """
+        package android.Manifest;
+        class permission {
+          public static final String READ_PHONE_STATE = "android.permission.READ_PHONE_STATE";
+        }
+        """
+    ).indented()
+
+    private val enforcePermissionAnnotationStub: TestFile = java(
+        """
+        package android.annotation;
+        public @interface EnforcePermission {}
+        """
+    ).indented()
+
+    private val stubs = arrayOf(interfaceIFooMethodStub, interfaceIBarStub,
+            manifestPermissionStub, enforcePermissionAnnotationStub)
+}
diff --git a/tools/lint/utils/enforce_permission_counter.py b/tools/lint/utils/enforce_permission_counter.py
new file mode 100644
index 0000000..a4c00f7
--- /dev/null
+++ b/tools/lint/utils/enforce_permission_counter.py
@@ -0,0 +1,63 @@
+#  Copyright (C) 2023 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.
+
+import re
+
+import soong_lint_fix
+
+CHECK = "AnnotatedAidlCounter"
+LINT_MODULE = "AndroidUtilsLintChecker"
+
+class EnforcePermissionMigratedCounter(soong_lint_fix.SoongLintWrapper):
+    """Wrapper around lint_fix to count the number of AIDL methods annotated."""
+
+    def __init__(self):
+        super().__init__(check=CHECK, lint_module=LINT_MODULE)
+
+    def run(self):
+        self._setup()
+
+        # Analyze the dependencies of the "services" module and the module
+        # "services.core.unboosted".
+        service_module = self._find_module("services")
+        dep_modules = self._find_module_java_deps(service_module) + \
+                      [self._find_module("services.core.unboosted")]
+
+        # Skip dependencies that are not services. Skip the "services.core"
+        # module which is analyzed via "services.core.unboosted".
+        modules = []
+        for module in dep_modules:
+            if "frameworks/base/services" not in module.path:
+                continue
+            if module.name == "services.core":
+                continue
+            modules.append(module)
+
+        self._lint(modules)
+
+        counts = { "unannotated": 0, "enforced": 0, "notRequired": 0 }
+        for module in modules:
+            with open(module.lint_report, "r") as f:
+                content = f.read()
+                keys = dict(re.findall(r'(\w+)=(\d+)', content))
+                for key in keys:
+                    counts[key] += int(keys[key])
+        print(counts)
+        total = sum(counts.values())
+        annotated_percent = (1 - (counts["unannotated"] / total)) * 100
+        print("Annotated methods = %.2f%%" % (annotated_percent))
+
+
+if __name__ == "__main__":
+    EnforcePermissionMigratedCounter().run()
diff --git a/tools/obbtool/Main.cpp b/tools/obbtool/Main.cpp
index 64808c0..7014068 100644
--- a/tools/obbtool/Main.cpp
+++ b/tools/obbtool/Main.cpp
@@ -135,7 +135,7 @@
     }
 
     printf("OBB info for '%s':\n", filename);
-    printf("Package name: %s\n", obb->getPackageName().string());
+    printf("Package name: %s\n", obb->getPackageName().c_str());
     printf("     Version: %d\n", obb->getVersion());
     printf("       Flags: 0x%08x\n", obb->getFlags());
     printf("     Overlay: %s\n", obb->isOverlay() ? "true" : "false");
diff --git a/tools/split-select/Android.bp b/tools/split-select/Android.bp
index 5402657..ec9d42a 100644
--- a/tools/split-select/Android.bp
+++ b/tools/split-select/Android.bp
@@ -57,9 +57,6 @@
 
     // This tool is prebuilt if we're doing an app-only build.
     product_variables: {
-        pdk: {
-            enabled: false,
-        },
         unbundled_build: {
             enabled: false,
         },
diff --git a/tools/split-select/Grouper_test.cpp b/tools/split-select/Grouper_test.cpp
index 7294a86..a8b78cd 100644
--- a/tools/split-select/Grouper_test.cpp
+++ b/tools/split-select/Grouper_test.cpp
@@ -179,7 +179,7 @@
             errorMessage.append("\n");
         }
     }
-    ADD_FAILURE() << errorMessage.string();
+    ADD_FAILURE() << errorMessage.c_str();
 }
 
 void GrouperTest::addSplit(Vector<SplitDescription>& splits, const char* str) {
diff --git a/tools/split-select/Main.cpp b/tools/split-select/Main.cpp
index e6966db..73bfa19 100644
--- a/tools/split-select/Main.cpp
+++ b/tools/split-select/Main.cpp
@@ -99,8 +99,7 @@
         }
         masterRule = Rule::simplify(masterRule);
         fprintf(stdout, "  {\n    \"path\": \"%s\",\n    \"rules\": %s\n  }",
-                splits.keyAt(i).string(),
-                masterRule->toJson(2).string());
+                splits.keyAt(i).c_str(), masterRule->toJson(2).c_str());
     }
     fprintf(stdout, "\n]\n");
 }
@@ -158,25 +157,23 @@
         const char16_t* name = xml.getElementName(&len);
         String16 name16(name, len);
         if (name16 == kManifestTag) {
-            ssize_t idx = xml.indexOfAttribute(
-                    kAndroidNamespace.string(), kAndroidNamespace.size(),
-                    kVersionCodeAttr.string(), kVersionCodeAttr.size());
+            ssize_t idx = xml.indexOfAttribute(kAndroidNamespace.c_str(), kAndroidNamespace.size(),
+                                               kVersionCodeAttr.c_str(), kVersionCodeAttr.size());
             if (idx >= 0) {
                 outInfo.versionCode = xml.getAttributeData(idx);
             }
 
         } else if (name16 == kApplicationTag) {
-            ssize_t idx = xml.indexOfAttribute(
-                    kAndroidNamespace.string(), kAndroidNamespace.size(),
-                    kMultiArchAttr.string(), kMultiArchAttr.size());
+            ssize_t idx = xml.indexOfAttribute(kAndroidNamespace.c_str(), kAndroidNamespace.size(),
+                                               kMultiArchAttr.c_str(), kMultiArchAttr.size());
             if (idx >= 0) {
                 outInfo.multiArch = xml.getAttributeData(idx) != 0;
             }
 
         } else if (name16 == kUsesSdkTag) {
-            ssize_t idx = xml.indexOfAttribute(
-                    kAndroidNamespace.string(), kAndroidNamespace.size(),
-                    kMinSdkVersionAttr.string(), kMinSdkVersionAttr.size());
+            ssize_t idx =
+                    xml.indexOfAttribute(kAndroidNamespace.c_str(), kAndroidNamespace.size(),
+                                         kMinSdkVersionAttr.c_str(), kMinSdkVersionAttr.size());
             if (idx >= 0) {
                 uint16_t type = xml.getAttributeDataType(idx);
                 if (type >= Res_value::TYPE_FIRST_INT && type <= Res_value::TYPE_LAST_INT) {
@@ -187,10 +184,10 @@
                         fprintf(stderr, "warning: failed to retrieve android:minSdkVersion.\n");
                     } else {
                         char *endPtr;
-                        int minSdk = strtol(minSdk8->string(), &endPtr, 10);
-                        if (endPtr != minSdk8->string() + minSdk8->size()) {
+                        int minSdk = strtol(minSdk8->c_str(), &endPtr, 10);
+                        if (endPtr != minSdk8->c_str() + minSdk8->size()) {
                             fprintf(stderr, "warning: failed to parse android:minSdkVersion '%s'\n",
-                                    minSdk8->string());
+                                    minSdk8->c_str());
                         } else {
                             outInfo.minSdkVersion = minSdk;
                         }
@@ -232,7 +229,7 @@
             splits.add();
             Vector<String8> parts = AaptUtil::splitAndLowerCase(dir->getFileName(i), '-');
             if (parseAbi(parts, 0, &splits.editTop()) < 0) {
-                fprintf(stderr, "Malformed library %s\n", dir->getFileName(i).string());
+                fprintf(stderr, "Malformed library %s\n", dir->getFileName(i).c_str());
                 splits.pop();
             }
         }
@@ -260,7 +257,7 @@
                 usage();
                 return 1;
             }
-            targetConfigStr.setTo(*argv);
+            targetConfigStr = *argv;
         } else if (arg == "--split") {
             argc--;
             argv++;
@@ -284,14 +281,14 @@
                 usage();
                 return 1;
             }
-            baseApkPath.setTo(*argv);
+            baseApkPath = *argv;
         } else if (arg == "--generate") {
             generateFlag = true;
         } else if (arg == "--help") {
             help();
             return 0;
         } else {
-            fprintf(stderr, "error: unknown argument '%s'.\n", arg.string());
+            fprintf(stderr, "error: unknown argument '%s'.\n", arg.c_str());
             usage();
             return 1;
         }
@@ -313,15 +310,14 @@
     // Find out some details about the base APK.
     AppInfo baseAppInfo;
     if (!getAppInfo(baseApkPath, baseAppInfo)) {
-        fprintf(stderr, "error: unable to read base APK: '%s'.\n", baseApkPath.string());
+        fprintf(stderr, "error: unable to read base APK: '%s'.\n", baseApkPath.c_str());
         return 1;
     }
 
     SplitDescription targetSplit;
     if (!generateFlag) {
         if (!SplitDescription::parse(targetConfigStr, &targetSplit)) {
-            fprintf(stderr, "error: invalid --target config: '%s'.\n",
-                    targetConfigStr.string());
+            fprintf(stderr, "error: invalid --target config: '%s'.\n", targetConfigStr.c_str());
             usage();
             return 1;
         }
@@ -341,7 +337,7 @@
         Vector<SplitDescription> splits = extractSplitDescriptionsFromApk(splitApkPaths[i]);
         if (splits.isEmpty()) {
             fprintf(stderr, "error: invalid --split path: '%s'. No splits found.\n",
-                    splitApkPaths[i].string());
+                    splitApkPaths[i].c_str());
             usage();
             return 1;
         }
@@ -364,7 +360,7 @@
         const size_t matchingSplitApkPathCount = matchingSplitPaths.size();
         for (size_t i = 0; i < matchingSplitApkPathCount; i++) {
             if (matchingSplitPaths[i] != baseApkPath) {
-                fprintf(stdout, "%s\n", matchingSplitPaths[i].string());
+                fprintf(stdout, "%s\n", matchingSplitPaths[i].c_str());
             }
         }
     } else {
diff --git a/tools/split-select/Rule_test.cpp b/tools/split-select/Rule_test.cpp
index c6cff0d..c78533f 100644
--- a/tools/split-select/Rule_test.cpp
+++ b/tools/split-select/Rule_test.cpp
@@ -68,7 +68,7 @@
     expected.erase(std::remove_if(expected.begin(), expected.end(), ::isspace), expected.end());
 
     // Result
-    std::string result(rule.toJson().string());
+    std::string result(rule.toJson().c_str());
     result.erase(std::remove_if(result.begin(), result.end(), ::isspace), result.end());
 
     ASSERT_EQ(expected, result);
diff --git a/tools/split-select/SplitDescription.cpp b/tools/split-select/SplitDescription.cpp
index 99bc23d..c02e2d7 100644
--- a/tools/split-select/SplitDescription.cpp
+++ b/tools/split-select/SplitDescription.cpp
@@ -70,7 +70,7 @@
 String8 SplitDescription::toString() const {
     String8 extension;
     if (abi != abi::Variant_none) {
-        if (extension.isEmpty()) {
+        if (extension.empty()) {
             extension.append(":");
         } else {
             extension.append("-");
@@ -134,10 +134,10 @@
     String8 configStr;
     String8 extensionStr;
     if (index >= 0) {
-        configStr.setTo(str.string(), index);
-        extensionStr.setTo(str.string() + index + 1);
+        configStr = String8(str.c_str(), index);
+        extensionStr = (str.c_str() + index + 1);
     } else {
-        configStr.setTo(str);
+        configStr = str;
     }
 
     SplitDescription split;
diff --git a/tools/split-select/TestRules.cpp b/tools/split-select/TestRules.cpp
index 86ccd6a..ca3c56f 100644
--- a/tools/split-select/TestRules.cpp
+++ b/tools/split-select/TestRules.cpp
@@ -78,9 +78,8 @@
     const String8 actualStr(actual != NULL ? actual->toJson() : String8());
 
     if (expectedStr != actualStr) {
-        return ::testing::AssertionFailure()
-                << "Expected: " << expectedStr.string() << "\n"
-                << "  Actual: " << actualStr.string();
+        return ::testing::AssertionFailure() << "Expected: " << expectedStr.c_str() << "\n"
+                                             << "  Actual: " << actualStr.c_str();
     }
     return ::testing::AssertionSuccess();
 }
diff --git a/tools/validatekeymaps/Main.cpp b/tools/validatekeymaps/Main.cpp
index 0d7d5f9..6cae3ec 100644
--- a/tools/validatekeymaps/Main.cpp
+++ b/tools/validatekeymaps/Main.cpp
@@ -165,7 +165,7 @@
 
         case FileType::INPUT_DEVICE_CONFIGURATION: {
             android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
-                    PropertyMap::load(String8(filename));
+                    PropertyMap::load(String8(filename).c_str());
             if (!propertyMap.ok()) {
                 error("Error %d parsing input device configuration file.\n\n",
                       propertyMap.error().code());