Merge "Removed logging ProcessMemoryStatReported atom to statsd" into main
diff --git a/AconfigFlags.bp b/AconfigFlags.bp
index 16907b3..55f5436 100644
--- a/AconfigFlags.bp
+++ b/AconfigFlags.bp
@@ -18,8 +18,15 @@
 
     // Add java_aconfig_libraries to here to add them to the core framework
     srcs: [
+        ":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}",
     ],
+    // Add aconfig-annotations-lib as a dependency for the optimization
+    libs: ["aconfig-annotations-lib"],
 }
 
 // Default flags for java_aconfig_libraries that go into framework-minus-apex
@@ -30,6 +37,7 @@
     libs: ["fake_device_config"],
 }
 
+// Camera
 aconfig_declarations {
     name: "com.android.hardware.camera2-aconfig",
     package: "com.android.hardware.camera2",
@@ -41,3 +49,76 @@
     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"],
+}
+
+// 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"],
+}
diff --git a/OWNERS b/OWNERS
index 6c25324..4e5c7d8 100644
--- a/OWNERS
+++ b/OWNERS
@@ -28,7 +28,7 @@
 # Support bulk translation updates
 per-file */res*/values*/*.xml = byi@google.com, delphij@google.com
 
-per-file **.bp,**.mk = hansson@google.com, joeo@google.com
+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/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/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/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/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/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 5b9d989..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;
@@ -1565,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
@@ -1786,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/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/core/api/current.txt b/core/api/current.txt
index 92fa9f4..cba935f 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -32371,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";
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index c893b54..26c72f0 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";
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/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/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 21d4b64..d04d8be 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;
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/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/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/hardware/Camera.java b/core/java/android/hardware/Camera.java
index ccc39b6..0396443 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/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/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/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java
index 7d0cf9c..a9eb672 100644
--- a/core/java/android/nfc/NfcAdapter.java
+++ b/core/java/android/nfc/NfcAdapter.java
@@ -600,6 +600,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 +638,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");
@@ -706,12 +712,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);
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/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/security/OWNERS b/core/java/android/security/OWNERS
index dd17788..96c0be7 100644
--- a/core/java/android/security/OWNERS
+++ b/core/java/android/security/OWNERS
@@ -1,10 +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 *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/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/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/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/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/view/View.java b/core/java/android/view/View.java
index f50dc8d..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;
 
@@ -21888,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/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/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/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/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/server/SystemConfig.java b/core/java/com/android/server/SystemConfig.java
index 21da321..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 =
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_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_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 b7a30e5..2af9a38 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -474,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
@@ -503,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,
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 eda5075..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;
diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp
index 9dce5e3..6ed0a8a 100644
--- a/core/jni/android_util_Binder.cpp
+++ b/core/jni/android_util_Binder.cpp
@@ -953,8 +953,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;
     }
 }
@@ -1286,8 +1288,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");
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/com_android_internal_os_Zygote.cpp b/core/jni/com_android_internal_os_Zygote.cpp
index bbaea0a..418000f 100644
--- a/core/jni/com_android_internal_os_Zygote.cpp
+++ b/core/jni/com_android_internal_os_Zygote.cpp
@@ -1806,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)));
         }
     }
 
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/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/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/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/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/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 f3e15241..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/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..9eed904 100644
--- a/keystore/java/android/security/keystore/KeyGenParameterSpec.java
+++ b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
@@ -1508,7 +1508,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
diff --git a/keystore/java/android/security/keystore2/AndroidKeyStoreCipherSpiBase.java b/keystore/java/android/security/keystore2/AndroidKeyStoreCipherSpiBase.java
index d129891..9ac0f6d 100644
--- a/keystore/java/android/security/keystore2/AndroidKeyStoreCipherSpiBase.java
+++ b/keystore/java/android/security/keystore2/AndroidKeyStoreCipherSpiBase.java
@@ -20,6 +20,7 @@
 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;
@@ -137,6 +138,7 @@
         if (!(key instanceof AndroidKeyStorePrivateKey)
                 && (key instanceof PrivateKey || key instanceof PublicKey)) {
             try {
+                StrictMode.noteSlowCall("engineInit");
                 mCipher = Cipher.getInstance(getTransform());
                 String transform = getTransform();
 
@@ -203,6 +205,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 +236,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 +350,7 @@
         parameters.add(KeyStore2ParameterUtils.makeEnum(KeymasterDefs.KM_TAG_PURPOSE, purpose));
 
         try {
+            StrictMode.noteDiskRead();
             mOperation = mKey.getSecurityLevel().createOperation(
                     mKey.getKeyIdDescriptor(),
                     parameters
@@ -521,6 +526,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 +568,7 @@
     @Override
     protected final void engineUpdateAAD(ByteBuffer src) {
         if (mCipher != null) {
+            StrictMode.noteSlowCall("engineUpdateAAD");
             mCipher.updateAAD(src);
             return;
         }
@@ -715,6 +722,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 +815,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..1398da3 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;
@@ -617,6 +618,7 @@
 
     @Override
     public KeyPair generateKeyPair() {
+        StrictMode.noteSlowCall("generateKeyPair");
         if (mKeyStore == null || mSpec == null) {
             throw new IllegalStateException("Not initialized");
         }
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 ced58a2..eef8179 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;
@@ -164,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) {
@@ -447,6 +449,7 @@
             assertCanReplace(alias, targetDomain, mNamespace, descriptor);
 
             try {
+                StrictMode.noteDiskWrite();
                 mKeyStore.updateSubcomponents(
                         ((AndroidKeyStorePrivateKey) key).getKeyIdDescriptor(),
                         userCertBytes, chainBytes);
@@ -597,6 +600,7 @@
                     importArgs, flags, pkcs8EncodedPrivateKeyBytes);
 
             try {
+                StrictMode.noteDiskWrite();
                 mKeyStore.updateSubcomponents(metadata.key, userCertBytes, chainBytes);
             } catch (android.security.KeyStoreException e) {
                 mKeyStore.deleteKey(metadata.key);
@@ -932,6 +936,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: "
@@ -988,6 +993,7 @@
         }
 
         try {
+            StrictMode.noteDiskWrite();
             securityLevel.importWrappedKey(
                     wrappedKey, wrappingkey,
                     entry.getWrappedKeyBytes(),
@@ -1048,6 +1054,7 @@
         }
 
         try {
+            StrictMode.noteDiskWrite();
             mKeyStore.updateSubcomponents(makeKeyDescriptor(alias),
                     null /* publicCert - unused when used as pure certificate store. */,
                     encoded);
@@ -1060,6 +1067,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) {
@@ -1070,6 +1078,7 @@
 
     private KeyDescriptor[] getAliasesBatch(String startPastAlias) {
         try {
+            StrictMode.noteDiskRead();
             return mKeyStore.listBatch(
                     getTargetDomain(),
                     mNamespace,
@@ -1097,6 +1106,7 @@
     @Override
     public int engineSize() {
         try {
+            StrictMode.noteDiskRead();
             return mKeyStore.getNumberOfEntries(
                     getTargetDomain(),
                     mNamespace
@@ -1160,6 +1170,7 @@
 
         KeyDescriptor[] keyDescriptors = null;
         try {
+            StrictMode.noteDiskRead();
             keyDescriptors = mKeyStore.list(
                     getTargetDomain(),
                     mNamespace
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 795bb3c..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,7 +89,7 @@
     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.c_str(), 255);
@@ -104,7 +105,7 @@
         }
         ++p;
     }
-    path.appendPath(filename);
+    appendPath(path, filename);
     path.append("@idmap");
 
     return path;
@@ -181,7 +182,7 @@
 
     String8 realPath(path);
     if (kAppZipName) {
-        realPath.appendPath(kAppZipName);
+        appendPath(realPath, kAppZipName);
     }
     ap.type = ::getFileType(realPath.c_str());
     if (ap.type == kFileTypeRegular) {
@@ -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.
@@ -587,8 +588,8 @@
                 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");
+                appendPath(overlaysListPath, kResourceCache);
+                appendPath(overlaysListPath, "overlays.list");
                 addSystemOverlays(overlaysListPath.c_str(), ap.path, sharedRes, nextEntryIdx);
 #endif
                 sharedRes = const_cast<AssetManager*>(this)->
@@ -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);
+            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);
             }
@@ -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;
 }
 
@@ -897,7 +898,7 @@
 {
     Asset* pAsset = NULL;
 
-    if (strcasecmp(pathName.getPathExtension().c_str(), ".gz") == 0) {
+    if (strcasecmp(getPathExtension(pathName).c_str(), ".gz") == 0) {
         //printf("TRYING '%s'\n", (const char*) pathName);
         pAsset = Asset::createFromCompressedFile(pathName.c_str(), mode);
     } else {
@@ -1078,8 +1079,7 @@
     //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)
@@ -1176,7 +1176,7 @@
             fileType = kFileTypeUnknown;
 #else
         // stat the file
-        fileType = ::getFileType(path.appendPathCopy(entry->d_name).c_str());
+        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().c_str(), ".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);
     }
 
@@ -1220,7 +1220,7 @@
 
     /* 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
@@ -1269,7 +1269,7 @@
             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()));
@@ -1425,7 +1425,7 @@
       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.c_str());
     mZipFile = ZipFileRO::open(mPath.c_str());
@@ -1439,7 +1439,7 @@
       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.c_str());
     mZipFile = ZipFileRO::openFd(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;
@@ -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;
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/BackupHelpers.cpp b/libs/androidfw/BackupHelpers.cpp
index 3582609..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>
@@ -606,14 +607,14 @@
             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
@@ -654,7 +655,7 @@
         // 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.c_str());
         memset(paxHeader + 345, 0, 155);            // rewrite the prefix area
diff --git a/libs/androidfw/OWNERS b/libs/androidfw/OWNERS
index 436f107..ef4cc46 100644
--- a/libs/androidfw/OWNERS
+++ b/libs/androidfw/OWNERS
@@ -1,5 +1,4 @@
 set noparent
-toddke@google.com
 zyy@google.com
 patb@google.com
 
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 0e7d841..11d153e 100644
--- a/libs/androidfw/ResourceTypes.cpp
+++ b/libs/androidfw/ResourceTypes.cpp
@@ -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";
         }
@@ -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);
         }
     }
 
@@ -7398,10 +7398,10 @@
         *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;
 }
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/hwui/RenderNode.h b/libs/hwui/RenderNode.h
index 7092e17..208dc3e 100644
--- a/libs/hwui/RenderNode.h
+++ b/libs/hwui/RenderNode.h
@@ -121,9 +121,9 @@
         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/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/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/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/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/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/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 44a0baa..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) {
@@ -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;
     }
 
@@ -3337,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/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/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/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/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/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/OWNERS b/packages/SystemUI/OWNERS
index 0cd8b45..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
@@ -35,6 +35,7 @@
 gwasserman@google.com
 hwwang@google.com
 hyunyoungs@google.com
+ikateryna@google.com
 jaggies@google.com
 jamesoleary@google.com
 jbolinger@google.com
@@ -72,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
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/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/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/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/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/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/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/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/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/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index 08c71c3..7f92960 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -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;
+                }
             }
         }
     }
@@ -1372,6 +1377,44 @@
         }
     }
 
+    /**
+     * 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();
@@ -1907,6 +1950,7 @@
 
             mPrimaryStorageUuid = mMoveTargetUuid;
             writeSettingsLocked();
+            mHandler.obtainMessage(H_REMOUNT_VOLUMES_ON_MOVE).sendToTarget();
         }
 
         if (PackageManager.isMoveStatusFinished(status)) {
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/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/audio/AudioDeviceBroker.java b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
index c17d2c8..1ad2420 100644
--- a/services/core/java/com/android/server/audio/AudioDeviceBroker.java
+++ b/services/core/java/com/android/server/audio/AudioDeviceBroker.java
@@ -1941,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 4c234a0..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;
@@ -12322,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
@@ -12335,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/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 cba5039..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
@@ -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));
-                        }
                     }
                 }
 
@@ -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/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/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/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/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/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/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 187b939..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;
@@ -54,16 +62,17 @@
             + "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/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/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/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/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/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/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 34a901c..e6b7cf3b 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -4439,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";
 
@@ -4458,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";
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/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/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/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/MffContext.java b/tests/Camera2Tests/SmartCamera/SimpleCamera/src/androidx/media/filterfw/MffContext.java
index 6bd6c18..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;
@@ -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.
      *
@@ -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/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/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/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 ae72247..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/tools/aapt/AaptAssets.cpp b/tools/aapt/AaptAssets.cpp
index b94d14f..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);
 
@@ -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,7 +308,7 @@
                 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",
@@ -315,14 +317,14 @@
             }
         } 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.c_str());
                 return -1;
@@ -331,15 +333,15 @@
             // 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.c_str());
             return -1;
@@ -349,7 +351,7 @@
     } else {
         if ((part.length() == 2 || part.length() == 3)
                && isAlpha(part) && strcmp("car", part.c_str())) {
-            setLanguage(part);
+            setLanguage(part.c_str());
             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;
     }
@@ -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);
     }
 
@@ -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,7 +703,7 @@
         String8 pathName(srcDir);
         FileType type;
 
-        pathName.appendPath(fileNames[i].c_str());
+        appendPath(pathName, fileNames[i]);
         type = getFileType(pathName.c_str());
         if (type == kFileTypeDirectory) {
             sp<AaptDir> subdir;
@@ -709,7 +711,7 @@
             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,
@@ -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...
@@ -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++;
     }
@@ -1154,7 +1156,7 @@
         }
 
         String8 subdirName(srcDir);
-        subdirName.appendPath(entry->d_name);
+        appendPath(subdirName, entry->d_name);
 
         AaptGroupEntry group;
         String8 resType;
@@ -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().c_str(), &resType);
+            kind.initFromDirName(walkPath(remain).c_str(), &resType);
         } else {
             // these are untyped and don't have an AaptGroupEntry
         }
@@ -1258,10 +1260,10 @@
         }
 
         // 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.c_str());
             count = err;
@@ -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
@@ -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
@@ -1540,7 +1542,7 @@
     }
 
     const String8& featureOfBase = bundle->getFeatureOfPackage();
-    if (!featureOfBase.isEmpty()) {
+    if (!featureOfBase.empty()) {
         if (bundle->getVerbose()) {
             printf("Including base feature resources from package: %s\n",
                     featureOfBase.c_str());
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/CacheUpdater.h b/tools/aapt/CacheUpdater.h
index 2dc143c..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
@@ -72,14 +75,14 @@
             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();
+                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.c_str());
@@ -101,7 +104,7 @@
     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 5a06b10..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>
@@ -400,7 +401,7 @@
 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>();
@@ -1133,7 +1134,7 @@
                 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++) {
@@ -1300,7 +1301,7 @@
                             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.c_str()).c_str());
                     }
@@ -2486,12 +2487,12 @@
     for (int i = 1; i < bundle->getFileSpecCount(); i++) {
         const char* fileName = bundle->getFileSpecEntry(i);
 
-        if (strcasecmp(String8(fileName).getPathExtension().c_str(), ".gz") == 0) {
+        if (strcasecmp(getPathExtension(String8(fileName)).c_str(), ".gz") == 0) {
             printf(" '%s'... (from gzip)\n", fileName);
-            result = zip->addGzip(fileName, String8(fileName).getBasePath().c_str(), 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.c_str()).c_str());
                 result = zip->add(fileName, storageName.c_str(),
@@ -2617,10 +2618,10 @@
         return original;
     }
 
-    String8 ext(original.getPathExtension());
+    String8 ext(getPathExtension(original));
     if (ext == String8(".apk")) {
         return String8::format("%s_%s%s",
-                original.getBasePath().c_str(),
+                getBasePath(original).c_str(),
                 split->getDirectorySafeName().c_str(),
                 ext.c_str());
     }
@@ -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);
     }
 
@@ -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 1f2febe..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>
@@ -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 cea3a6e..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>
@@ -77,7 +78,7 @@
 
         mEntry = *entryPtr;
         // Get stats
-        String8 fullPath = mBasePath.appendPathCopy(mEntry.d_name);
+        String8 fullPath = appendPathCopy(mBasePath, mEntry.d_name);
         stat(fullPath.c_str(),&mStats);
         return &mEntry;
     };
diff --git a/tools/aapt/FileFinder.cpp b/tools/aapt/FileFinder.cpp
index a5c19806..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,7 +58,7 @@
         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.c_str()) ) {
             DirectoryWalker* copy = dw->clone();
@@ -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 c6c7e96..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>
 
@@ -1357,7 +1358,7 @@
 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.c_str(), ".png") != 0) {
@@ -1518,7 +1519,7 @@
 
     // Check to see if we're dealing with a 9-patch
     // If we are, process appropriately
-    if (source.getBasePath().getPathExtension() == ".9")  {
+    if (getPathExtension(getBasePath(source)) == ".9")  {
         if (do_9patch(source.c_str(), &imageInfo) != NO_ERROR) {
             return error;
         }
@@ -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.c_str(), ".xml") == 0) {
-        String16 resourceName(parseResourceName(file->getSourceFile().getPathLeaf()));
+        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 965655b..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>
@@ -169,7 +171,7 @@
     /* anything here? */
     if (zip->getNumEntries() == 0) {
         if (bundle->getVerbose()) {
-            printf("Archive is empty -- removing %s\n", outputFile.getPathLeaf().c_str());
+            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;
@@ -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;
             }
@@ -273,9 +275,9 @@
         return true;
     }
 
-    if (strcasecmp(storageName.getPathExtension().c_str(), ".gz") == 0) {
+    if (strcasecmp(getPathExtension(storageName).c_str(), ".gz") == 0) {
         fromGzip = true;
-        storageName = storageName.getBasePath();
+        storageName = getBasePath(storageName);
     }
 
     if (bundle->getUpdate()) {
@@ -365,7 +367,7 @@
  */
 bool okayToCompress(Bundle* bundle, const String8& pathName)
 {
-    String8 ext = pathName.getPathExtension();
+    String8 ext = getPathExtension(pathName);
     int i;
 
     if (ext.length() == 0)
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index 4ca3a68..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.
@@ -142,8 +145,8 @@
                         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",
@@ -321,7 +324,7 @@
             str++;
         }
         String8 resPath = it.getPath();
-        resPath.convertToResPath();
+        convertToResPath(resPath);
         status_t result = table->addEntry(SourcePos(it.getPath(), 0),
                         String16(assets->getPackage()),
                         type16,
@@ -778,7 +781,7 @@
         if (kIsDebug) {
             printf("Qualifying class '%s' to '%s'", name.c_str(), className.c_str());
         }
-        attr->string.setTo(String16(className));
+        attr->string = String16(className);
     }
 }
 
@@ -921,7 +924,7 @@
 
     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,7 +971,7 @@
             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.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);
                 }
             }
         }
@@ -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;
@@ -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());
@@ -2850,7 +2853,7 @@
                 s++;
                 if (s > last && (*s == '.' || *s == 0)) {
                     String8 part(last, s-last);
-                    dest.appendPath(part);
+                    appendPath(dest, part);
 #ifdef _WIN32
                     _mkdir(dest.c_str());
 #else
@@ -2860,7 +2863,7 @@
                 }
             } while (*s);
         }
-        dest.appendPath(className);
+        appendPath(dest, className);
         dest.append(".java");
         FILE* fp = fopen(dest.c_str(), "w+");
         if (fp == NULL) {
@@ -2891,7 +2894,7 @@
 
         if (textSymbolsDest != NULL && R == className) {
             String8 textDest(textSymbolsDest);
-            textDest.appendPath(className);
+            appendPath(textDest, className);
             textDest.append(".txt");
 
             FILE* fp = fopen(textDest.c_str(), "w+");
@@ -2917,7 +2920,7 @@
         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.c_str(), "a");
             fprintf(fp,"%s \\\n", dest.c_str());
@@ -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) {
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 3abb89a..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;
     }
 
@@ -1362,11 +1364,11 @@
                     size_t length;
                     const char16_t* attr = block.getAttributeName(i, &length);
                     if (strcmp16(attr, name16.c_str()) == 0) {
-                        name.setTo(block.getAttributeStringValue(i, &length));
+                        name = String16(block.getAttributeStringValue(i, &length));
                     } else if (strcmp16(attr, translatable16.c_str()) == 0) {
-                        translatable.setTo(block.getAttributeStringValue(i, &length));
+                        translatable = String16(block.getAttributeStringValue(i, &length));
                     } else if (strcmp16(attr, formatted16.c_str()) == 0) {
-                        formatted.setTo(block.getAttributeStringValue(i, &length));
+                        formatted = String16(block.getAttributeStringValue(i, &length));
                     }
                 }
                 
@@ -1540,7 +1542,7 @@
                 } else {
                     ssize_t sep = ident.findLast('.');
                     if (sep >= 0) {
-                        parentIdent.setTo(ident, sep);
+                        parentIdent = String16(ident, sep);
                     }
                 }
 
@@ -1812,7 +1814,7 @@
     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",
@@ -1822,7 +1824,7 @@
 
         const ResTable& featureTable = featureAssetManager.getResources(false);
         mTypeIdOffset = std::max(mTypeIdOffset,
-                findLargestTypeIdForPackage(featureTable, mAssetsPackage)); 
+                findLargestTypeIdForPackage(featureTable, mAssetsPackage));
     }
 
     return NO_ERROR;
@@ -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)) {
@@ -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";
@@ -4803,7 +4805,7 @@
     String8 resPath = String8::format("res/%s/%s.xml",
             newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
             String8(resourceName).c_str());
-    resPath.convertToResPath();
+    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();
 
@@ -4927,7 +4929,7 @@
         String8 resPath = String8::format("res/%s/%s.xml",
                 newFile->getGroupEntry().toDirName(target->getResourceType()).c_str(),
                 String8(resourceName).c_str());
-        resPath.convertToResPath();
+        convertToResPath(resPath);
 
         // Add a resource table entry.
         if (bundle->getVerbose()) {
diff --git a/tools/aapt/SourcePos.cpp b/tools/aapt/SourcePos.cpp
index e130286..354a65c 100644
--- a/tools/aapt/SourcePos.cpp
+++ b/tools/aapt/SourcePos.cpp
@@ -78,7 +78,7 @@
         break;
     }
     
-    if (!this->file.isEmpty()) {
+    if (!this->file.empty()) {
         if (this->line >= 0) {
             fprintf(to, "%s:%d: %s%s\n", this->file.c_str(), this->line, type, this->error.c_str());
         } else {
diff --git a/tools/aapt/StringPool.cpp b/tools/aapt/StringPool.cpp
index 8d02683..1af8d6f 100644
--- a/tools/aapt/StringPool.cpp
+++ b/tools/aapt/StringPool.cpp
@@ -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;
@@ -592,7 +592,7 @@
     ssize_t res = indices != NULL && indices->size() > 0 ? indices->itemAt(0) : -1;
     if (kIsDebug) {
         printf("Offset for string %s: %zd (%s)\n", String8(val).c_str(), res,
-                res >= 0 ? String8(mEntries[mEntryArray[res]].value).c_str() : String8());
+               res >= 0 ? String8(mEntries[mEntryArray[res]].value).c_str() : "");
     }
     return res;
 }
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 e270a73..1a648c0 100644
--- a/tools/aapt/XMLNode.cpp
+++ b/tools/aapt/XMLNode.cpp
@@ -334,9 +334,9 @@
             String16 spanTag;
             ssize_t semi = span.name.findFirst(';');
             if (semi >= 0) {
-                spanTag.setTo(span.name.c_str(), semi);
+                spanTag = String16(span.name.c_str(), semi);
             } else {
-                spanTag.setTo(span.name);
+                spanTag = span.name;
             }
             if (strcmp16(inXml->getElementName(&len), spanTag.c_str()) != 0) {
                 SourcePos(String8(fileName), inXml->getLineNumber()).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;
@@ -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());
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/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/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/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/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/soong_lint_fix.py b/tools/lint/fix/soong_lint_fix.py
index cd4d778d..acc0ad0 100644
--- a/tools/lint/fix/soong_lint_fix.py
+++ b/tools/lint/fix/soong_lint_fix.py
@@ -29,6 +29,39 @@
 PATH_SUFFIX = "android_common/lint"
 FIX_ZIP = "suggested-fixes.zip"
 
+
+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
+    """
+    def __init__(self, name):
+        self._name = name
+
+    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!")
+
+        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}"
+
+    @property
+    def name(self):
+        return self._name
+
+    @property
+    def lint_report(self):
+        return f"{self._path}/lint-report.txt"
+
+    @property
+    def suggested_fixes(self):
+        return f"{self._path}/{FIX_ZIP}"
+
+
 class SoongLintFix:
     """
     This class creates a command line tool that will
@@ -53,16 +86,14 @@
         self._parser = _setup_parser()
         self._args = None
         self._kwargs = None
-        self._path = None
-        self._target = None
+        self._modules = []
 
-
-    def run(self, additional_setup=None, custom_fix=None):
+    def run(self):
         """
         Run the script
         """
         self._setup()
-        self._find_module()
+        self._find_modules()
         self._lint()
 
         if not self._args.no_fix:
@@ -87,8 +118,6 @@
 
         os.chdir(ANDROID_BUILD_TOP)
 
-
-    def _find_module(self):
         print("Refreshing soong modules...")
         try:
             os.mkdir(ANDROID_PRODUCT_OUT)
@@ -97,48 +126,47 @@
         subprocess.call(f"{SOONG_UI} --make-mode {PRODUCT_OUT}/module-info.json", **self._kwargs)
         print("done.")
 
+
+    def _find_modules(self):
         with open(f"{ANDROID_PRODUCT_OUT}/module-info.json") as f:
             module_info = json.load(f)
 
-        if self._args.module not in module_info:
-            sys.exit(f"Module {self._args.module} not found!")
-
-        module_path = module_info[self._args.module]["path"][0]
-        print(f"Found module {module_path}/{self._args.module}.")
-
-        self._path = f"{PATH_PREFIX}/{module_path}/{self._args.module}/{PATH_SUFFIX}"
-        self._target = f"{self._path}/lint-report.txt"
-
+        for module_name in self._args.modules:
+            module = SoongModule(module_name)
+            module.find(module_info)
+            self._modules.append(module)
 
     def _lint(self):
         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 self._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 self._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)
+        for module in self._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):
-        print("### lint-report.txt ###", end="\n\n")
-        with open(self._target, "r") as f:
-            print(f.read())
+        for module in self._modules:
+            print(f"### lint-report.txt {module.name} ###", end="\n\n")
+            with open(module.lint_report, "r") as f:
+                print(f.read())
 
 
 def _setup_parser():
@@ -151,7 +179,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 +199,4 @@
     return parser
 
 if __name__ == "__main__":
-    SoongLintFix().run()
\ No newline at end of file
+    SoongLintFix().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/utils/Android.bp b/tools/lint/utils/Android.bp
new file mode 100644
index 0000000..75e8d68
--- /dev/null
+++ b/tools/lint/utils/Android.bp
@@ -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 {
+    // 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",
+    ],
+}
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/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/Main.cpp b/tools/split-select/Main.cpp
index 1e75117..73bfa19 100644
--- a/tools/split-select/Main.cpp
+++ b/tools/split-select/Main.cpp
@@ -257,7 +257,7 @@
                 usage();
                 return 1;
             }
-            targetConfigStr.setTo(*argv);
+            targetConfigStr = *argv;
         } else if (arg == "--split") {
             argc--;
             argv++;
@@ -281,7 +281,7 @@
                 usage();
                 return 1;
             }
-            baseApkPath.setTo(*argv);
+            baseApkPath = *argv;
         } else if (arg == "--generate") {
             generateFlag = true;
         } else if (arg == "--help") {
diff --git a/tools/split-select/SplitDescription.cpp b/tools/split-select/SplitDescription.cpp
index 4e2b48e..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.c_str(), index);
-        extensionStr.setTo(str.c_str() + 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/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());