Merge "sched_policy: add get_cpuset/sched_policy_profile_name"
diff --git a/adb/Android.bp b/adb/Android.bp
index 3dc70b5..2f9c8fc 100644
--- a/adb/Android.bp
+++ b/adb/Android.bp
@@ -27,7 +27,6 @@
         "-DADB_HOST=1",         // overridden by adbd_defaults
         "-DALLOW_ADBD_ROOT=0",  // overridden by adbd_defaults
         "-DANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION=1",
-        "-DENABLE_FASTDEPLOY=1", // enable fast deploy
     ],
     cpp_std: "experimental",
 
@@ -691,6 +690,7 @@
     name: "libfastdeploy_host",
     defaults: ["adb_defaults"],
     srcs: [
+        "fastdeploy/deploypatchgenerator/apk_archive.cpp",
         "fastdeploy/deploypatchgenerator/deploy_patch_generator.cpp",
         "fastdeploy/deploypatchgenerator/patch_utils.cpp",
         "fastdeploy/proto/ApkEntry.proto",
@@ -727,6 +727,7 @@
     name: "fastdeploy_test",
     defaults: ["adb_defaults"],
     srcs: [
+        "fastdeploy/deploypatchgenerator/apk_archive_test.cpp",
         "fastdeploy/deploypatchgenerator/deploy_patch_generator_test.cpp",
         "fastdeploy/deploypatchgenerator/patch_utils_test.cpp",
     ],
@@ -754,6 +755,9 @@
         },
     },
     data: [
+        "fastdeploy/testdata/rotating_cube-metadata-release.data",
         "fastdeploy/testdata/rotating_cube-release.apk",
+        "fastdeploy/testdata/sample.apk",
+        "fastdeploy/testdata/sample.cd",
     ],
 }
diff --git a/adb/client/adb_install.cpp b/adb/client/adb_install.cpp
index 042a2d6..73dcde1 100644
--- a/adb/client/adb_install.cpp
+++ b/adb/client/adb_install.cpp
@@ -37,9 +37,7 @@
 #include "commandline.h"
 #include "fastdeploy.h"
 
-#if defined(ENABLE_FASTDEPLOY)
 static constexpr int kFastDeployMinApi = 24;
-#endif
 
 namespace {
 
@@ -146,15 +144,7 @@
     *buf = '\0';
 }
 
-#if defined(ENABLE_FASTDEPLOY)
-static int delete_device_patch_file(const char* apkPath) {
-    std::string patchDevicePath = get_patch_path(apkPath);
-    return delete_device_file(patchDevicePath);
-}
-#endif
-
-static int install_app_streamed(int argc, const char** argv, bool use_fastdeploy,
-                                bool use_localagent) {
+static int install_app_streamed(int argc, const char** argv, bool use_fastdeploy) {
     printf("Performing Streamed Install\n");
 
     // The last argument must be the APK file
@@ -176,31 +166,15 @@
         error_exit("--fastdeploy doesn't support .apex files");
     }
 
-    if (use_fastdeploy == true) {
-#if defined(ENABLE_FASTDEPLOY)
-        TemporaryFile metadataTmpFile;
-        std::string patchTmpFilePath;
-        {
-            TemporaryFile patchTmpFile;
-            patchTmpFile.DoNotRemove();
-            patchTmpFilePath = patchTmpFile.path;
+    if (use_fastdeploy) {
+        auto metadata = extract_metadata(file);
+        if (metadata.has_value()) {
+            // pass all but 1st (command) and last (apk path) parameters through to pm for
+            // session creation
+            std::vector<const char*> pm_args{argv + 1, argv + argc - 1};
+            auto patchFd = install_patch(pm_args.size(), pm_args.data());
+            return stream_patch(file, std::move(metadata.value()), std::move(patchFd));
         }
-
-        FILE* metadataFile = fopen(metadataTmpFile.path, "wb");
-        extract_metadata(file, metadataFile);
-        fclose(metadataFile);
-
-        create_patch(file, metadataTmpFile.path, patchTmpFilePath.c_str());
-        // pass all but 1st (command) and last (apk path) parameters through to pm for
-        // session creation
-        std::vector<const char*> pm_args{argv + 1, argv + argc - 1};
-        install_patch(file, patchTmpFilePath.c_str(), pm_args.size(), pm_args.data());
-        adb_unlink(patchTmpFilePath.c_str());
-        delete_device_patch_file(file);
-        return 0;
-#else
-        error_exit("fastdeploy is disabled");
-#endif
     }
 
     struct stat sb;
@@ -265,8 +239,7 @@
     return 1;
 }
 
-static int install_app_legacy(int argc, const char** argv, bool use_fastdeploy,
-                              bool use_localagent) {
+static int install_app_legacy(int argc, const char** argv, bool use_fastdeploy) {
     printf("Performing Push Install\n");
 
     // Find last APK argument.
@@ -287,35 +260,26 @@
     int result = -1;
     std::vector<const char*> apk_file = {argv[last_apk]};
     std::string apk_dest = "/data/local/tmp/" + android::base::Basename(argv[last_apk]);
-
-    if (use_fastdeploy == true) {
-#if defined(ENABLE_FASTDEPLOY)
-        TemporaryFile metadataTmpFile;
-        TemporaryFile patchTmpFile;
-
-        FILE* metadataFile = fopen(metadataTmpFile.path, "wb");
-        extract_metadata(apk_file[0], metadataFile);
-        fclose(metadataFile);
-
-        create_patch(apk_file[0], metadataTmpFile.path, patchTmpFile.path);
-        apply_patch_on_device(apk_file[0], patchTmpFile.path, apk_dest.c_str());
-#else
-        error_exit("fastdeploy is disabled");
-#endif
-    } else {
-        if (!do_sync_push(apk_file, apk_dest.c_str(), false)) goto cleanup_apk;
-    }
-
     argv[last_apk] = apk_dest.c_str(); /* destination name, not source location */
-    result = pm_command(argc, argv);
 
-cleanup_apk:
-    if (use_fastdeploy == true) {
-#if defined(ENABLE_FASTDEPLOY)
-        delete_device_patch_file(apk_file[0]);
-#endif
+    if (use_fastdeploy) {
+        auto metadata = extract_metadata(apk_file[0]);
+        if (metadata.has_value()) {
+            auto patchFd = apply_patch_on_device(apk_dest.c_str());
+            int status = stream_patch(apk_file[0], std::move(metadata.value()), std::move(patchFd));
+
+            result = pm_command(argc, argv);
+            delete_device_file(apk_dest);
+
+            return status;
+        }
     }
-    delete_device_file(apk_dest);
+
+    if (do_sync_push(apk_file, apk_dest.c_str(), false)) {
+        result = pm_command(argc, argv);
+        delete_device_file(apk_dest);
+    }
+
     return result;
 }
 
@@ -324,7 +288,6 @@
     InstallMode installMode = INSTALL_DEFAULT;
     bool use_fastdeploy = false;
     bool is_reinstall = false;
-    bool use_localagent = false;
     FastDeploy_AgentUpdateStrategy agent_update_strategy = FastDeploy_AgentUpdateDifferentVersion;
 
     for (int i = 1; i < argc; i++) {
@@ -353,11 +316,6 @@
         } else if (!strcmp(argv[i], "--version-check-agent")) {
             processedArgIndicies.push_back(i);
             agent_update_strategy = FastDeploy_AgentUpdateDifferentVersion;
-#ifndef _WIN32
-        } else if (!strcmp(argv[i], "--local-agent")) {
-            processedArgIndicies.push_back(i);
-            use_localagent = true;
-#endif
         }
     }
 
@@ -369,14 +327,13 @@
         error_exit("Attempting to use streaming install on unsupported device");
     }
 
-#if defined(ENABLE_FASTDEPLOY)
-    if (use_fastdeploy == true && get_device_api_level() < kFastDeployMinApi) {
+    if (use_fastdeploy && get_device_api_level() < kFastDeployMinApi) {
         printf("Fast Deploy is only compatible with devices of API version %d or higher, "
                "ignoring.\n",
                kFastDeployMinApi);
         use_fastdeploy = false;
     }
-#endif
+    fastdeploy_set_agent_update_strategy(agent_update_strategy);
 
     std::vector<const char*> passthrough_argv;
     for (int i = 0; i < argc; i++) {
@@ -389,26 +346,13 @@
         error_exit("install requires an apk argument");
     }
 
-    if (use_fastdeploy == true) {
-#if defined(ENABLE_FASTDEPLOY)
-        fastdeploy_set_local_agent(use_localagent);
-        update_agent(agent_update_strategy);
-
-        // The last argument must be the APK file
-        const char* file = passthrough_argv.back();
-        use_fastdeploy = find_package(file);
-#else
-        error_exit("fastdeploy is disabled");
-#endif
-    }
-
     switch (installMode) {
         case INSTALL_PUSH:
             return install_app_legacy(passthrough_argv.size(), passthrough_argv.data(),
-                                      use_fastdeploy, use_localagent);
+                                      use_fastdeploy);
         case INSTALL_STREAM:
             return install_app_streamed(passthrough_argv.size(), passthrough_argv.data(),
-                                        use_fastdeploy, use_localagent);
+                                        use_fastdeploy);
         case INSTALL_DEFAULT:
         default:
             return 1;
diff --git a/adb/client/auth.cpp b/adb/client/auth.cpp
index ed6a9a8..e8be784 100644
--- a/adb/client/auth.cpp
+++ b/adb/client/auth.cpp
@@ -173,7 +173,8 @@
 
     RSA* key = RSA_new();
     if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
-        LOG(ERROR) << "Failed to read key";
+        LOG(ERROR) << "Failed to read key from '" << file << "'";
+        ERR_print_errors_fp(stderr);
         RSA_free(key);
         return nullptr;
     }
@@ -249,7 +250,7 @@
     return adb_get_android_dir_path() + OS_PATH_SEPARATOR + "adbkey";
 }
 
-static bool generate_userkey() {
+static bool load_userkey() {
     std::string path = get_user_key_path();
     if (path.empty()) {
         PLOG(ERROR) << "Error getting user key filename";
@@ -435,8 +436,8 @@
 void adb_auth_init() {
     LOG(INFO) << "adb_auth_init...";
 
-    if (!generate_userkey()) {
-        LOG(ERROR) << "Failed to generate user key";
+    if (!load_userkey()) {
+        LOG(ERROR) << "Failed to load (or generate) user key";
         return;
     }
 
diff --git a/adb/client/commandline.cpp b/adb/client/commandline.cpp
index a0818d3..0ffdbc2 100644
--- a/adb/client/commandline.cpp
+++ b/adb/client/commandline.cpp
@@ -255,13 +255,8 @@
 }
 #endif
 
-// Reads from |fd| and prints received data. If |use_shell_protocol| is true
-// this expects that incoming data will use the shell protocol, in which case
-// stdout/stderr are routed independently and the remote exit code will be
-// returned.
-// if |callback| is non-null, stdout/stderr output will be handled by it.
-int read_and_dump(borrowed_fd fd, bool use_shell_protocol = false,
-                  StandardStreamsCallbackInterface* callback = &DEFAULT_STANDARD_STREAMS_CALLBACK) {
+int read_and_dump(borrowed_fd fd, bool use_shell_protocol,
+                  StandardStreamsCallbackInterface* callback) {
     int exit_code = 0;
     if (fd < 0) return exit_code;
 
diff --git a/adb/client/commandline.h b/adb/client/commandline.h
index cd5933a..ab77b29 100644
--- a/adb/client/commandline.h
+++ b/adb/client/commandline.h
@@ -109,6 +109,14 @@
         const std::string& command, bool disable_shell_protocol = false,
         StandardStreamsCallbackInterface* callback = &DEFAULT_STANDARD_STREAMS_CALLBACK);
 
+// Reads from |fd| and prints received data. If |use_shell_protocol| is true
+// this expects that incoming data will use the shell protocol, in which case
+// stdout/stderr are routed independently and the remote exit code will be
+// returned.
+// if |callback| is non-null, stdout/stderr output will be handled by it.
+int read_and_dump(borrowed_fd fd, bool use_shell_protocol = false,
+                  StandardStreamsCallbackInterface* callback = &DEFAULT_STANDARD_STREAMS_CALLBACK);
+
 // Connects to the device "abb" service with |command| and returns the fd.
 template <typename ContainerT>
 unique_fd send_abb_exec_command(const ContainerT& command_args, std::string* error) {
diff --git a/adb/client/fastdeploy.cpp b/adb/client/fastdeploy.cpp
index fbae219..bdc9e56 100644
--- a/adb/client/fastdeploy.cpp
+++ b/adb/client/fastdeploy.cpp
@@ -30,112 +30,114 @@
 #include "deployagent.inc"        // Generated include via build rule.
 #include "deployagentscript.inc"  // Generated include via build rule.
 #include "fastdeploy/deploypatchgenerator/deploy_patch_generator.h"
+#include "fastdeploy/deploypatchgenerator/patch_utils.h"
+#include "fastdeploy/proto/ApkEntry.pb.h"
 #include "fastdeploycallbacks.h"
 #include "sysdeps.h"
 
 #include "adb_utils.h"
 
-static constexpr long kRequiredAgentVersion = 0x00000002;
+static constexpr long kRequiredAgentVersion = 0x00000003;
 
-static constexpr const char* kDeviceAgentPath = "/data/local/tmp/";
+static constexpr int kPackageMissing = 3;
+static constexpr int kInvalidAgentVersion = 4;
+
 static constexpr const char* kDeviceAgentFile = "/data/local/tmp/deployagent.jar";
 static constexpr const char* kDeviceAgentScript = "/data/local/tmp/deployagent";
 
-static bool g_use_localagent = false;
+static constexpr bool g_verbose_timings = false;
+static FastDeploy_AgentUpdateStrategy g_agent_update_strategy =
+        FastDeploy_AgentUpdateDifferentVersion;
 
-long get_agent_version() {
-    std::vector<char> versionOutputBuffer;
-    std::vector<char> versionErrorBuffer;
+using APKMetaData = com::android::fastdeploy::APKMetaData;
 
-    int statusCode = capture_shell_command("/data/local/tmp/deployagent version",
-                                           &versionOutputBuffer, &versionErrorBuffer);
-    long version = -1;
+namespace {
 
-    if (statusCode == 0 && versionOutputBuffer.size() > 0) {
-        version = strtol((char*)versionOutputBuffer.data(), NULL, 16);
+struct TimeReporter {
+    TimeReporter(const char* label) : label_(label) {}
+    ~TimeReporter() {
+        if (g_verbose_timings) {
+            auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
+                    std::chrono::steady_clock::now() - start_);
+            fprintf(stderr, "%s finished in %lldms\n", label_,
+                    static_cast<long long>(duration.count()));
+        }
     }
 
-    return version;
-}
+  private:
+    const char* label_;
+    std::chrono::steady_clock::time_point start_ = std::chrono::steady_clock::now();
+};
+#define REPORT_FUNC_TIME() TimeReporter reporter(__func__)
+
+struct FileDeleter {
+    FileDeleter(const char* path) : path_(path) {}
+    ~FileDeleter() { adb_unlink(path_); }
+
+  private:
+    const char* const path_;
+};
+
+}  // namespace
 
 int get_device_api_level() {
-    std::vector<char> sdkVersionOutputBuffer;
-    std::vector<char> sdkVersionErrorBuffer;
+    REPORT_FUNC_TIME();
+    std::vector<char> sdk_version_output_buffer;
+    std::vector<char> sdk_version_error_buffer;
     int api_level = -1;
 
-    int statusCode = capture_shell_command("getprop ro.build.version.sdk", &sdkVersionOutputBuffer,
-                                           &sdkVersionErrorBuffer);
-    if (statusCode == 0 && sdkVersionOutputBuffer.size() > 0) {
-        api_level = strtol((char*)sdkVersionOutputBuffer.data(), NULL, 10);
+    int statusCode = capture_shell_command("getprop ro.build.version.sdk",
+                                           &sdk_version_output_buffer, &sdk_version_error_buffer);
+    if (statusCode == 0 && sdk_version_output_buffer.size() > 0) {
+        api_level = strtol((char*)sdk_version_output_buffer.data(), NULL, 10);
     }
 
     return api_level;
 }
 
-void fastdeploy_set_local_agent(bool use_localagent) {
-    g_use_localagent = use_localagent;
+void fastdeploy_set_agent_update_strategy(FastDeploy_AgentUpdateStrategy agent_update_strategy) {
+    g_agent_update_strategy = agent_update_strategy;
 }
 
-static bool deploy_agent(bool checkTimeStamps) {
+static void push_to_device(const void* data, size_t byte_count, const char* dst, bool sync) {
     std::vector<const char*> srcs;
-    // TODO: Deploy agent from bin2c directly instead of writing to disk first.
-    TemporaryFile tempAgent;
-    android::base::WriteFully(tempAgent.fd, kDeployAgent, sizeof(kDeployAgent));
-    srcs.push_back(tempAgent.path);
-    if (!do_sync_push(srcs, kDeviceAgentFile, checkTimeStamps)) {
+    {
+        TemporaryFile temp;
+        android::base::WriteFully(temp.fd, data, byte_count);
+        srcs.push_back(temp.path);
+
+        // On Windows, the file needs to be flushed before pushing to device.
+        // closing the file flushes its content, but we still need to remove it after push.
+        // FileDeleter does exactly that.
+        temp.DoNotRemove();
+    }
+    FileDeleter temp_deleter(srcs.back());
+
+    if (!do_sync_push(srcs, dst, sync)) {
         error_exit("Failed to push fastdeploy agent to device.");
     }
-    srcs.clear();
-    // TODO: Deploy agent from bin2c directly instead of writing to disk first.
-    TemporaryFile tempAgentScript;
-    android::base::WriteFully(tempAgentScript.fd, kDeployAgentScript, sizeof(kDeployAgentScript));
-    srcs.push_back(tempAgentScript.path);
-    if (!do_sync_push(srcs, kDeviceAgentScript, checkTimeStamps)) {
-        error_exit("Failed to push fastdeploy agent script to device.");
-    }
-    srcs.clear();
+}
+
+static bool deploy_agent(bool check_time_stamps) {
+    REPORT_FUNC_TIME();
+
+    push_to_device(kDeployAgent, sizeof(kDeployAgent), kDeviceAgentFile, check_time_stamps);
+    push_to_device(kDeployAgentScript, sizeof(kDeployAgentScript), kDeviceAgentScript,
+                   check_time_stamps);
+
     // on windows the shell script might have lost execute permission
     // so need to set this explicitly
     const char* kChmodCommandPattern = "chmod 777 %s";
-    std::string chmodCommand =
+    std::string chmod_command =
             android::base::StringPrintf(kChmodCommandPattern, kDeviceAgentScript);
-    int ret = send_shell_command(chmodCommand);
+    int ret = send_shell_command(chmod_command);
     if (ret != 0) {
-        error_exit("Error executing %s returncode: %d", chmodCommand.c_str(), ret);
+        error_exit("Error executing %s returncode: %d", chmod_command.c_str(), ret);
     }
 
     return true;
 }
 
-void update_agent(FastDeploy_AgentUpdateStrategy agentUpdateStrategy) {
-    long agent_version = get_agent_version();
-    switch (agentUpdateStrategy) {
-        case FastDeploy_AgentUpdateAlways:
-            deploy_agent(false);
-            break;
-        case FastDeploy_AgentUpdateNewerTimeStamp:
-            deploy_agent(true);
-            break;
-        case FastDeploy_AgentUpdateDifferentVersion:
-            if (agent_version != kRequiredAgentVersion) {
-                if (agent_version < 0) {
-                    printf("Could not detect agent on device, deploying\n");
-                } else {
-                    printf("Device agent version is (%ld), (%ld) is required, re-deploying\n",
-                           agent_version, kRequiredAgentVersion);
-                }
-                deploy_agent(false);
-            }
-            break;
-    }
-
-    agent_version = get_agent_version();
-    if (agent_version != kRequiredAgentVersion) {
-        error_exit("After update agent version remains incorrect! Expected %ld but version is %ld",
-                   kRequiredAgentVersion, agent_version);
-    }
-}
-
 static std::string get_string_from_utf16(const char16_t* input, int input_len) {
     ssize_t utf8_length = utf16_to_utf8_length(input, input_len);
     if (utf8_length <= 0) {
@@ -147,29 +149,29 @@
     return utf8;
 }
 
-static std::string get_packagename_from_apk(const char* apkPath) {
+static std::string get_package_name_from_apk(const char* apk_path) {
 #undef open
-    std::unique_ptr<android::ZipFileRO> zipFile(android::ZipFileRO::open(apkPath));
+    std::unique_ptr<android::ZipFileRO> zip_file((android::ZipFileRO::open)(apk_path));
 #define open ___xxx_unix_open
-    if (zipFile == nullptr) {
-        perror_exit("Could not open %s", apkPath);
+    if (zip_file == nullptr) {
+        perror_exit("Could not open %s", apk_path);
     }
-    android::ZipEntryRO entry = zipFile->findEntryByName("AndroidManifest.xml");
+    android::ZipEntryRO entry = zip_file->findEntryByName("AndroidManifest.xml");
     if (entry == nullptr) {
-        error_exit("Could not find AndroidManifest.xml inside %s", apkPath);
+        error_exit("Could not find AndroidManifest.xml inside %s", apk_path);
     }
     uint32_t manifest_len = 0;
-    if (!zipFile->getEntryInfo(entry, NULL, &manifest_len, NULL, NULL, NULL, NULL)) {
-        error_exit("Could not read AndroidManifest.xml inside %s", apkPath);
+    if (!zip_file->getEntryInfo(entry, NULL, &manifest_len, NULL, NULL, NULL, NULL)) {
+        error_exit("Could not read AndroidManifest.xml inside %s", apk_path);
     }
     std::vector<char> manifest_data(manifest_len);
-    if (!zipFile->uncompressEntry(entry, manifest_data.data(), manifest_len)) {
-        error_exit("Could not uncompress AndroidManifest.xml inside %s", apkPath);
+    if (!zip_file->uncompressEntry(entry, manifest_data.data(), manifest_len)) {
+        error_exit("Could not uncompress AndroidManifest.xml inside %s", apk_path);
     }
     android::ResXMLTree tree;
     android::status_t setto_status = tree.setTo(manifest_data.data(), manifest_len, true);
     if (setto_status != android::OK) {
-        error_exit("Could not parse AndroidManifest.xml inside %s", apkPath);
+        error_exit("Could not parse AndroidManifest.xml inside %s", apk_path);
     }
     android::ResXMLParser::event_code_t code;
     while ((code = tree.next()) != android::ResXMLParser::BAD_DOCUMENT &&
@@ -210,80 +212,97 @@
                 break;
         }
     }
-    error_exit("Could not find package name tag in AndroidManifest.xml inside %s", apkPath);
+    error_exit("Could not find package name tag in AndroidManifest.xml inside %s", apk_path);
 }
 
-void extract_metadata(const char* apkPath, FILE* outputFp) {
-    std::string packageName = get_packagename_from_apk(apkPath);
-    const char* kAgentExtractCommandPattern = "/data/local/tmp/deployagent extract %s";
-    std::string extractCommand =
-            android::base::StringPrintf(kAgentExtractCommandPattern, packageName.c_str());
+static long parse_agent_version(const std::vector<char>& version_buffer) {
+    long version = -1;
+    if (!version_buffer.empty()) {
+        version = strtol((char*)version_buffer.data(), NULL, 16);
+    }
+    return version;
+}
 
-    std::vector<char> extractErrorBuffer;
-    DeployAgentFileCallback cb(outputFp, &extractErrorBuffer);
-    int returnCode = send_shell_command(extractCommand, false, &cb);
+static void update_agent_if_necessary() {
+    switch (g_agent_update_strategy) {
+        case FastDeploy_AgentUpdateAlways:
+            deploy_agent(/*check_time_stamps=*/false);
+            break;
+        case FastDeploy_AgentUpdateNewerTimeStamp:
+            deploy_agent(/*check_time_stamps=*/true);
+            break;
+        default:
+            break;
+    }
+}
+
+std::optional<APKMetaData> extract_metadata(const char* apk_path) {
+    // Update agent if there is a command line argument forcing to do so.
+    update_agent_if_necessary();
+
+    REPORT_FUNC_TIME();
+
+    std::string package_name = get_package_name_from_apk(apk_path);
+
+    // Dump apk command checks the required vs current agent version and if they match then returns
+    // the APK dump for package. Doing this in a single call saves round-trip and agent launch time.
+    constexpr const char* kAgentDumpCommandPattern = "/data/local/tmp/deployagent dump %ld %s";
+    std::string dump_command = android::base::StringPrintf(
+            kAgentDumpCommandPattern, kRequiredAgentVersion, package_name.c_str());
+
+    std::vector<char> dump_out_buffer;
+    std::vector<char> dump_error_buffer;
+    int returnCode =
+            capture_shell_command(dump_command.c_str(), &dump_out_buffer, &dump_error_buffer);
+    if (returnCode >= kInvalidAgentVersion) {
+        // Agent has wrong version or missing.
+        long agent_version = parse_agent_version(dump_out_buffer);
+        if (agent_version < 0) {
+            printf("Could not detect agent on device, deploying\n");
+        } else {
+            printf("Device agent version is (%ld), (%ld) is required, re-deploying\n",
+                   agent_version, kRequiredAgentVersion);
+        }
+        deploy_agent(/*check_time_stamps=*/false);
+
+        // Retry with new agent.
+        dump_out_buffer.clear();
+        dump_error_buffer.clear();
+        returnCode =
+                capture_shell_command(dump_command.c_str(), &dump_out_buffer, &dump_error_buffer);
+    }
     if (returnCode != 0) {
-        fprintf(stderr, "Executing %s returned %d\n", extractCommand.c_str(), returnCode);
-        fprintf(stderr, "%*s\n", int(extractErrorBuffer.size()), extractErrorBuffer.data());
+        if (returnCode == kInvalidAgentVersion) {
+            long agent_version = parse_agent_version(dump_out_buffer);
+            error_exit(
+                    "After update agent version remains incorrect! Expected %ld but version is %ld",
+                    kRequiredAgentVersion, agent_version);
+        }
+        if (returnCode == kPackageMissing) {
+            fprintf(stderr, "Package %s not found, falling back to install\n",
+                    package_name.c_str());
+            return {};
+        }
+        fprintf(stderr, "Executing %s returned %d\n", dump_command.c_str(), returnCode);
+        fprintf(stderr, "%*s\n", int(dump_error_buffer.size()), dump_error_buffer.data());
         error_exit("Aborting");
     }
+
+    com::android::fastdeploy::APKDump dump;
+    if (!dump.ParseFromArray(dump_out_buffer.data(), dump_out_buffer.size())) {
+        fprintf(stderr, "Can't parse output of %s\n", dump_command.c_str());
+        error_exit("Aborting");
+    }
+
+    return PatchUtils::GetDeviceAPKMetaData(dump);
 }
 
-void create_patch(const char* apkPath, const char* metadataPath, const char* patchPath) {
-    DeployPatchGenerator generator(false);
-    unique_fd patchFd(adb_open(patchPath, O_WRONLY | O_CREAT | O_CLOEXEC));
-    if (patchFd < 0) {
-        perror_exit("adb: failed to create %s", patchPath);
-    }
-    bool success = generator.CreatePatch(apkPath, metadataPath, patchFd);
-    if (!success) {
-        error_exit("Failed to create patch for %s", apkPath);
-    }
-}
+unique_fd install_patch(int argc, const char** argv) {
+    REPORT_FUNC_TIME();
+    constexpr char kAgentApplyServicePattern[] = "shell:/data/local/tmp/deployagent apply - -pm %s";
 
-std::string get_patch_path(const char* apkPath) {
-    std::string packageName = get_packagename_from_apk(apkPath);
-    std::string patchDevicePath =
-            android::base::StringPrintf("%s%s.patch", kDeviceAgentPath, packageName.c_str());
-    return patchDevicePath;
-}
-
-void apply_patch_on_device(const char* apkPath, const char* patchPath, const char* outputPath) {
-    const std::string kAgentApplyCommandPattern = "/data/local/tmp/deployagent apply %s %s -o %s";
-    std::string packageName = get_packagename_from_apk(apkPath);
-    std::string patchDevicePath = get_patch_path(apkPath);
-
-    std::vector<const char*> srcs = {patchPath};
-    bool push_ok = do_sync_push(srcs, patchDevicePath.c_str(), false);
-    if (!push_ok) {
-        error_exit("Error pushing %s to %s returned", patchPath, patchDevicePath.c_str());
-    }
-
-    std::string applyPatchCommand =
-            android::base::StringPrintf(kAgentApplyCommandPattern.c_str(), packageName.c_str(),
-                                        patchDevicePath.c_str(), outputPath);
-
-    int returnCode = send_shell_command(applyPatchCommand);
-    if (returnCode != 0) {
-        error_exit("Executing %s returned %d", applyPatchCommand.c_str(), returnCode);
-    }
-}
-
-void install_patch(const char* apkPath, const char* patchPath, int argc, const char** argv) {
-    const std::string kAgentApplyCommandPattern = "/data/local/tmp/deployagent apply %s %s -pm %s";
-    std::string packageName = get_packagename_from_apk(apkPath);
-
-    std::string patchDevicePath =
-            android::base::StringPrintf("%s%s.patch", kDeviceAgentPath, packageName.c_str());
-
-    std::vector<const char*> srcs{patchPath};
-    bool push_ok = do_sync_push(srcs, patchDevicePath.c_str(), false);
-    if (!push_ok) {
-        error_exit("Error pushing %s to %s returned", patchPath, patchDevicePath.c_str());
-    }
-
-    std::vector<unsigned char> applyOutputBuffer;
-    std::vector<unsigned char> applyErrorBuffer;
+    std::vector<unsigned char> apply_output_buffer;
+    std::vector<unsigned char> apply_error_buffer;
     std::string argsString;
 
     bool rSwitchPresent = false;
@@ -298,17 +317,42 @@
         argsString.append("-r");
     }
 
-    std::string applyPatchCommand =
-            android::base::StringPrintf(kAgentApplyCommandPattern.c_str(), packageName.c_str(),
-                                        patchDevicePath.c_str(), argsString.c_str());
-    int returnCode = send_shell_command(applyPatchCommand);
-    if (returnCode != 0) {
-        error_exit("Executing %s returned %d", applyPatchCommand.c_str(), returnCode);
+    std::string error;
+    std::string apply_patch_service_string =
+            android::base::StringPrintf(kAgentApplyServicePattern, argsString.c_str());
+    unique_fd fd{adb_connect(apply_patch_service_string, &error)};
+    if (fd < 0) {
+        error_exit("Executing %s returned %s", apply_patch_service_string.c_str(), error.c_str());
+    }
+    return fd;
+}
+
+unique_fd apply_patch_on_device(const char* output_path) {
+    REPORT_FUNC_TIME();
+    constexpr char kAgentApplyServicePattern[] = "shell:/data/local/tmp/deployagent apply - -o %s";
+
+    std::string error;
+    std::string apply_patch_service_string =
+            android::base::StringPrintf(kAgentApplyServicePattern, output_path);
+    unique_fd fd{adb_connect(apply_patch_service_string, &error)};
+    if (fd < 0) {
+        error_exit("Executing %s returned %s", apply_patch_service_string.c_str(), error.c_str());
+    }
+    return fd;
+}
+
+static void create_patch(const char* apk_path, APKMetaData metadata, borrowed_fd patch_fd) {
+    REPORT_FUNC_TIME();
+    DeployPatchGenerator generator(/*is_verbose=*/false);
+    bool success = generator.CreatePatch(apk_path, std::move(metadata), patch_fd);
+    if (!success) {
+        error_exit("Failed to create patch for %s", apk_path);
     }
 }
 
-bool find_package(const char* apkPath) {
-    const std::string findCommand =
-            "/data/local/tmp/deployagent find " + get_packagename_from_apk(apkPath);
-    return !send_shell_command(findCommand);
+int stream_patch(const char* apk_path, APKMetaData metadata, unique_fd patch_fd) {
+    create_patch(apk_path, std::move(metadata), patch_fd);
+
+    REPORT_FUNC_TIME();
+    return read_and_dump(patch_fd.get());
 }
diff --git a/adb/client/fastdeploy.h b/adb/client/fastdeploy.h
index 7b7f2ec..830aeb2 100644
--- a/adb/client/fastdeploy.h
+++ b/adb/client/fastdeploy.h
@@ -16,6 +16,11 @@
 
 #pragma once
 
+#include "adb_unique_fd.h"
+
+#include "fastdeploy/proto/ApkEntry.pb.h"
+
+#include <optional>
 #include <string>
 
 enum FastDeploy_AgentUpdateStrategy {
@@ -24,12 +29,11 @@
     FastDeploy_AgentUpdateDifferentVersion
 };
 
-void fastdeploy_set_local_agent(bool use_localagent);
+void fastdeploy_set_agent_update_strategy(FastDeploy_AgentUpdateStrategy agent_update_strategy);
 int get_device_api_level();
-void update_agent(FastDeploy_AgentUpdateStrategy agentUpdateStrategy);
-void extract_metadata(const char* apkPath, FILE* outputFp);
-void create_patch(const char* apkPath, const char* metadataPath, const char* patchPath);
-void apply_patch_on_device(const char* apkPath, const char* patchPath, const char* outputPath);
-void install_patch(const char* apkPath, const char* patchPath, int argc, const char** argv);
-std::string get_patch_path(const char* apkPath);
-bool find_package(const char* apkPath);
+
+std::optional<com::android::fastdeploy::APKMetaData> extract_metadata(const char* apk_path);
+unique_fd install_patch(int argc, const char** argv);
+unique_fd apply_patch_on_device(const char* output_path);
+int stream_patch(const char* apk_path, com::android::fastdeploy::APKMetaData metadata,
+                 unique_fd patch_fd);
diff --git a/adb/client/fastdeploycallbacks.cpp b/adb/client/fastdeploycallbacks.cpp
index 23a0aca..86ceaa1 100644
--- a/adb/client/fastdeploycallbacks.cpp
+++ b/adb/client/fastdeploycallbacks.cpp
@@ -49,35 +49,7 @@
 int capture_shell_command(const char* command, std::vector<char>* outBuffer,
                           std::vector<char>* errBuffer) {
     DeployAgentBufferCallback cb(outBuffer, errBuffer);
-    return send_shell_command(command, false, &cb);
-}
-
-DeployAgentFileCallback::DeployAgentFileCallback(FILE* outputFile, std::vector<char>* errBuffer) {
-    mpOutFile = outputFile;
-    mpErrBuffer = errBuffer;
-    mBytesWritten = 0;
-}
-
-void DeployAgentFileCallback::OnStdout(const char* buffer, int length) {
-    if (mpOutFile != NULL) {
-        int bytes_written = fwrite(buffer, 1, length, mpOutFile);
-        if (bytes_written != length) {
-            printf("Write error %d\n", bytes_written);
-        }
-        mBytesWritten += bytes_written;
-    }
-}
-
-void DeployAgentFileCallback::OnStderr(const char* buffer, int length) {
-    appendBuffer(mpErrBuffer, buffer, length);
-}
-
-int DeployAgentFileCallback::Done(int status) {
-    return status;
-}
-
-int DeployAgentFileCallback::getBytesWritten() {
-    return mBytesWritten;
+    return send_shell_command(command, /*disable_shell_protocol=*/false, &cb);
 }
 
 DeployAgentBufferCallback::DeployAgentBufferCallback(std::vector<char>* outBuffer,
diff --git a/adb/client/fastdeploycallbacks.h b/adb/client/fastdeploycallbacks.h
index 7e049c5..4a6fb99 100644
--- a/adb/client/fastdeploycallbacks.h
+++ b/adb/client/fastdeploycallbacks.h
@@ -17,23 +17,6 @@
 #pragma once
 
 #include <vector>
-#include "commandline.h"
-
-class DeployAgentFileCallback : public StandardStreamsCallbackInterface {
-  public:
-    DeployAgentFileCallback(FILE* outputFile, std::vector<char>* errBuffer);
-
-    virtual void OnStdout(const char* buffer, int length);
-    virtual void OnStderr(const char* buffer, int length);
-    virtual int Done(int status);
-
-    int getBytesWritten();
-
-  private:
-    FILE* mpOutFile;
-    std::vector<char>* mpErrBuffer;
-    int mBytesWritten;
-};
 
 int capture_shell_command(const char* command, std::vector<char>* outBuffer,
                           std::vector<char>* errBuffer);
diff --git a/adb/fastdeploy/Android.bp b/adb/fastdeploy/Android.bp
index 95e1a28..245d52a 100644
--- a/adb/fastdeploy/Android.bp
+++ b/adb/fastdeploy/Android.bp
@@ -13,15 +13,76 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 //
-java_binary {
-    name: "deployagent",
+java_library {
+    name: "deployagent_lib",
     sdk_version: "24",
-    srcs: ["deployagent/src/**/*.java", "deploylib/src/**/*.java", "proto/**/*.proto"],
-    static_libs: ["apkzlib_zip"],
+    srcs: [
+        "deployagent/src/**/*.java",
+        "proto/**/*.proto",
+    ],
     proto: {
         type: "lite",
     },
+}
+
+java_binary {
+    name: "deployagent",
+    static_libs: [
+        "deployagent_lib",
+    ],
     dex_preopt: {
         enabled: false,
     }
-}
\ No newline at end of file
+}
+
+android_test {
+    name: "FastDeployTests",
+
+    manifest: "AndroidManifest.xml",
+
+    srcs: [
+        "deployagent/test/com/android/fastdeploy/ApkArchiveTest.java",
+    ],
+
+    static_libs: [
+        "androidx.test.core",
+        "androidx.test.runner",
+        "androidx.test.rules",
+        "deployagent_lib",
+        "mockito-target-inline-minus-junit4",
+    ],
+
+    libs: [
+        "android.test.runner",
+        "android.test.base",
+        "android.test.mock",
+    ],
+
+    data: [
+        "testdata/sample.apk",
+        "testdata/sample.cd",
+    ],
+
+    optimize: {
+        enabled: false,
+    },
+}
+
+java_test_host {
+    name: "FastDeployHostTests",
+    srcs: [
+        "deployagent/test/com/android/fastdeploy/FastDeployTest.java",
+    ],
+    data: [
+        "testdata/helloworld5.apk",
+        "testdata/helloworld7.apk",
+    ],
+    libs: [
+        "compatibility-host-util",
+        "cts-tradefed",
+        "tradefed",
+    ],
+    test_suites: [
+        "general-tests",
+    ],
+}
diff --git a/adb/fastdeploy/AndroidManifest.xml b/adb/fastdeploy/AndroidManifest.xml
new file mode 100644
index 0000000..89dc745
--- /dev/null
+++ b/adb/fastdeploy/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.fastdeploytests">
+
+    <application android:testOnly="true"
+                 android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation
+        android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.fastdeploytests"
+        android:label="FastDeploy Tests" />
+</manifest>
\ No newline at end of file
diff --git a/adb/fastdeploy/AndroidTest.xml b/adb/fastdeploy/AndroidTest.xml
new file mode 100644
index 0000000..24a72bc
--- /dev/null
+++ b/adb/fastdeploy/AndroidTest.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2019 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License
+  -->
+<configuration description="Runs Device Tests for FastDeploy.">
+    <option name="test-suite-tag" value="FastDeployTests"/>
+
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true"/>
+        <option name="install-arg" value="-t"/>
+        <option name="test-file-name" value="FastDeployTests.apk"/>
+    </target_preparer>
+
+    <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer">
+        <option name="cleanup" value="false" />
+        <option name="push-file" key="sample.apk" value="/data/local/tmp/FastDeployTests/sample.apk" />
+        <option name="push-file" key="sample.cd" value="/data/local/tmp/FastDeployTests/sample.cd" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest">
+        <option name="package" value="com.android.fastdeploytests"/>
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner"/>
+    </test>
+
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="FastDeployHostTests.jar" />
+    </test>
+</configuration>
diff --git a/adb/fastdeploy/deployagent/src/com/android/fastdeploy/ApkArchive.java b/adb/fastdeploy/deployagent/src/com/android/fastdeploy/ApkArchive.java
new file mode 100644
index 0000000..31e0502
--- /dev/null
+++ b/adb/fastdeploy/deployagent/src/com/android/fastdeploy/ApkArchive.java
@@ -0,0 +1,193 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.fastdeploy;
+
+import android.util.Log;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+
+/**
+ * Extremely light-weight APK parser class.
+ * Aware of Central Directory, Local File Headers and Signature.
+ * No Zip64 support yet.
+ */
+public final class ApkArchive {
+    private static final String TAG = "ApkArchive";
+
+    // Central Directory constants.
+    private static final int EOCD_SIGNATURE = 0x06054b50;
+    private static final int EOCD_MIN_SIZE = 22;
+    private static final long EOCD_MAX_SIZE = 65_535L + EOCD_MIN_SIZE;
+
+    private static final int CD_ENTRY_HEADER_SIZE_BYTES = 22;
+    private static final int CD_LOCAL_FILE_HEADER_SIZE_OFFSET = 12;
+
+    // Signature constants.
+    private static final int EOSIGNATURE_SIZE = 24;
+
+    public final static class Dump {
+        final byte[] cd;
+        final byte[] signature;
+
+        Dump(byte[] cd, byte[] signature) {
+            this.cd = cd;
+            this.signature = signature;
+        }
+    }
+
+    final static class Location {
+        final long offset;
+        final long size;
+
+        public Location(long offset, long size) {
+            this.offset = offset;
+            this.size = size;
+        }
+    }
+
+    private final RandomAccessFile mFile;
+    private final FileChannel mChannel;
+
+    public ApkArchive(File apk) throws IOException {
+        mFile = new RandomAccessFile(apk, "r");
+        mChannel = mFile.getChannel();
+    }
+
+    /**
+     * Extract the APK metadata: content of Central Directory and Signature.
+     *
+     * @return raw content from APK representing CD and Signature data.
+     */
+    public Dump extractMetadata() throws IOException {
+        Location cdLoc = getCDLocation();
+        byte[] cd = readMetadata(cdLoc);
+
+        byte[] signature = null;
+        Location sigLoc = getSignatureLocation(cdLoc.offset);
+        if (sigLoc != null) {
+            signature = readMetadata(sigLoc);
+            long size = ByteBuffer.wrap(signature).order(ByteOrder.LITTLE_ENDIAN).getLong();
+            if (sigLoc.size != size) {
+                Log.e(TAG, "Mismatching signature sizes: " + sigLoc.size + " != " + size);
+                signature = null;
+            }
+        }
+
+        return new Dump(cd, signature);
+    }
+
+    private long findEndOfCDRecord() throws IOException {
+        final long fileSize = mChannel.size();
+        int sizeToRead = Math.toIntExact(Math.min(fileSize, EOCD_MAX_SIZE));
+        final long readOffset = fileSize - sizeToRead;
+        ByteBuffer buffer = mChannel.map(FileChannel.MapMode.READ_ONLY, readOffset,
+                sizeToRead).order(ByteOrder.LITTLE_ENDIAN);
+
+        buffer.position(sizeToRead - EOCD_MIN_SIZE);
+        while (true) {
+            int signature = buffer.getInt(); // Read 4 bytes.
+            if (signature == EOCD_SIGNATURE) {
+                return readOffset + buffer.position() - 4;
+            }
+            if (buffer.position() == 4) {
+                break;
+            }
+            buffer.position(buffer.position() - Integer.BYTES - 1); // Backtrack 5 bytes.
+        }
+
+        return -1L;
+    }
+
+    private Location findCDRecord(ByteBuffer buf) {
+        if (buf.order() != ByteOrder.LITTLE_ENDIAN) {
+            throw new IllegalArgumentException("ByteBuffer byte order must be little endian");
+        }
+        if (buf.remaining() < CD_ENTRY_HEADER_SIZE_BYTES) {
+            throw new IllegalArgumentException(
+                    "Input too short. Need at least " + CD_ENTRY_HEADER_SIZE_BYTES
+                            + " bytes, available: " + buf.remaining() + "bytes.");
+        }
+
+        int originalPosition = buf.position();
+        int recordSignature = buf.getInt();
+        if (recordSignature != EOCD_SIGNATURE) {
+            throw new IllegalArgumentException(
+                    "Not a Central Directory record. Signature: 0x"
+                            + Long.toHexString(recordSignature & 0xffffffffL));
+        }
+
+        buf.position(originalPosition + CD_LOCAL_FILE_HEADER_SIZE_OFFSET);
+        long size = buf.getInt() & 0xffffffffL;
+        long offset = buf.getInt() & 0xffffffffL;
+        return new Location(offset, size);
+    }
+
+    // Retrieve the location of the Central Directory Record.
+    Location getCDLocation() throws IOException {
+        long eocdRecord = findEndOfCDRecord();
+        if (eocdRecord < 0) {
+            throw new IllegalArgumentException("Unable to find End of Central Directory record.");
+        }
+
+        Location location = findCDRecord(mChannel.map(FileChannel.MapMode.READ_ONLY, eocdRecord,
+                CD_ENTRY_HEADER_SIZE_BYTES).order(ByteOrder.LITTLE_ENDIAN));
+        if (location == null) {
+            throw new IllegalArgumentException("Unable to find Central Directory File Header.");
+        }
+
+        return location;
+    }
+
+    // Retrieve the location of the signature block starting from Central
+    // Directory Record or null if signature is not found.
+    Location getSignatureLocation(long cdRecordOffset) throws IOException {
+        long signatureOffset = cdRecordOffset - EOSIGNATURE_SIZE;
+        if (signatureOffset < 0) {
+            Log.e(TAG, "Unable to find Signature.");
+            return null;
+        }
+
+        ByteBuffer signature = mChannel.map(FileChannel.MapMode.READ_ONLY, signatureOffset,
+                EOSIGNATURE_SIZE).order(ByteOrder.LITTLE_ENDIAN);
+
+        long size = signature.getLong();
+
+        byte[] sign = new byte[16];
+        signature.get(sign);
+        String signAsString = new String(sign);
+        if (!"APK Sig Block 42".equals(signAsString)) {
+            Log.e(TAG, "Signature magic does not match: " + signAsString);
+            return null;
+        }
+
+        long offset = cdRecordOffset - size - 8;
+
+        return new Location(offset, size);
+    }
+
+    private byte[] readMetadata(Location loc) throws IOException {
+        byte[] payload = new byte[(int) loc.size];
+        ByteBuffer buffer = mChannel.map(FileChannel.MapMode.READ_ONLY, loc.offset, loc.size);
+        buffer.get(payload);
+        return payload;
+    }
+}
diff --git a/adb/fastdeploy/deployagent/src/com/android/fastdeploy/DeployAgent.java b/adb/fastdeploy/deployagent/src/com/android/fastdeploy/DeployAgent.java
index a8103c4..3812307 100644
--- a/adb/fastdeploy/deployagent/src/com/android/fastdeploy/DeployAgent.java
+++ b/adb/fastdeploy/deployagent/src/com/android/fastdeploy/DeployAgent.java
@@ -24,18 +24,22 @@
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStream;
-import java.util.concurrent.SynchronousQueue;
-import java.util.concurrent.TimeUnit;
-import java.io.OutputStream;
 import java.io.RandomAccessFile;
-import java.util.Set;
+import java.nio.channels.Channels;
+import java.nio.channels.FileChannel;
+import java.nio.channels.WritableByteChannel;
 
+import com.android.fastdeploy.PatchFormatException;
+import com.android.fastdeploy.ApkArchive;
+import com.android.fastdeploy.APKDump;
 import com.android.fastdeploy.APKMetaData;
 import com.android.fastdeploy.PatchUtils;
 
+import com.google.protobuf.ByteString;
+
 public final class DeployAgent {
     private static final int BUFFER_SIZE = 128 * 1024;
-    private static final int AGENT_VERSION = 0x00000002;
+    private static final int AGENT_VERSION = 0x00000003;
 
     public static void main(String[] args) {
         int exitCode = 0;
@@ -45,68 +49,70 @@
             }
 
             String commandString = args[0];
+            switch (commandString) {
+                case "dump": {
+                    if (args.length != 3) {
+                        showUsage(1);
+                    }
 
-            if (commandString.equals("extract")) {
-                if (args.length != 2) {
-                    showUsage(1);
-                }
-
-                String packageName = args[1];
-                extractMetaData(packageName);
-            } else if (commandString.equals("find")) {
-                if (args.length != 2) {
-                    showUsage(1);
-                }
-
-                String packageName = args[1];
-                if (getFilenameFromPackageName(packageName) == null) {
-                    exitCode = 3;
-                }
-            } else if (commandString.equals("apply")) {
-                if (args.length < 4) {
-                    showUsage(1);
-                }
-
-                String packageName = args[1];
-                String patchPath = args[2];
-                String outputParam = args[3];
-
-                InputStream deltaInputStream = null;
-                if (patchPath.compareTo("-") == 0) {
-                    deltaInputStream = System.in;
-                } else {
-                    deltaInputStream = new FileInputStream(patchPath);
-                }
-
-                if (outputParam.equals("-o")) {
-                    OutputStream outputStream = null;
-                    if (args.length > 4) {
-                        String outputPath = args[4];
-                        if (!outputPath.equals("-")) {
-                            outputStream = new FileOutputStream(outputPath);
+                    String requiredVersion = args[1];
+                    if (AGENT_VERSION == Integer.parseInt(requiredVersion)) {
+                        String packageName = args[2];
+                        String packagePath = getFilenameFromPackageName(packageName);
+                        if (packagePath != null) {
+                            dumpApk(packageName, packagePath);
+                        } else {
+                            exitCode = 3;
                         }
+                    } else {
+                        System.out.printf("0x%08X\n", AGENT_VERSION);
+                        exitCode = 4;
                     }
-                    if (outputStream == null) {
-                        outputStream = System.out;
-                    }
-                    File deviceFile = getFileFromPackageName(packageName);
-                    writePatchToStream(
-                            new RandomAccessFile(deviceFile, "r"), deltaInputStream, outputStream);
-                } else if (outputParam.equals("-pm")) {
-                    String[] sessionArgs = null;
-                    if (args.length > 4) {
-                        int numSessionArgs = args.length-4;
-                        sessionArgs = new String[numSessionArgs];
-                        for (int i=0 ; i<numSessionArgs ; i++) {
-                            sessionArgs[i] = args[i+4];
-                        }
-                    }
-                    exitCode = applyPatch(packageName, deltaInputStream, sessionArgs);
+                    break;
                 }
-            } else if (commandString.equals("version")) {
-                System.out.printf("0x%08X\n", AGENT_VERSION);
-            } else {
-                showUsage(1);
+                case "apply": {
+                    if (args.length < 3) {
+                        showUsage(1);
+                    }
+
+                    String patchPath = args[1];
+                    String outputParam = args[2];
+
+                    InputStream deltaInputStream = null;
+                    if (patchPath.compareTo("-") == 0) {
+                        deltaInputStream = System.in;
+                    } else {
+                        deltaInputStream = new FileInputStream(patchPath);
+                    }
+
+                    if (outputParam.equals("-o")) {
+                        OutputStream outputStream = null;
+                        if (args.length > 3) {
+                            String outputPath = args[3];
+                            if (!outputPath.equals("-")) {
+                                outputStream = new FileOutputStream(outputPath);
+                            }
+                        }
+                        if (outputStream == null) {
+                            outputStream = System.out;
+                        }
+                        writePatchToStream(deltaInputStream, outputStream);
+                    } else if (outputParam.equals("-pm")) {
+                        String[] sessionArgs = null;
+                        if (args.length > 3) {
+                            int numSessionArgs = args.length - 3;
+                            sessionArgs = new String[numSessionArgs];
+                            for (int i = 0; i < numSessionArgs; i++) {
+                                sessionArgs[i] = args[i + 3];
+                            }
+                        }
+                        exitCode = applyPatch(deltaInputStream, sessionArgs);
+                    }
+                    break;
+                }
+                default:
+                    showUsage(1);
+                    break;
             }
         } catch (Exception e) {
             System.err.println("Error: " + e);
@@ -118,16 +124,16 @@
 
     private static void showUsage(int exitCode) {
         System.err.println(
-            "usage: deployagent <command> [<args>]\n\n" +
-            "commands:\n" +
-            "version                             get the version\n" +
-            "find PKGNAME                        return zero if package found, else non-zero\n" +
-            "extract PKGNAME                     extract an installed package's metadata\n" +
-            "apply PKGNAME PATCHFILE [-o|-pm]    apply a patch from PATCHFILE (- for stdin) to an installed package\n" +
-            " -o <FILE> directs output to FILE, default or - for stdout\n" +
-            " -pm <ARGS> directs output to package manager, passes <ARGS> to 'pm install-create'\n"
-            );
-
+                "usage: deployagent <command> [<args>]\n\n" +
+                        "commands:\n" +
+                        "dump VERSION PKGNAME  dump info for an installed package given that " +
+                        "VERSION equals current agent's version\n" +
+                        "apply PATCHFILE [-o|-pm]    apply a patch from PATCHFILE " +
+                        "(- for stdin) to an installed package\n" +
+                        " -o <FILE> directs output to FILE, default or - for stdout\n" +
+                        " -pm <ARGS> directs output to package manager, passes <ARGS> to " +
+                        "'pm install-create'\n"
+        );
         System.exit(exitCode);
     }
 
@@ -162,32 +168,34 @@
                 }
                 int equalsIndex = line.lastIndexOf(packageSuffix);
                 String fileName =
-                    line.substring(packageIndex + packagePrefix.length(), equalsIndex);
+                        line.substring(packageIndex + packagePrefix.length(), equalsIndex);
                 return fileName;
             }
         }
         return null;
     }
 
-    private static File getFileFromPackageName(String packageName) throws IOException {
-        String filename = getFilenameFromPackageName(packageName);
-        if (filename == null) {
-            // Should not happen (function is only called when we know the package exists)
-            throw new IOException("package not found");
-        }
-        return new File(filename);
-    }
+    private static void dumpApk(String packageName, String packagePath) throws IOException {
+        File apk = new File(packagePath);
+        ApkArchive.Dump dump = new ApkArchive(apk).extractMetadata();
 
-    private static void extractMetaData(String packageName) throws IOException {
-        File apkFile = getFileFromPackageName(packageName);
-        APKMetaData apkMetaData = PatchUtils.getAPKMetaData(apkFile);
-        apkMetaData.writeTo(System.out);
+        APKDump.Builder apkDumpBuilder = APKDump.newBuilder();
+        apkDumpBuilder.setName(packageName);
+        if (dump.cd != null) {
+            apkDumpBuilder.setCd(ByteString.copyFrom(dump.cd));
+        }
+        if (dump.signature != null) {
+            apkDumpBuilder.setSignature(ByteString.copyFrom(dump.signature));
+        }
+        apkDumpBuilder.setAbsolutePath(apk.getAbsolutePath());
+
+        apkDumpBuilder.build().writeTo(System.out);
     }
 
     private static int createInstallSession(String[] args) throws IOException {
         StringBuilder commandBuilder = new StringBuilder();
         commandBuilder.append("pm install-create ");
-        for (int i=0 ; args != null && i<args.length ; i++) {
+        for (int i = 0; args != null && i < args.length; i++) {
             commandBuilder.append(args[i] + " ");
         }
 
@@ -199,7 +207,8 @@
         String successLineEnd = "]";
         while ((line = reader.readLine()) != null) {
             if (line.startsWith(successLineStart) && line.endsWith(successLineEnd)) {
-                return Integer.parseInt(line.substring(successLineStart.length(), line.lastIndexOf(successLineEnd)));
+                return Integer.parseInt(line.substring(successLineStart.length(),
+                        line.lastIndexOf(successLineEnd)));
             }
         }
 
@@ -213,16 +222,15 @@
         return p.exitValue();
     }
 
-    private static int applyPatch(String packageName, InputStream deltaStream, String[] sessionArgs)
+    private static int applyPatch(InputStream deltaStream, String[] sessionArgs)
             throws IOException, PatchFormatException {
-        File deviceFile = getFileFromPackageName(packageName);
         int sessionId = createInstallSession(sessionArgs);
         if (sessionId < 0) {
             System.err.println("PM Create Session Failed");
             return -1;
         }
 
-        int writeExitCode = writePatchedDataToSession(new RandomAccessFile(deviceFile, "r"), deltaStream, sessionId);
+        int writeExitCode = writePatchedDataToSession(deltaStream, sessionId);
         if (writeExitCode == 0) {
             return commitInstallSession(sessionId);
         } else {
@@ -230,84 +238,94 @@
         }
     }
 
-    private static long writePatchToStream(RandomAccessFile oldData, InputStream patchData,
-        OutputStream outputStream) throws IOException, PatchFormatException {
+    private static long writePatchToStream(InputStream patchData,
+            OutputStream outputStream) throws IOException, PatchFormatException {
         long newSize = readPatchHeader(patchData);
-        long bytesWritten = writePatchedDataToStream(oldData, newSize, patchData, outputStream);
+        long bytesWritten = writePatchedDataToStream(newSize, patchData, outputStream);
         outputStream.flush();
         if (bytesWritten != newSize) {
             throw new PatchFormatException(String.format(
-                "output size mismatch (expected %ld but wrote %ld)", newSize, bytesWritten));
+                    "output size mismatch (expected %ld but wrote %ld)", newSize, bytesWritten));
         }
         return bytesWritten;
     }
 
     private static long readPatchHeader(InputStream patchData)
-        throws IOException, PatchFormatException {
+            throws IOException, PatchFormatException {
         byte[] signatureBuffer = new byte[PatchUtils.SIGNATURE.length()];
         try {
-            PatchUtils.readFully(patchData, signatureBuffer, 0, signatureBuffer.length);
+            PatchUtils.readFully(patchData, signatureBuffer);
         } catch (IOException e) {
             throw new PatchFormatException("truncated signature");
         }
 
-        String signature = new String(signatureBuffer, 0, signatureBuffer.length, "US-ASCII");
+        String signature = new String(signatureBuffer);
         if (!PatchUtils.SIGNATURE.equals(signature)) {
             throw new PatchFormatException("bad signature");
         }
 
-        long newSize = PatchUtils.readBsdiffLong(patchData);
-        if (newSize < 0 || newSize > Integer.MAX_VALUE) {
-            throw new PatchFormatException("bad newSize");
+        long newSize = PatchUtils.readLELong(patchData);
+        if (newSize < 0) {
+            throw new PatchFormatException("bad newSize: " + newSize);
         }
 
         return newSize;
     }
 
     // Note that this function assumes patchData has been seek'ed to the start of the delta stream
-    // (i.e. the signature has already been read by readPatchHeader). For a stream that points to the
-    // start of a patch file call writePatchToStream
-    private static long writePatchedDataToStream(RandomAccessFile oldData, long newSize,
-        InputStream patchData, OutputStream outputStream) throws IOException {
+    // (i.e. the signature has already been read by readPatchHeader). For a stream that points to
+    // the start of a patch file call writePatchToStream
+    private static long writePatchedDataToStream(long newSize, InputStream patchData,
+            OutputStream outputStream) throws IOException {
+        String deviceFile = PatchUtils.readString(patchData);
+        RandomAccessFile oldDataFile = new RandomAccessFile(deviceFile, "r");
+        FileChannel oldData = oldDataFile.getChannel();
+
+        WritableByteChannel newData = Channels.newChannel(outputStream);
+
         long newDataBytesWritten = 0;
         byte[] buffer = new byte[BUFFER_SIZE];
 
         while (newDataBytesWritten < newSize) {
-            long copyLen = PatchUtils.readFormattedLong(patchData);
-            if (copyLen > 0) {
-                PatchUtils.pipe(patchData, outputStream, buffer, (int) copyLen);
+            long newDataLen = PatchUtils.readLELong(patchData);
+            if (newDataLen > 0) {
+                PatchUtils.pipe(patchData, outputStream, buffer, newDataLen);
             }
 
-            long oldDataOffset = PatchUtils.readFormattedLong(patchData);
-            long oldDataLen = PatchUtils.readFormattedLong(patchData);
-            oldData.seek(oldDataOffset);
-            if (oldDataLen > 0) {
-                PatchUtils.pipe(oldData, outputStream, buffer, (int) oldDataLen);
+            long oldDataOffset = PatchUtils.readLELong(patchData);
+            long oldDataLen = PatchUtils.readLELong(patchData);
+            if (oldDataLen >= 0) {
+                long offset = oldDataOffset;
+                long len = oldDataLen;
+                while (len > 0) {
+                    long chunkLen = Math.min(len, 1024*1024*1024);
+                    oldData.transferTo(offset, chunkLen, newData);
+                    offset += chunkLen;
+                    len -= chunkLen;
+                }
             }
-            newDataBytesWritten += copyLen + oldDataLen;
+            newDataBytesWritten += newDataLen + oldDataLen;
         }
 
         return newDataBytesWritten;
     }
 
-    private static int writePatchedDataToSession(RandomAccessFile oldData, InputStream patchData, int sessionId)
+    private static int writePatchedDataToSession(InputStream patchData, int sessionId)
             throws IOException, PatchFormatException {
         try {
             Process p;
             long newSize = readPatchHeader(patchData);
-            StringBuilder commandBuilder = new StringBuilder();
-            commandBuilder.append(String.format("pm install-write -S %d %d -- -", newSize, sessionId));
-
-            String command = commandBuilder.toString();
+            String command = String.format("pm install-write -S %d %d -- -", newSize, sessionId);
             p = Runtime.getRuntime().exec(command);
 
             OutputStream sessionOutputStream = p.getOutputStream();
-            long bytesWritten = writePatchedDataToStream(oldData, newSize, patchData, sessionOutputStream);
+            long bytesWritten = writePatchedDataToStream(newSize, patchData, sessionOutputStream);
             sessionOutputStream.flush();
             p.waitFor();
             if (bytesWritten != newSize) {
                 throw new PatchFormatException(
-                        String.format("output size mismatch (expected %d but wrote %)", newSize, bytesWritten));
+                        String.format("output size mismatch (expected %d but wrote %)", newSize,
+                                bytesWritten));
             }
             return p.exitValue();
         } catch (InterruptedException e) {
diff --git a/adb/fastdeploy/deploylib/src/com/android/fastdeploy/PatchFormatException.java b/adb/fastdeploy/deployagent/src/com/android/fastdeploy/PatchFormatException.java
similarity index 100%
rename from adb/fastdeploy/deploylib/src/com/android/fastdeploy/PatchFormatException.java
rename to adb/fastdeploy/deployagent/src/com/android/fastdeploy/PatchFormatException.java
diff --git a/adb/fastdeploy/deployagent/src/com/android/fastdeploy/PatchUtils.java b/adb/fastdeploy/deployagent/src/com/android/fastdeploy/PatchUtils.java
new file mode 100644
index 0000000..54be26f
--- /dev/null
+++ b/adb/fastdeploy/deployagent/src/com/android/fastdeploy/PatchUtils.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.fastdeploy;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+class PatchUtils {
+    public static final String SIGNATURE = "FASTDEPLOY";
+
+    /**
+     * Reads a 64-bit signed integer in Little Endian format from the specified {@link
+     * DataInputStream}.
+     *
+     * @param in the stream to read from.
+     */
+    static long readLELong(InputStream in) throws IOException {
+        byte[] buffer = new byte[Long.BYTES];
+        readFully(in, buffer);
+        ByteBuffer buf = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN);
+        return buf.getLong();
+    }
+
+    static String readString(InputStream in) throws IOException {
+        int size = (int) readLELong(in);
+        byte[] buffer = new byte[size];
+        readFully(in, buffer);
+        return new String(buffer);
+    }
+
+    static void readFully(final InputStream in, final byte[] destination, final int startAt,
+            final int numBytes) throws IOException {
+        int numRead = 0;
+        while (numRead < numBytes) {
+            int readNow = in.read(destination, startAt + numRead, numBytes - numRead);
+            if (readNow == -1) {
+                throw new IOException("truncated input stream");
+            }
+            numRead += readNow;
+        }
+    }
+
+    static void readFully(final InputStream in, final byte[] destination) throws IOException {
+        readFully(in, destination, 0, destination.length);
+    }
+
+    static void pipe(final InputStream in, final OutputStream out, final byte[] buffer,
+            long copyLength) throws IOException {
+        while (copyLength > 0) {
+            int maxCopy = (int) Math.min(buffer.length, copyLength);
+            readFully(in, buffer, 0, maxCopy);
+            out.write(buffer, 0, maxCopy);
+            copyLength -= maxCopy;
+        }
+    }
+}
diff --git a/adb/fastdeploy/deployagent/test/com/android/fastdeploy/ApkArchiveTest.java b/adb/fastdeploy/deployagent/test/com/android/fastdeploy/ApkArchiveTest.java
new file mode 100644
index 0000000..7c2468f
--- /dev/null
+++ b/adb/fastdeploy/deployagent/test/com/android/fastdeploy/ApkArchiveTest.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.fastdeploy;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import com.android.fastdeploy.ApkArchive;
+
+import java.io.File;
+import java.io.IOException;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class ApkArchiveTest {
+    private static final File SAMPLE_APK = new File("/data/local/tmp/FastDeployTests/sample.apk");
+    private static final File WRONG_APK = new File("/data/local/tmp/FastDeployTests/sample.cd");
+
+    @Test
+    public void testApkArchiveSizes() throws IOException {
+        ApkArchive archive = new ApkArchive(SAMPLE_APK);
+
+        ApkArchive.Location cdLoc = archive.getCDLocation();
+        assertNotEquals(cdLoc, null);
+        assertEquals(cdLoc.offset, 2044145);
+        assertEquals(cdLoc.size, 49390);
+
+        // Check that block can be retrieved
+        ApkArchive.Location sigLoc = archive.getSignatureLocation(cdLoc.offset);
+        assertNotEquals(sigLoc, null);
+        assertEquals(sigLoc.offset, 2040049);
+        assertEquals(sigLoc.size, 4088);
+    }
+
+    @Test
+    public void testApkArchiveDump() throws IOException {
+        ApkArchive archive = new ApkArchive(SAMPLE_APK);
+
+        ApkArchive.Dump dump = archive.extractMetadata();
+        assertNotEquals(dump, null);
+        assertNotEquals(dump.cd, null);
+        assertNotEquals(dump.signature, null);
+        assertEquals(dump.cd.length, 49390);
+        assertEquals(dump.signature.length, 4088);
+    }
+
+    @Test(expected = IllegalArgumentException.class)
+    public void testApkArchiveDumpWrongApk() throws IOException {
+        ApkArchive archive = new ApkArchive(WRONG_APK);
+
+        archive.extractMetadata();
+    }
+}
diff --git a/adb/fastdeploy/deployagent/test/com/android/fastdeploy/FastDeployTest.java b/adb/fastdeploy/deployagent/test/com/android/fastdeploy/FastDeployTest.java
new file mode 100644
index 0000000..ef6ccae
--- /dev/null
+++ b/adb/fastdeploy/deployagent/test/com/android/fastdeploy/FastDeployTest.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.fastdeploy;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class FastDeployTest extends BaseHostJUnit4Test {
+
+    private static final String TEST_APP_PACKAGE = "com.example.helloworld";
+    private static final String TEST_APK5_NAME = "helloworld5.apk";
+    private static final String TEST_APK7_NAME = "helloworld7.apk";
+
+    private String mTestApk5Path;
+    private String mTestApk7Path;
+
+    @Before
+    public void setUp() throws Exception {
+        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(getBuild());
+        getDevice().uninstallPackage(TEST_APP_PACKAGE);
+        mTestApk5Path = buildHelper.getTestFile(TEST_APK5_NAME).getAbsolutePath();
+        mTestApk7Path = buildHelper.getTestFile(TEST_APK7_NAME).getAbsolutePath();
+    }
+
+    @Test
+    public void testAppInstalls() throws Exception {
+        fastInstallPackage(mTestApk5Path);
+        assertTrue(isAppInstalled(TEST_APP_PACKAGE));
+        getDevice().uninstallPackage(TEST_APP_PACKAGE);
+        assertFalse(isAppInstalled(TEST_APP_PACKAGE));
+    }
+
+    @Test
+    public void testAppPatch() throws Exception {
+        fastInstallPackage(mTestApk5Path);
+        assertTrue(isAppInstalled(TEST_APP_PACKAGE));
+        fastInstallPackage(mTestApk7Path);
+        assertTrue(isAppInstalled(TEST_APP_PACKAGE));
+        getDevice().uninstallPackage(TEST_APP_PACKAGE);
+        assertFalse(isAppInstalled(TEST_APP_PACKAGE));
+    }
+
+    private boolean isAppInstalled(String packageName) throws DeviceNotAvailableException {
+        final String commandResult = getDevice().executeShellCommand("pm list packages");
+        final int prefixLength = "package:".length();
+        return Arrays.stream(commandResult.split("\\r?\\n"))
+                .anyMatch(line -> line.substring(prefixLength).equals(packageName));
+    }
+
+    // Mostly copied from PkgInstallSignatureVerificationTest.java.
+    private String fastInstallPackage(String apkPath)
+            throws IOException, DeviceNotAvailableException {
+        return getDevice().executeAdbCommand("install", "-t", "--fastdeploy", "--force-agent",
+                apkPath);
+    }
+}
+
+
diff --git a/adb/fastdeploy/deploylib/src/com/android/fastdeploy/PatchUtils.java b/adb/fastdeploy/deploylib/src/com/android/fastdeploy/PatchUtils.java
deleted file mode 100644
index c60f9a6..0000000
--- a/adb/fastdeploy/deploylib/src/com/android/fastdeploy/PatchUtils.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.fastdeploy;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.RandomAccessFile;
-import java.util.Arrays;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-
-import com.android.tools.build.apkzlib.zip.ZFile;
-import com.android.tools.build.apkzlib.zip.ZFileOptions;
-import com.android.tools.build.apkzlib.zip.StoredEntry;
-import com.android.tools.build.apkzlib.zip.StoredEntryType;
-import com.android.tools.build.apkzlib.zip.CentralDirectoryHeaderCompressInfo;
-import com.android.tools.build.apkzlib.zip.CentralDirectoryHeader;
-
-import com.android.fastdeploy.APKMetaData;
-import com.android.fastdeploy.APKEntry;
-
-class PatchUtils {
-    private static final long NEGATIVE_MASK = 1L << 63;
-    private static final long NEGATIVE_LONG_SIGN_MASK = 1L << 63;
-    public static final String SIGNATURE = "FASTDEPLOY";
-
-    private static long getOffsetFromEntry(StoredEntry entry) {
-        return entry.getCentralDirectoryHeader().getOffset() + entry.getLocalHeaderSize();
-    }
-
-    public static APKMetaData getAPKMetaData(File apkFile) throws IOException {
-        APKMetaData.Builder apkEntriesBuilder = APKMetaData.newBuilder();
-        ZFileOptions options = new ZFileOptions();
-        ZFile zFile = new ZFile(apkFile, options);
-
-        ArrayList<StoredEntry> metaDataEntries = new ArrayList<StoredEntry>();
-
-        for (StoredEntry entry : zFile.entries()) {
-            if (entry.getType() != StoredEntryType.FILE) {
-                continue;
-            }
-            metaDataEntries.add(entry);
-        }
-
-        Collections.sort(metaDataEntries, new Comparator<StoredEntry>() {
-            private long getOffsetFromEntry(StoredEntry entry) {
-                return PatchUtils.getOffsetFromEntry(entry);
-            }
-
-            @Override
-            public int compare(StoredEntry lhs, StoredEntry rhs) {
-                // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
-                return Long.compare(getOffsetFromEntry(lhs), getOffsetFromEntry(rhs));
-            }
-        });
-
-        for (StoredEntry entry : metaDataEntries) {
-            CentralDirectoryHeader cdh = entry.getCentralDirectoryHeader();
-            CentralDirectoryHeaderCompressInfo cdhci = cdh.getCompressionInfoWithWait();
-
-            APKEntry.Builder entryBuilder = APKEntry.newBuilder();
-            entryBuilder.setCrc32(cdh.getCrc32());
-            entryBuilder.setFileName(cdh.getName());
-            entryBuilder.setCompressedSize(cdhci.getCompressedSize());
-            entryBuilder.setUncompressedSize(cdh.getUncompressedSize());
-            entryBuilder.setDataOffset(getOffsetFromEntry(entry));
-
-            apkEntriesBuilder.addEntries(entryBuilder);
-            apkEntriesBuilder.build();
-        }
-        return apkEntriesBuilder.build();
-    }
-
-    /**
-     * Writes a 64-bit signed integer to the specified {@link OutputStream}. The least significant
-     * byte is written first and the most significant byte is written last.
-     * @param value the value to write
-     * @param outputStream the stream to write to
-     */
-    static void writeFormattedLong(final long value, OutputStream outputStream) throws IOException {
-        long y = value;
-        if (y < 0) {
-            y = (-y) | NEGATIVE_MASK;
-        }
-
-        for (int i = 0; i < 8; ++i) {
-            outputStream.write((byte) (y & 0xff));
-            y >>>= 8;
-        }
-    }
-
-    /**
-     * Reads a 64-bit signed integer written by {@link #writeFormattedLong(long, OutputStream)} from
-     * the specified {@link InputStream}.
-     * @param inputStream the stream to read from
-     */
-    static long readFormattedLong(InputStream inputStream) throws IOException {
-        long result = 0;
-        for (int bitshift = 0; bitshift < 64; bitshift += 8) {
-            result |= ((long) inputStream.read()) << bitshift;
-        }
-
-        if ((result - NEGATIVE_MASK) > 0) {
-            result = (result & ~NEGATIVE_MASK) * -1;
-        }
-        return result;
-    }
-
-    static final long readBsdiffLong(InputStream in) throws PatchFormatException, IOException {
-        long result = 0;
-        for (int bitshift = 0; bitshift < 64; bitshift += 8) {
-            result |= ((long) in.read()) << bitshift;
-        }
-
-        if (result == NEGATIVE_LONG_SIGN_MASK) {
-            // "Negative zero", which is valid in signed-magnitude format.
-            // NB: No sane patch generator should ever produce such a value.
-            throw new PatchFormatException("read negative zero");
-        }
-
-        if ((result & NEGATIVE_LONG_SIGN_MASK) != 0) {
-            result = -(result & ~NEGATIVE_LONG_SIGN_MASK);
-        }
-
-        return result;
-    }
-
-    static void readFully(final InputStream in, final byte[] destination, final int startAt,
-        final int numBytes) throws IOException {
-        int numRead = 0;
-        while (numRead < numBytes) {
-            int readNow = in.read(destination, startAt + numRead, numBytes - numRead);
-            if (readNow == -1) {
-                throw new IOException("truncated input stream");
-            }
-            numRead += readNow;
-        }
-    }
-
-    static void pipe(final InputStream in, final OutputStream out, final byte[] buffer,
-        long copyLength) throws IOException {
-        while (copyLength > 0) {
-            int maxCopy = Math.min(buffer.length, (int) copyLength);
-            readFully(in, buffer, 0, maxCopy);
-            out.write(buffer, 0, maxCopy);
-            copyLength -= maxCopy;
-        }
-    }
-
-    static void pipe(final RandomAccessFile in, final OutputStream out, final byte[] buffer,
-        long copyLength) throws IOException {
-        while (copyLength > 0) {
-            int maxCopy = Math.min(buffer.length, (int) copyLength);
-            in.readFully(buffer, 0, maxCopy);
-            out.write(buffer, 0, maxCopy);
-            copyLength -= maxCopy;
-        }
-    }
-
-    static void fill(byte value, final OutputStream out, final byte[] buffer, long fillLength)
-        throws IOException {
-        while (fillLength > 0) {
-            int maxCopy = Math.min(buffer.length, (int) fillLength);
-            Arrays.fill(buffer, 0, maxCopy, value);
-            out.write(buffer, 0, maxCopy);
-            fillLength -= maxCopy;
-        }
-    }
-}
diff --git a/adb/fastdeploy/deploypatchgenerator/apk_archive.cpp b/adb/fastdeploy/deploypatchgenerator/apk_archive.cpp
new file mode 100644
index 0000000..3dc5e50
--- /dev/null
+++ b/adb/fastdeploy/deploypatchgenerator/apk_archive.cpp
@@ -0,0 +1,415 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+
+#define TRACE_TAG ADB
+
+#include "apk_archive.h"
+
+#include "adb_trace.h"
+#include "sysdeps.h"
+
+#include <android-base/endian.h>
+#include <android-base/mapped_file.h>
+
+#include <openssl/md5.h>
+
+constexpr uint16_t kCompressStored = 0;
+
+// mask value that signifies that the entry has a DD
+static const uint32_t kGPBDDFlagMask = 0x0008;
+
+namespace {
+struct FileRegion {
+    FileRegion(borrowed_fd fd, off64_t offset, size_t length)
+        : mapped_(android::base::MappedFile::FromOsHandle(adb_get_os_handle(fd), offset, length,
+                                                          PROT_READ)) {
+        if (mapped_.data() != nullptr) {
+            return;
+        }
+
+        // Mapped file failed, falling back to pread.
+        buffer_.resize(length);
+        if (auto err = adb_pread(fd.get(), buffer_.data(), length, offset); size_t(err) != length) {
+            fprintf(stderr, "Unable to read %lld bytes at offset %" PRId64 " \n",
+                    static_cast<long long>(length), offset);
+            buffer_.clear();
+            return;
+        }
+    }
+
+    const char* data() const { return mapped_.data() ? mapped_.data() : buffer_.data(); }
+    size_t size() const { return mapped_.data() ? mapped_.size() : buffer_.size(); }
+
+  private:
+    FileRegion() = default;
+    DISALLOW_COPY_AND_ASSIGN(FileRegion);
+
+    android::base::MappedFile mapped_;
+    std::string buffer_;
+};
+}  // namespace
+
+using com::android::fastdeploy::APKDump;
+
+ApkArchive::ApkArchive(const std::string& path) : path_(path), size_(0) {
+    fd_.reset(adb_open(path_.c_str(), O_RDONLY));
+    if (fd_ == -1) {
+        fprintf(stderr, "Unable to open file '%s'\n", path_.c_str());
+        return;
+    }
+
+    struct stat st;
+    if (stat(path_.c_str(), &st) == -1) {
+        fprintf(stderr, "Unable to stat file '%s'\n", path_.c_str());
+        return;
+    }
+    size_ = st.st_size;
+}
+
+ApkArchive::~ApkArchive() {}
+
+APKDump ApkArchive::ExtractMetadata() {
+    D("ExtractMetadata");
+    if (!ready()) {
+        return {};
+    }
+
+    Location cdLoc = GetCDLocation();
+    if (!cdLoc.valid) {
+        return {};
+    }
+
+    APKDump dump;
+    dump.set_absolute_path(path_);
+    dump.set_cd(ReadMetadata(cdLoc));
+
+    Location sigLoc = GetSignatureLocation(cdLoc.offset);
+    if (sigLoc.valid) {
+        dump.set_signature(ReadMetadata(sigLoc));
+    }
+    return dump;
+}
+
+off_t ApkArchive::FindEndOfCDRecord() const {
+    constexpr int endOfCDSignature = 0x06054b50;
+    constexpr off_t endOfCDMinSize = 22;
+    constexpr off_t endOfCDMaxSize = 65535 + endOfCDMinSize;
+
+    auto sizeToRead = std::min(size_, endOfCDMaxSize);
+    auto readOffset = size_ - sizeToRead;
+    FileRegion mapped(fd_, readOffset, sizeToRead);
+
+    // Start scanning from the end
+    auto* start = mapped.data();
+    auto* cursor = start + mapped.size() - sizeof(endOfCDSignature);
+
+    // Search for End of Central Directory record signature.
+    while (cursor >= start) {
+        if (*(int32_t*)cursor == endOfCDSignature) {
+            return readOffset + (cursor - start);
+        }
+        cursor--;
+    }
+    return -1;
+}
+
+ApkArchive::Location ApkArchive::FindCDRecord(const char* cursor) {
+    struct ecdr_t {
+        int32_t signature;
+        uint16_t diskNumber;
+        uint16_t numDisk;
+        uint16_t diskEntries;
+        uint16_t numEntries;
+        uint32_t crSize;
+        uint32_t offsetToCdHeader;
+        uint16_t commentSize;
+        uint8_t comment[0];
+    } __attribute__((packed));
+    ecdr_t* header = (ecdr_t*)cursor;
+
+    Location location;
+    location.offset = header->offsetToCdHeader;
+    location.size = header->crSize;
+    location.valid = true;
+    return location;
+}
+
+ApkArchive::Location ApkArchive::GetCDLocation() {
+    constexpr off_t cdEntryHeaderSizeBytes = 22;
+    Location location;
+
+    // Find End of Central Directory Record
+    off_t eocdRecord = FindEndOfCDRecord();
+    if (eocdRecord < 0) {
+        fprintf(stderr, "Unable to find End of Central Directory record in file '%s'\n",
+                path_.c_str());
+        return location;
+    }
+
+    // Find Central Directory Record
+    FileRegion mapped(fd_, eocdRecord, cdEntryHeaderSizeBytes);
+    location = FindCDRecord(mapped.data());
+    if (!location.valid) {
+        fprintf(stderr, "Unable to find Central Directory File Header in file '%s'\n",
+                path_.c_str());
+        return location;
+    }
+
+    return location;
+}
+
+ApkArchive::Location ApkArchive::GetSignatureLocation(off_t cdRecordOffset) {
+    Location location;
+
+    // Signature constants.
+    constexpr off_t endOfSignatureSize = 24;
+    off_t signatureOffset = cdRecordOffset - endOfSignatureSize;
+    if (signatureOffset < 0) {
+        fprintf(stderr, "Unable to find signature in file '%s'\n", path_.c_str());
+        return location;
+    }
+
+    FileRegion mapped(fd_, signatureOffset, endOfSignatureSize);
+
+    uint64_t signatureSize = *(uint64_t*)mapped.data();
+    auto* signature = mapped.data() + sizeof(signatureSize);
+    // Check if there is a v2/v3 Signature block here.
+    if (memcmp(signature, "APK Sig Block 42", 16)) {
+        return location;
+    }
+
+    // This is likely a signature block.
+    location.size = signatureSize;
+    location.offset = cdRecordOffset - location.size - 8;
+    location.valid = true;
+
+    return location;
+}
+
+std::string ApkArchive::ReadMetadata(Location loc) const {
+    FileRegion mapped(fd_, loc.offset, loc.size);
+    return {mapped.data(), mapped.size()};
+}
+
+size_t ApkArchive::ParseCentralDirectoryRecord(const char* input, size_t size, std::string* md5Hash,
+                                               int64_t* localFileHeaderOffset, int64_t* dataSize) {
+    // A structure representing the fixed length fields for a single
+    // record in the central directory of the archive. In addition to
+    // the fixed length fields listed here, each central directory
+    // record contains a variable length "file_name" and "extra_field"
+    // whose lengths are given by |file_name_length| and |extra_field_length|
+    // respectively.
+    static constexpr int kCDFileHeaderMagic = 0x02014b50;
+    struct CentralDirectoryRecord {
+        // The start of record signature. Must be |kSignature|.
+        uint32_t record_signature;
+        // Source tool version. Top byte gives source OS.
+        uint16_t version_made_by;
+        // Tool version. Ignored by this implementation.
+        uint16_t version_needed;
+        // The "general purpose bit flags" for this entry. The only
+        // flag value that we currently check for is the "data descriptor"
+        // flag.
+        uint16_t gpb_flags;
+        // The compression method for this entry, one of |kCompressStored|
+        // and |kCompressDeflated|.
+        uint16_t compression_method;
+        // The file modification time and date for this entry.
+        uint16_t last_mod_time;
+        uint16_t last_mod_date;
+        // The CRC-32 checksum for this entry.
+        uint32_t crc32;
+        // The compressed size (in bytes) of this entry.
+        uint32_t compressed_size;
+        // The uncompressed size (in bytes) of this entry.
+        uint32_t uncompressed_size;
+        // The length of the entry file name in bytes. The file name
+        // will appear immediately after this record.
+        uint16_t file_name_length;
+        // The length of the extra field info (in bytes). This data
+        // will appear immediately after the entry file name.
+        uint16_t extra_field_length;
+        // The length of the entry comment (in bytes). This data will
+        // appear immediately after the extra field.
+        uint16_t comment_length;
+        // The start disk for this entry. Ignored by this implementation).
+        uint16_t file_start_disk;
+        // File attributes. Ignored by this implementation.
+        uint16_t internal_file_attributes;
+        // File attributes. For archives created on Unix, the top bits are the
+        // mode.
+        uint32_t external_file_attributes;
+        // The offset to the local file header for this entry, from the
+        // beginning of this archive.
+        uint32_t local_file_header_offset;
+
+      private:
+        CentralDirectoryRecord() = default;
+        DISALLOW_COPY_AND_ASSIGN(CentralDirectoryRecord);
+    } __attribute__((packed));
+
+    const CentralDirectoryRecord* cdr;
+    if (size < sizeof(*cdr)) {
+        return 0;
+    }
+
+    auto begin = input;
+    cdr = reinterpret_cast<const CentralDirectoryRecord*>(begin);
+    if (cdr->record_signature != kCDFileHeaderMagic) {
+        fprintf(stderr, "Invalid Central Directory Record signature\n");
+        return 0;
+    }
+    auto end = begin + sizeof(*cdr) + cdr->file_name_length + cdr->extra_field_length +
+               cdr->comment_length;
+
+    uint8_t md5Digest[MD5_DIGEST_LENGTH];
+    MD5((const unsigned char*)begin, end - begin, md5Digest);
+    md5Hash->assign((const char*)md5Digest, sizeof(md5Digest));
+
+    *localFileHeaderOffset = cdr->local_file_header_offset;
+    *dataSize = (cdr->compression_method == kCompressStored) ? cdr->uncompressed_size
+                                                             : cdr->compressed_size;
+
+    return end - begin;
+}
+
+size_t ApkArchive::CalculateLocalFileEntrySize(int64_t localFileHeaderOffset,
+                                               int64_t dataSize) const {
+    // The local file header for a given entry. This duplicates information
+    // present in the central directory of the archive. It is an error for
+    // the information here to be different from the central directory
+    // information for a given entry.
+    static constexpr int kLocalFileHeaderMagic = 0x04034b50;
+    struct LocalFileHeader {
+        // The local file header signature, must be |kSignature|.
+        uint32_t lfh_signature;
+        // Tool version. Ignored by this implementation.
+        uint16_t version_needed;
+        // The "general purpose bit flags" for this entry. The only
+        // flag value that we currently check for is the "data descriptor"
+        // flag.
+        uint16_t gpb_flags;
+        // The compression method for this entry, one of |kCompressStored|
+        // and |kCompressDeflated|.
+        uint16_t compression_method;
+        // The file modification time and date for this entry.
+        uint16_t last_mod_time;
+        uint16_t last_mod_date;
+        // The CRC-32 checksum for this entry.
+        uint32_t crc32;
+        // The compressed size (in bytes) of this entry.
+        uint32_t compressed_size;
+        // The uncompressed size (in bytes) of this entry.
+        uint32_t uncompressed_size;
+        // The length of the entry file name in bytes. The file name
+        // will appear immediately after this record.
+        uint16_t file_name_length;
+        // The length of the extra field info (in bytes). This data
+        // will appear immediately after the entry file name.
+        uint16_t extra_field_length;
+
+      private:
+        LocalFileHeader() = default;
+        DISALLOW_COPY_AND_ASSIGN(LocalFileHeader);
+    } __attribute__((packed));
+    static constexpr int kLocalFileHeaderSize = sizeof(LocalFileHeader);
+    CHECK(ready()) << path_;
+
+    const LocalFileHeader* lfh;
+    if (localFileHeaderOffset + kLocalFileHeaderSize > size_) {
+        fprintf(stderr,
+                "Invalid Local File Header offset in file '%s' at offset %lld, file size %lld\n",
+                path_.c_str(), static_cast<long long>(localFileHeaderOffset),
+                static_cast<long long>(size_));
+        return 0;
+    }
+
+    FileRegion lfhMapped(fd_, localFileHeaderOffset, sizeof(LocalFileHeader));
+    lfh = reinterpret_cast<const LocalFileHeader*>(lfhMapped.data());
+    if (lfh->lfh_signature != kLocalFileHeaderMagic) {
+        fprintf(stderr, "Invalid Local File Header signature in file '%s' at offset %lld\n",
+                path_.c_str(), static_cast<long long>(localFileHeaderOffset));
+        return 0;
+    }
+
+    // The *optional* data descriptor start signature.
+    static constexpr int kOptionalDataDescriptorMagic = 0x08074b50;
+    struct DataDescriptor {
+        // CRC-32 checksum of the entry.
+        uint32_t crc32;
+        // Compressed size of the entry.
+        uint32_t compressed_size;
+        // Uncompressed size of the entry.
+        uint32_t uncompressed_size;
+
+      private:
+        DataDescriptor() = default;
+        DISALLOW_COPY_AND_ASSIGN(DataDescriptor);
+    } __attribute__((packed));
+    static constexpr int kDataDescriptorSize = sizeof(DataDescriptor);
+
+    off_t ddOffset = localFileHeaderOffset + kLocalFileHeaderSize + lfh->file_name_length +
+                     lfh->extra_field_length + dataSize;
+    int64_t ddSize = 0;
+
+    int64_t localDataSize;
+    if (lfh->gpb_flags & kGPBDDFlagMask) {
+        // There is trailing data descriptor.
+        const DataDescriptor* dd;
+
+        if (ddOffset + int(sizeof(uint32_t)) > size_) {
+            fprintf(stderr,
+                    "Error reading trailing data descriptor signature in file '%s' at offset %lld, "
+                    "file size %lld\n",
+                    path_.c_str(), static_cast<long long>(ddOffset), static_cast<long long>(size_));
+            return 0;
+        }
+
+        FileRegion ddMapped(fd_, ddOffset, sizeof(uint32_t) + sizeof(DataDescriptor));
+
+        off_t localDDOffset = 0;
+        if (kOptionalDataDescriptorMagic == *(uint32_t*)ddMapped.data()) {
+            ddOffset += sizeof(uint32_t);
+            localDDOffset += sizeof(uint32_t);
+            ddSize += sizeof(uint32_t);
+        }
+        if (ddOffset + kDataDescriptorSize > size_) {
+            fprintf(stderr,
+                    "Error reading trailing data descriptor in file '%s' at offset %lld, file size "
+                    "%lld\n",
+                    path_.c_str(), static_cast<long long>(ddOffset), static_cast<long long>(size_));
+            return 0;
+        }
+
+        dd = reinterpret_cast<const DataDescriptor*>(ddMapped.data() + localDDOffset);
+        localDataSize = (lfh->compression_method == kCompressStored) ? dd->uncompressed_size
+                                                                     : dd->compressed_size;
+        ddSize += sizeof(*dd);
+    } else {
+        localDataSize = (lfh->compression_method == kCompressStored) ? lfh->uncompressed_size
+                                                                     : lfh->compressed_size;
+    }
+    if (localDataSize != dataSize) {
+        fprintf(stderr,
+                "Data sizes mismatch in file '%s' at offset %lld, CDr: %lld vs LHR/DD: %lld\n",
+                path_.c_str(), static_cast<long long>(localFileHeaderOffset),
+                static_cast<long long>(dataSize), static_cast<long long>(localDataSize));
+        return 0;
+    }
+
+    return kLocalFileHeaderSize + lfh->file_name_length + lfh->extra_field_length + dataSize +
+           ddSize;
+}
diff --git a/adb/fastdeploy/deploypatchgenerator/apk_archive.h b/adb/fastdeploy/deploypatchgenerator/apk_archive.h
new file mode 100644
index 0000000..7127800
--- /dev/null
+++ b/adb/fastdeploy/deploypatchgenerator/apk_archive.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2019 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 <memory>
+#include <string>
+#include <vector>
+
+#include <adb_unique_fd.h>
+
+#include "fastdeploy/proto/ApkEntry.pb.h"
+
+class ApkArchiveTester;
+
+// Manipulates an APK archive. Process it by mmaping it in order to minimize
+// I/Os.
+class ApkArchive {
+  public:
+    friend ApkArchiveTester;
+
+    // A convenience struct to store the result of search operation when
+    // locating the EoCDr, CDr, and Signature Block.
+    struct Location {
+        off_t offset = 0;
+        off_t size = 0;
+        bool valid = false;
+    };
+
+    ApkArchive(const std::string& path);
+    ~ApkArchive();
+
+    com::android::fastdeploy::APKDump ExtractMetadata();
+
+    // Parses the CDr starting from |input| and returns number of bytes consumed.
+    // Extracts local file header offset, data size and calculates MD5 hash of the record.
+    // 0 indicates invalid CDr.
+    static size_t ParseCentralDirectoryRecord(const char* input, size_t size, std::string* md5Hash,
+                                              int64_t* localFileHeaderOffset, int64_t* dataSize);
+    // Calculates Local File Entry size including header using offset and data size from CDr.
+    // 0 indicates invalid Local File Entry.
+    size_t CalculateLocalFileEntrySize(int64_t localFileHeaderOffset, int64_t dataSize) const;
+
+  private:
+    std::string ReadMetadata(Location loc) const;
+
+    // Retrieve the location of the Central Directory Record.
+    Location GetCDLocation();
+
+    // Retrieve the location of the signature block starting from Central
+    // Directory Record
+    Location GetSignatureLocation(off_t cdRecordOffset);
+
+    // Find the End of Central Directory Record, starting from the end of the
+    // file.
+    off_t FindEndOfCDRecord() const;
+
+    // Find Central Directory Record, starting from the end of the file.
+    Location FindCDRecord(const char* cursor);
+
+    // Checks if the archive can be used.
+    bool ready() const { return fd_ >= 0; }
+
+    std::string path_;
+    off_t size_;
+    unique_fd fd_;
+};
diff --git a/adb/fastdeploy/deploypatchgenerator/apk_archive_test.cpp b/adb/fastdeploy/deploypatchgenerator/apk_archive_test.cpp
new file mode 100644
index 0000000..554cb57
--- /dev/null
+++ b/adb/fastdeploy/deploypatchgenerator/apk_archive_test.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2019 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 <iostream>
+
+#include <gtest/gtest.h>
+
+#include "apk_archive.h"
+
+// Friend test to get around private scope of ApkArchive private functions.
+class ApkArchiveTester {
+  public:
+    ApkArchiveTester(const std::string& path) : archive_(path) {}
+
+    bool ready() { return archive_.ready(); }
+
+    auto ExtractMetadata() { return archive_.ExtractMetadata(); }
+
+    ApkArchive::Location GetCDLocation() { return archive_.GetCDLocation(); }
+    ApkArchive::Location GetSignatureLocation(size_t start) {
+        return archive_.GetSignatureLocation(start);
+    }
+
+  private:
+    ApkArchive archive_;
+};
+
+TEST(ApkArchiveTest, TestApkArchiveSizes) {
+    ApkArchiveTester archiveTester("fastdeploy/testdata/sample.apk");
+    EXPECT_TRUE(archiveTester.ready());
+
+    ApkArchive::Location cdLoc = archiveTester.GetCDLocation();
+    EXPECT_TRUE(cdLoc.valid);
+    ASSERT_EQ(cdLoc.offset, 2044145u);
+    ASSERT_EQ(cdLoc.size, 49390u);
+
+    // Check that block can be retrieved
+    ApkArchive::Location sigLoc = archiveTester.GetSignatureLocation(cdLoc.offset);
+    EXPECT_TRUE(sigLoc.valid);
+    ASSERT_EQ(sigLoc.offset, 2040049u);
+    ASSERT_EQ(sigLoc.size, 4088u);
+}
+
+TEST(ApkArchiveTest, TestApkArchiveDump) {
+    ApkArchiveTester archiveTester("fastdeploy/testdata/sample.apk");
+    EXPECT_TRUE(archiveTester.ready());
+
+    auto dump = archiveTester.ExtractMetadata();
+    ASSERT_EQ(dump.cd().size(), 49390u);
+    ASSERT_EQ(dump.signature().size(), 4088u);
+}
+
+TEST(ApkArchiveTest, WrongApk) {
+    ApkArchiveTester archiveTester("fastdeploy/testdata/sample.cd");
+    EXPECT_TRUE(archiveTester.ready());
+
+    auto dump = archiveTester.ExtractMetadata();
+    ASSERT_EQ(dump.cd().size(), 0u);
+    ASSERT_EQ(dump.signature().size(), 0u);
+}
diff --git a/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator.cpp b/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator.cpp
index 154c9b9..8aa7da7 100644
--- a/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator.cpp
+++ b/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator.cpp
@@ -25,8 +25,12 @@
 #include <iostream>
 #include <sstream>
 #include <string>
+#include <unordered_map>
+
+#include <openssl/md5.h>
 
 #include "adb_unique_fd.h"
+#include "adb_utils.h"
 #include "android-base/file.h"
 #include "patch_utils.h"
 #include "sysdeps.h"
@@ -34,9 +38,6 @@
 using namespace com::android::fastdeploy;
 
 void DeployPatchGenerator::Log(const char* fmt, ...) {
-    if (!is_verbose_) {
-        return;
-    }
     va_list ap;
     va_start(ap, fmt);
     vprintf(fmt, ap);
@@ -44,19 +45,34 @@
     va_end(ap);
 }
 
-void DeployPatchGenerator::APKEntryToLog(const APKEntry& entry) {
-    Log("Filename: %s", entry.filename().c_str());
-    Log("CRC32: 0x%08" PRIX64, entry.crc32());
-    Log("Data Offset: %" PRId64, entry.dataoffset());
-    Log("Compressed Size: %" PRId64, entry.compressedsize());
-    Log("Uncompressed Size: %" PRId64, entry.uncompressedsize());
+static std::string HexEncode(const void* in_buffer, unsigned int size) {
+    static const char kHexChars[] = "0123456789ABCDEF";
+
+    // Each input byte creates two output hex characters.
+    std::string out_buffer(size * 2, '\0');
+
+    for (unsigned int i = 0; i < size; ++i) {
+        char byte = ((const uint8_t*)in_buffer)[i];
+        out_buffer[(i << 1)] = kHexChars[(byte >> 4) & 0xf];
+        out_buffer[(i << 1) + 1] = kHexChars[byte & 0xf];
+    }
+    return out_buffer;
 }
 
-void DeployPatchGenerator::APKMetaDataToLog(const char* file, const APKMetaData& metadata) {
+void DeployPatchGenerator::APKEntryToLog(const APKEntry& entry) {
     if (!is_verbose_) {
         return;
     }
-    Log("APK Metadata: %s", file);
+    Log("MD5: %s", HexEncode(entry.md5().data(), entry.md5().size()).c_str());
+    Log("Data Offset: %" PRId64, entry.dataoffset());
+    Log("Data Size: %" PRId64, entry.datasize());
+}
+
+void DeployPatchGenerator::APKMetaDataToLog(const APKMetaData& metadata) {
+    if (!is_verbose_) {
+        return;
+    }
+    Log("APK Metadata: %s", metadata.absolute_path().c_str());
     for (int i = 0; i < metadata.entries_size(); i++) {
         const APKEntry& entry = metadata.entries(i);
         APKEntryToLog(entry);
@@ -65,49 +81,93 @@
 
 void DeployPatchGenerator::ReportSavings(const std::vector<SimpleEntry>& identicalEntries,
                                          uint64_t totalSize) {
-    long totalEqualBytes = 0;
-    int totalEqualFiles = 0;
+    uint64_t totalEqualBytes = 0;
+    uint64_t totalEqualFiles = 0;
     for (size_t i = 0; i < identicalEntries.size(); i++) {
         if (identicalEntries[i].deviceEntry != nullptr) {
-            totalEqualBytes += identicalEntries[i].localEntry->compressedsize();
+            totalEqualBytes += identicalEntries[i].localEntry->datasize();
             totalEqualFiles++;
         }
     }
-    float savingPercent = (totalEqualBytes * 100.0f) / totalSize;
-    fprintf(stderr, "Detected %d equal APK entries\n", totalEqualFiles);
-    fprintf(stderr, "%ld bytes are equal out of %" PRIu64 " (%.2f%%)\n", totalEqualBytes, totalSize,
-            savingPercent);
+    double savingPercent = (totalEqualBytes * 100.0f) / totalSize;
+    fprintf(stderr, "Detected %" PRIu64 " equal APK entries\n", totalEqualFiles);
+    fprintf(stderr, "%" PRIu64 " bytes are equal out of %" PRIu64 " (%.2f%%)\n", totalEqualBytes,
+            totalSize, savingPercent);
+}
+
+struct PatchEntry {
+    int64_t deltaFromDeviceDataStart = 0;
+    int64_t deviceDataOffset = 0;
+    int64_t deviceDataLength = 0;
+};
+static void WritePatchEntry(const PatchEntry& patchEntry, borrowed_fd input, borrowed_fd output,
+                            size_t* realSizeOut) {
+    if (!(patchEntry.deltaFromDeviceDataStart | patchEntry.deviceDataOffset |
+          patchEntry.deviceDataLength)) {
+        return;
+    }
+
+    PatchUtils::WriteLong(patchEntry.deltaFromDeviceDataStart, output);
+    if (patchEntry.deltaFromDeviceDataStart > 0) {
+        PatchUtils::Pipe(input, output, patchEntry.deltaFromDeviceDataStart);
+    }
+    auto hostDataLength = patchEntry.deviceDataLength;
+    adb_lseek(input, hostDataLength, SEEK_CUR);
+
+    PatchUtils::WriteLong(patchEntry.deviceDataOffset, output);
+    PatchUtils::WriteLong(patchEntry.deviceDataLength, output);
+
+    *realSizeOut += patchEntry.deltaFromDeviceDataStart + hostDataLength;
 }
 
 void DeployPatchGenerator::GeneratePatch(const std::vector<SimpleEntry>& entriesToUseOnDevice,
-                                         const char* localApkPath, borrowed_fd output) {
-    unique_fd input(adb_open(localApkPath, O_RDONLY | O_CLOEXEC));
+                                         const std::string& localApkPath,
+                                         const std::string& deviceApkPath, borrowed_fd output) {
+    unique_fd input(adb_open(localApkPath.c_str(), O_RDONLY | O_CLOEXEC));
     size_t newApkSize = adb_lseek(input, 0L, SEEK_END);
     adb_lseek(input, 0L, SEEK_SET);
 
+    // Header.
     PatchUtils::WriteSignature(output);
     PatchUtils::WriteLong(newApkSize, output);
+    PatchUtils::WriteString(deviceApkPath, output);
+
     size_t currentSizeOut = 0;
+    size_t realSizeOut = 0;
     // Write data from the host upto the first entry we have that matches a device entry. Then write
     // the metadata about the device entry and repeat for all entries that match on device. Finally
     // write out any data left. If the device and host APKs are exactly the same this ends up
     // writing out zip metadata from the local APK followed by offsets to the data to use from the
     // device APK.
-    for (auto&& entry : entriesToUseOnDevice) {
-        int64_t deviceDataOffset = entry.deviceEntry->dataoffset();
+    PatchEntry patchEntry;
+    for (size_t i = 0, size = entriesToUseOnDevice.size(); i < size; ++i) {
+        auto&& entry = entriesToUseOnDevice[i];
         int64_t hostDataOffset = entry.localEntry->dataoffset();
-        int64_t deviceDataLength = entry.deviceEntry->compressedsize();
+        int64_t hostDataLength = entry.localEntry->datasize();
+        int64_t deviceDataOffset = entry.deviceEntry->dataoffset();
+        // Both entries are the same, using host data length.
+        int64_t deviceDataLength = hostDataLength;
+
         int64_t deltaFromDeviceDataStart = hostDataOffset - currentSizeOut;
-        PatchUtils::WriteLong(deltaFromDeviceDataStart, output);
         if (deltaFromDeviceDataStart > 0) {
-            PatchUtils::Pipe(input, output, deltaFromDeviceDataStart);
+            WritePatchEntry(patchEntry, input, output, &realSizeOut);
+            patchEntry.deltaFromDeviceDataStart = deltaFromDeviceDataStart;
+            patchEntry.deviceDataOffset = deviceDataOffset;
+            patchEntry.deviceDataLength = deviceDataLength;
+        } else {
+            patchEntry.deviceDataLength += deviceDataLength;
         }
-        PatchUtils::WriteLong(deviceDataOffset, output);
-        PatchUtils::WriteLong(deviceDataLength, output);
-        adb_lseek(input, deviceDataLength, SEEK_CUR);
-        currentSizeOut += deltaFromDeviceDataStart + deviceDataLength;
+
+        currentSizeOut += deltaFromDeviceDataStart + hostDataLength;
     }
-    if (currentSizeOut != newApkSize) {
+    WritePatchEntry(patchEntry, input, output, &realSizeOut);
+    if (realSizeOut != currentSizeOut) {
+        fprintf(stderr, "Size mismatch current %lld vs real %lld\n",
+                static_cast<long long>(currentSizeOut), static_cast<long long>(realSizeOut));
+        error_exit("Aborting");
+    }
+
+    if (newApkSize > currentSizeOut) {
         PatchUtils::WriteLong(newApkSize - currentSizeOut, output);
         PatchUtils::Pipe(input, output, newApkSize - currentSizeOut);
         PatchUtils::WriteLong(0, output);
@@ -115,44 +175,72 @@
     }
 }
 
-bool DeployPatchGenerator::CreatePatch(const char* localApkPath, const char* deviceApkMetadataPath,
-                                       borrowed_fd output) {
-    std::string content;
-    APKMetaData deviceApkMetadata;
-    if (android::base::ReadFileToString(deviceApkMetadataPath, &content)) {
-        deviceApkMetadata.ParsePartialFromString(content);
-    } else {
-        // TODO: What do we want to do if we don't find any metadata.
-        // The current fallback behavior is to build a patch with the contents of |localApkPath|.
-    }
+bool DeployPatchGenerator::CreatePatch(const char* localApkPath, APKMetaData deviceApkMetadata,
+                                       android::base::borrowed_fd output) {
+    return CreatePatch(PatchUtils::GetHostAPKMetaData(localApkPath), std::move(deviceApkMetadata),
+                       output);
+}
 
-    APKMetaData localApkMetadata = PatchUtils::GetAPKMetaData(localApkPath);
-    // Log gathered metadata info.
-    APKMetaDataToLog(deviceApkMetadataPath, deviceApkMetadata);
-    APKMetaDataToLog(localApkPath, localApkMetadata);
+bool DeployPatchGenerator::CreatePatch(APKMetaData localApkMetadata, APKMetaData deviceApkMetadata,
+                                       borrowed_fd output) {
+    // Log metadata info.
+    APKMetaDataToLog(deviceApkMetadata);
+    APKMetaDataToLog(localApkMetadata);
+
+    const std::string localApkPath = localApkMetadata.absolute_path();
+    const std::string deviceApkPath = deviceApkMetadata.absolute_path();
 
     std::vector<SimpleEntry> identicalEntries;
     uint64_t totalSize =
             BuildIdenticalEntries(identicalEntries, localApkMetadata, deviceApkMetadata);
     ReportSavings(identicalEntries, totalSize);
-    GeneratePatch(identicalEntries, localApkPath, output);
+    GeneratePatch(identicalEntries, localApkPath, deviceApkPath, output);
+
     return true;
 }
 
 uint64_t DeployPatchGenerator::BuildIdenticalEntries(std::vector<SimpleEntry>& outIdenticalEntries,
                                                      const APKMetaData& localApkMetadata,
                                                      const APKMetaData& deviceApkMetadata) {
+    outIdenticalEntries.reserve(
+            std::min(localApkMetadata.entries_size(), deviceApkMetadata.entries_size()));
+
+    using md5Digest = std::pair<uint64_t, uint64_t>;
+    struct md5Hash {
+        size_t operator()(const md5Digest& digest) const {
+            std::hash<uint64_t> hasher;
+            size_t seed = 0;
+            seed ^= hasher(digest.first) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
+            seed ^= hasher(digest.second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
+            return seed;
+        }
+    };
+    static_assert(sizeof(md5Digest) == MD5_DIGEST_LENGTH);
+    std::unordered_map<md5Digest, std::vector<const APKEntry*>, md5Hash> deviceEntries;
+    for (const auto& deviceEntry : deviceApkMetadata.entries()) {
+        md5Digest md5;
+        memcpy(&md5, deviceEntry.md5().data(), deviceEntry.md5().size());
+
+        deviceEntries[md5].push_back(&deviceEntry);
+    }
+
     uint64_t totalSize = 0;
-    for (int i = 0; i < localApkMetadata.entries_size(); i++) {
-        const APKEntry& localEntry = localApkMetadata.entries(i);
-        totalSize += localEntry.compressedsize();
-        for (int j = 0; j < deviceApkMetadata.entries_size(); j++) {
-            const APKEntry& deviceEntry = deviceApkMetadata.entries(j);
-            if (deviceEntry.crc32() == localEntry.crc32() &&
-                deviceEntry.filename().compare(localEntry.filename()) == 0) {
+    for (const auto& localEntry : localApkMetadata.entries()) {
+        totalSize += localEntry.datasize();
+
+        md5Digest md5;
+        memcpy(&md5, localEntry.md5().data(), localEntry.md5().size());
+
+        auto deviceEntriesIt = deviceEntries.find(md5);
+        if (deviceEntriesIt == deviceEntries.end()) {
+            continue;
+        }
+
+        for (const auto* deviceEntry : deviceEntriesIt->second) {
+            if (deviceEntry->md5() == localEntry.md5()) {
                 SimpleEntry simpleEntry;
-                simpleEntry.localEntry = const_cast<APKEntry*>(&localEntry);
-                simpleEntry.deviceEntry = const_cast<APKEntry*>(&deviceEntry);
+                simpleEntry.localEntry = &localEntry;
+                simpleEntry.deviceEntry = deviceEntry;
                 APKEntryToLog(localEntry);
                 outIdenticalEntries.push_back(simpleEntry);
                 break;
diff --git a/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator.h b/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator.h
index 30e41a5..fd7eaee 100644
--- a/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator.h
+++ b/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator.h
@@ -27,12 +27,15 @@
  */
 class DeployPatchGenerator {
   public:
+    using APKEntry = com::android::fastdeploy::APKEntry;
+    using APKMetaData = com::android::fastdeploy::APKMetaData;
+
     /**
      * Simple struct to hold mapping between local metadata and device metadata.
      */
     struct SimpleEntry {
-        com::android::fastdeploy::APKEntry* localEntry;
-        com::android::fastdeploy::APKEntry* deviceEntry;
+        const APKEntry* localEntry;
+        const APKEntry* deviceEntry;
     };
 
     /**
@@ -41,10 +44,10 @@
      */
     explicit DeployPatchGenerator(bool is_verbose) : is_verbose_(is_verbose) {}
     /**
-     * Given a |localApkPath|, and the |deviceApkMetadataPath| from an installed APK this function
+     * Given a |localApkPath|, and the |deviceApkMetadata| from an installed APK this function
      * writes a patch to the given |output|.
      */
-    bool CreatePatch(const char* localApkPath, const char* deviceApkMetadataPath,
+    bool CreatePatch(const char* localApkPath, APKMetaData deviceApkMetadata,
                      android::base::borrowed_fd output);
 
   private:
@@ -57,14 +60,20 @@
 
     /**
      * Helper function to log the APKMetaData structure. If |is_verbose_| is false this function
-     * early outs. |file| is the path to the file represented by |metadata|. This function is used
-     * for debugging / information.
+     * early outs. This function is used for debugging / information.
      */
-    void APKMetaDataToLog(const char* file, const com::android::fastdeploy::APKMetaData& metadata);
+    void APKMetaDataToLog(const APKMetaData& metadata);
     /**
      * Helper function to log APKEntry.
      */
-    void APKEntryToLog(const com::android::fastdeploy::APKEntry& entry);
+    void APKEntryToLog(const APKEntry& entry);
+
+    /**
+     * Given the |localApkMetadata| metadata, and the |deviceApkMetadata| from an installed APK this
+     * function writes a patch to the given |output|.
+     */
+    bool CreatePatch(APKMetaData localApkMetadata, APKMetaData deviceApkMetadata,
+                     android::base::borrowed_fd output);
 
     /**
      * Helper function to report savings by fastdeploy. This function prints out savings even with
@@ -92,11 +101,11 @@
      * highest.
      */
     void GeneratePatch(const std::vector<SimpleEntry>& entriesToUseOnDevice,
-                       const char* localApkPath, android::base::borrowed_fd output);
+                       const std::string& localApkPath, const std::string& deviceApkPath,
+                       android::base::borrowed_fd output);
 
   protected:
-    uint64_t BuildIdenticalEntries(
-            std::vector<SimpleEntry>& outIdenticalEntries,
-            const com::android::fastdeploy::APKMetaData& localApkMetadata,
-            const com::android::fastdeploy::APKMetaData& deviceApkMetadataPath);
-};
\ No newline at end of file
+    uint64_t BuildIdenticalEntries(std::vector<SimpleEntry>& outIdenticalEntries,
+                                   const APKMetaData& localApkMetadata,
+                                   const APKMetaData& deviceApkMetadata);
+};
diff --git a/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator_test.cpp b/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator_test.cpp
index 9cdc44e..e4c96ea 100644
--- a/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator_test.cpp
+++ b/adb/fastdeploy/deploypatchgenerator/deploy_patch_generator_test.cpp
@@ -15,6 +15,7 @@
  */
 
 #include "deploy_patch_generator.h"
+#include "apk_archive.h"
 #include "patch_utils.h"
 
 #include <android-base/file.h>
@@ -31,21 +32,17 @@
     return "fastdeploy/testdata/" + name;
 }
 
-class TestPatchGenerator : DeployPatchGenerator {
-  public:
-    TestPatchGenerator() : DeployPatchGenerator(false) {}
-    void GatherIdenticalEntries(std::vector<DeployPatchGenerator::SimpleEntry>& outIdenticalEntries,
-                                const APKMetaData& metadataA, const APKMetaData& metadataB) {
-        BuildIdenticalEntries(outIdenticalEntries, metadataA, metadataB);
-    }
+struct TestPatchGenerator : DeployPatchGenerator {
+    using DeployPatchGenerator::BuildIdenticalEntries;
+    using DeployPatchGenerator::DeployPatchGenerator;
 };
 
 TEST(DeployPatchGeneratorTest, IdenticalFileEntries) {
     std::string apkPath = GetTestFile("rotating_cube-release.apk");
-    APKMetaData metadataA = PatchUtils::GetAPKMetaData(apkPath.c_str());
-    TestPatchGenerator generator;
+    APKMetaData metadataA = PatchUtils::GetHostAPKMetaData(apkPath.c_str());
+    TestPatchGenerator generator(false);
     std::vector<DeployPatchGenerator::SimpleEntry> entries;
-    generator.GatherIdenticalEntries(entries, metadataA, metadataA);
+    generator.BuildIdenticalEntries(entries, metadataA, metadataA);
     // Expect the entry count to match the number of entries in the metadata.
     const uint32_t identicalCount = entries.size();
     const uint32_t entriesCount = metadataA.entries_size();
@@ -64,9 +61,28 @@
     // Create a patch that is 100% different.
     TemporaryFile output;
     DeployPatchGenerator generator(true);
-    generator.CreatePatch(apkPath.c_str(), "", output.fd);
+    generator.CreatePatch(apkPath.c_str(), {}, output.fd);
 
     // Expect a patch file that has a size at least the size of our initial APK.
     long patchSize = adb_lseek(output.fd, 0L, SEEK_END);
     EXPECT_GT(patchSize, apkSize);
-}
\ No newline at end of file
+}
+
+TEST(DeployPatchGeneratorTest, ZeroSizePatch) {
+    std::string apkPath = GetTestFile("rotating_cube-release.apk");
+    ApkArchive archive(apkPath);
+    auto dump = archive.ExtractMetadata();
+    EXPECT_NE(dump.cd().size(), 0u);
+
+    APKMetaData metadata = PatchUtils::GetDeviceAPKMetaData(dump);
+
+    // Create a patch that is 100% the same.
+    TemporaryFile output;
+    output.DoNotRemove();
+    DeployPatchGenerator generator(true);
+    generator.CreatePatch(apkPath.c_str(), metadata, output.fd);
+
+    // Expect a patch file that is smaller than 0.5K.
+    int64_t patchSize = adb_lseek(output.fd, 0L, SEEK_END);
+    EXPECT_LE(patchSize, 512);
+}
diff --git a/adb/fastdeploy/deploypatchgenerator/patch_utils.cpp b/adb/fastdeploy/deploypatchgenerator/patch_utils.cpp
index f11ddd1..2b00c80 100644
--- a/adb/fastdeploy/deploypatchgenerator/patch_utils.cpp
+++ b/adb/fastdeploy/deploypatchgenerator/patch_utils.cpp
@@ -16,72 +16,94 @@
 
 #include "patch_utils.h"
 
-#include <androidfw/ZipFileRO.h>
 #include <stdio.h>
 
 #include "adb_io.h"
+#include "adb_utils.h"
 #include "android-base/endian.h"
 #include "sysdeps.h"
 
+#include "apk_archive.h"
+
 using namespace com::android;
 using namespace com::android::fastdeploy;
 using namespace android::base;
 
 static constexpr char kSignature[] = "FASTDEPLOY";
 
-APKMetaData PatchUtils::GetAPKMetaData(const char* apkPath) {
+APKMetaData PatchUtils::GetDeviceAPKMetaData(const APKDump& apk_dump) {
     APKMetaData apkMetaData;
-#undef open
-    std::unique_ptr<android::ZipFileRO> zipFile(android::ZipFileRO::open(apkPath));
-#define open ___xxx_unix_open
-    if (zipFile == nullptr) {
-        printf("Could not open %s", apkPath);
-        exit(1);
-    }
-    void* cookie;
-    if (zipFile->startIteration(&cookie)) {
-        android::ZipEntryRO entry;
-        while ((entry = zipFile->nextEntry(cookie)) != NULL) {
-            char fileName[256];
-            // Make sure we have a file name.
-            // TODO: Handle filenames longer than 256.
-            if (zipFile->getEntryFileName(entry, fileName, sizeof(fileName))) {
-                continue;
-            }
+    apkMetaData.set_absolute_path(apk_dump.absolute_path());
 
-            uint32_t uncompressedSize, compressedSize, crc32;
-            int64_t dataOffset;
-            zipFile->getEntryInfo(entry, nullptr, &uncompressedSize, &compressedSize, &dataOffset,
-                                  nullptr, &crc32);
-            APKEntry* apkEntry = apkMetaData.add_entries();
-            apkEntry->set_crc32(crc32);
-            apkEntry->set_filename(fileName);
-            apkEntry->set_compressedsize(compressedSize);
-            apkEntry->set_uncompressedsize(uncompressedSize);
-            apkEntry->set_dataoffset(dataOffset);
-        }
+    std::string md5Hash;
+    int64_t localFileHeaderOffset;
+    int64_t dataSize;
+
+    const auto& cd = apk_dump.cd();
+    auto cur = cd.data();
+    int64_t size = cd.size();
+    while (auto consumed = ApkArchive::ParseCentralDirectoryRecord(
+                   cur, size, &md5Hash, &localFileHeaderOffset, &dataSize)) {
+        cur += consumed;
+        size -= consumed;
+
+        auto apkEntry = apkMetaData.add_entries();
+        apkEntry->set_md5(md5Hash);
+        apkEntry->set_dataoffset(localFileHeaderOffset);
+        apkEntry->set_datasize(dataSize);
     }
     return apkMetaData;
 }
 
+APKMetaData PatchUtils::GetHostAPKMetaData(const char* apkPath) {
+    ApkArchive archive(apkPath);
+    auto dump = archive.ExtractMetadata();
+    if (dump.cd().empty()) {
+        fprintf(stderr, "adb: Could not extract Central Directory from %s\n", apkPath);
+        error_exit("Aborting");
+    }
+
+    auto apkMetaData = GetDeviceAPKMetaData(dump);
+
+    // Now let's set data sizes.
+    for (auto& apkEntry : *apkMetaData.mutable_entries()) {
+        auto dataSize =
+                archive.CalculateLocalFileEntrySize(apkEntry.dataoffset(), apkEntry.datasize());
+        if (dataSize == 0) {
+            error_exit("Aborting");
+        }
+        apkEntry.set_datasize(dataSize);
+    }
+
+    return apkMetaData;
+}
+
 void PatchUtils::WriteSignature(borrowed_fd output) {
     WriteFdExactly(output, kSignature, sizeof(kSignature) - 1);
 }
 
 void PatchUtils::WriteLong(int64_t value, borrowed_fd output) {
-    int64_t toLittleEndian = htole64(value);
-    WriteFdExactly(output, &toLittleEndian, sizeof(int64_t));
+    int64_t littleEndian = htole64(value);
+    WriteFdExactly(output, &littleEndian, sizeof(littleEndian));
+}
+
+void PatchUtils::WriteString(const std::string& value, android::base::borrowed_fd output) {
+    WriteLong(value.size(), output);
+    WriteFdExactly(output, value);
 }
 
 void PatchUtils::Pipe(borrowed_fd input, borrowed_fd output, size_t amount) {
-    constexpr static int BUFFER_SIZE = 128 * 1024;
+    constexpr static size_t BUFFER_SIZE = 128 * 1024;
     char buffer[BUFFER_SIZE];
     size_t transferAmount = 0;
     while (transferAmount != amount) {
-        long chunkAmount =
-                amount - transferAmount > BUFFER_SIZE ? BUFFER_SIZE : amount - transferAmount;
-        long readAmount = adb_read(input, buffer, chunkAmount);
+        auto chunkAmount = std::min(amount - transferAmount, BUFFER_SIZE);
+        auto readAmount = adb_read(input, buffer, chunkAmount);
+        if (readAmount < 0) {
+            fprintf(stderr, "adb: failed to read from input: %s\n", strerror(errno));
+            error_exit("Aborting");
+        }
         WriteFdExactly(output, buffer, readAmount);
         transferAmount += readAmount;
     }
-}
\ No newline at end of file
+}
diff --git a/adb/fastdeploy/deploypatchgenerator/patch_utils.h b/adb/fastdeploy/deploypatchgenerator/patch_utils.h
index 0ebfe8f..8dc9b9c 100644
--- a/adb/fastdeploy/deploypatchgenerator/patch_utils.h
+++ b/adb/fastdeploy/deploypatchgenerator/patch_utils.h
@@ -25,11 +25,18 @@
 class PatchUtils {
   public:
     /**
+     * This function takes the dump of Central Directly and builds the APKMetaData required by the
+     * patching algorithm. The if this function has an error a string is printed to the terminal and
+     * exit(1) is called.
+     */
+    static com::android::fastdeploy::APKMetaData GetDeviceAPKMetaData(
+            const com::android::fastdeploy::APKDump& apk_dump);
+    /**
      * This function takes a local APK file and builds the APKMetaData required by the patching
      * algorithm. The if this function has an error a string is printed to the terminal and exit(1)
      * is called.
      */
-    static com::android::fastdeploy::APKMetaData GetAPKMetaData(const char* file);
+    static com::android::fastdeploy::APKMetaData GetHostAPKMetaData(const char* file);
     /**
      * Writes a fixed signature string to the header of the patch.
      */
@@ -39,8 +46,12 @@
      */
     static void WriteLong(int64_t value, android::base::borrowed_fd output);
     /**
+     * Writes string to the |output|.
+     */
+    static void WriteString(const std::string& value, android::base::borrowed_fd output);
+    /**
      * Copy |amount| of data from |input| to |output|.
      */
     static void Pipe(android::base::borrowed_fd input, android::base::borrowed_fd output,
                      size_t amount);
-};
\ No newline at end of file
+};
diff --git a/adb/fastdeploy/deploypatchgenerator/patch_utils_test.cpp b/adb/fastdeploy/deploypatchgenerator/patch_utils_test.cpp
index a7eeebf..3ec5ab3 100644
--- a/adb/fastdeploy/deploypatchgenerator/patch_utils_test.cpp
+++ b/adb/fastdeploy/deploypatchgenerator/patch_utils_test.cpp
@@ -23,10 +23,13 @@
 #include <sstream>
 #include <string>
 
+#include <google/protobuf/util/message_differencer.h>
+
 #include "adb_io.h"
 #include "sysdeps.h"
 
 using namespace com::android::fastdeploy;
+using google::protobuf::util::MessageDifferencer;
 
 static std::string GetTestFile(const std::string& name) {
     return "fastdeploy/testdata/" + name;
@@ -86,11 +89,56 @@
 
 TEST(PatchUtilsTest, GatherMetadata) {
     std::string apkFile = GetTestFile("rotating_cube-release.apk");
-    APKMetaData metadata = PatchUtils::GetAPKMetaData(apkFile.c_str());
+    APKMetaData actual = PatchUtils::GetHostAPKMetaData(apkFile.c_str());
+
     std::string expectedMetadata;
     android::base::ReadFileToString(GetTestFile("rotating_cube-metadata-release.data"),
                                     &expectedMetadata);
+    APKMetaData expected;
+    EXPECT_TRUE(expected.ParseFromString(expectedMetadata));
+
+    // Test paths might vary.
+    expected.set_absolute_path(actual.absolute_path());
+
     std::string actualMetadata;
-    metadata.SerializeToString(&actualMetadata);
+    actual.SerializeToString(&actualMetadata);
+
+    expected.SerializeToString(&expectedMetadata);
+
     EXPECT_EQ(expectedMetadata, actualMetadata);
-}
\ No newline at end of file
+}
+
+static inline void sanitize(APKMetaData& metadata) {
+    metadata.clear_absolute_path();
+    for (auto&& entry : *metadata.mutable_entries()) {
+        entry.clear_datasize();
+    }
+}
+
+TEST(PatchUtilsTest, GatherDumpMetadata) {
+    APKMetaData hostMetadata;
+    APKMetaData deviceMetadata;
+
+    hostMetadata = PatchUtils::GetHostAPKMetaData(GetTestFile("sample.apk").c_str());
+
+    {
+        std::string cd;
+        android::base::ReadFileToString(GetTestFile("sample.cd"), &cd);
+
+        APKDump dump;
+        dump.set_cd(std::move(cd));
+
+        deviceMetadata = PatchUtils::GetDeviceAPKMetaData(dump);
+    }
+
+    sanitize(hostMetadata);
+    sanitize(deviceMetadata);
+
+    std::string expectedMetadata;
+    hostMetadata.SerializeToString(&expectedMetadata);
+
+    std::string actualMetadata;
+    deviceMetadata.SerializeToString(&actualMetadata);
+
+    EXPECT_EQ(expectedMetadata, actualMetadata);
+}
diff --git a/adb/fastdeploy/proto/ApkEntry.proto b/adb/fastdeploy/proto/ApkEntry.proto
index 9460d15..d84c5a5 100644
--- a/adb/fastdeploy/proto/ApkEntry.proto
+++ b/adb/fastdeploy/proto/ApkEntry.proto
@@ -1,18 +1,26 @@
-syntax = "proto2";
+syntax = "proto3";
 
 package com.android.fastdeploy;
 
 option java_package = "com.android.fastdeploy";
+option java_outer_classname = "ApkEntryProto";
 option java_multiple_files = true;
+option optimize_for = LITE_RUNTIME;
+
+message APKDump {
+    string name = 1;
+    bytes cd = 2;
+    bytes signature = 3;
+    string absolute_path = 4;
+}
 
 message APKEntry {
-    required int64 crc32 = 1;
-    required string fileName = 2;
-    required int64 dataOffset = 3;
-    required int64 compressedSize = 4;
-    required int64 uncompressedSize = 5;
+    bytes md5 = 1;
+    int64 dataOffset = 2;
+    int64 dataSize = 3;
 }
 
 message APKMetaData {
-    repeated APKEntry entries = 1;
+    string absolute_path = 1;
+    repeated APKEntry entries = 2;
 }
diff --git a/adb/fastdeploy/testdata/helloworld5.apk b/adb/fastdeploy/testdata/helloworld5.apk
new file mode 100644
index 0000000..4a1539e
--- /dev/null
+++ b/adb/fastdeploy/testdata/helloworld5.apk
Binary files differ
diff --git a/adb/fastdeploy/testdata/helloworld7.apk b/adb/fastdeploy/testdata/helloworld7.apk
new file mode 100644
index 0000000..82c46df
--- /dev/null
+++ b/adb/fastdeploy/testdata/helloworld7.apk
Binary files differ
diff --git a/adb/fastdeploy/testdata/rotating_cube-metadata-release.data b/adb/fastdeploy/testdata/rotating_cube-metadata-release.data
index 0671bf3..52352ff 100644
--- a/adb/fastdeploy/testdata/rotating_cube-metadata-release.data
+++ b/adb/fastdeploy/testdata/rotating_cube-metadata-release.data
Binary files differ
diff --git a/adb/fastdeploy/testdata/sample.apk b/adb/fastdeploy/testdata/sample.apk
new file mode 100644
index 0000000..c316205
--- /dev/null
+++ b/adb/fastdeploy/testdata/sample.apk
Binary files differ
diff --git a/adb/fastdeploy/testdata/sample.cd b/adb/fastdeploy/testdata/sample.cd
new file mode 100644
index 0000000..5e5b4d4
--- /dev/null
+++ b/adb/fastdeploy/testdata/sample.cd
Binary files differ
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index 987f994..466c2ce 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -601,6 +601,10 @@
     return path[0] == '/';
 }
 
+static __inline__ int adb_get_os_handle(borrowed_fd fd) {
+    return fd.get();
+}
+
 #endif /* !_WIN32 */
 
 static inline void disable_tcp_nagle(borrowed_fd fd) {
diff --git a/base/file.cpp b/base/file.cpp
index b1ddc5d..6321fc6 100644
--- a/base/file.cpp
+++ b/base/file.cpp
@@ -53,34 +53,47 @@
 
 #ifdef _WIN32
 static int mkstemp(char* name_template, size_t size_in_chars) {
-  auto path = name_template;
-  if (_mktemp_s(path, size_in_chars) != 0) {
+  std::wstring path;
+  CHECK(android::base::UTF8ToWide(name_template, &path))
+      << "path can't be converted to wchar: " << name_template;
+  if (_wmktemp_s(path.data(), path.size() + 1) != 0) {
     return -1;
   }
 
-  std::wstring path_wide;
-  CHECK(android::base::UTF8ToWide(path, &path_wide))
-      << "path can't be converted to wchar: " << path;
-
   // Use open() to match the close() that TemporaryFile's destructor does.
   // Use O_BINARY to match base file APIs.
-  return _wopen(path_wide.c_str(), O_CREAT | O_EXCL | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR);
+  int fd = _wopen(path.c_str(), O_CREAT | O_EXCL | O_RDWR | O_BINARY, S_IRUSR | S_IWUSR);
+  if (fd < 0) {
+    return -1;
+  }
+
+  std::string path_utf8;
+  CHECK(android::base::WideToUTF8(path, &path_utf8)) << "path can't be converted to utf8";
+  CHECK(strcpy_s(name_template, size_in_chars, path_utf8.c_str()) == 0)
+      << "utf8 path can't be assigned back to name_template";
+
+  return fd;
 }
 
 static char* mkdtemp(char* name_template, size_t size_in_chars) {
-  auto path = name_template;
-  if (_mktemp_s(path, size_in_chars) != 0) {
+  std::wstring path;
+  CHECK(android::base::UTF8ToWide(name_template, &path))
+      << "path can't be converted to wchar: " << name_template;
+
+  if (_wmktemp_s(path.data(), path.size() + 1) != 0) {
     return nullptr;
   }
 
-  std::wstring path_wide;
-  CHECK(android::base::UTF8ToWide(path, &path_wide))
-      << "path can't be converted to wchar: " << path;
-
-  if (_wmkdir(path_wide.c_str()) != 0) {
+  if (_wmkdir(path.c_str()) != 0) {
     return nullptr;
   }
-  return path;
+
+  std::string path_utf8;
+  CHECK(android::base::WideToUTF8(path, &path_utf8)) << "path can't be converted to utf8";
+  CHECK(strcpy_s(name_template, size_in_chars, path_utf8.c_str()) == 0)
+      << "utf8 path can't be assigned back to name_template";
+
+  return name_template;
 }
 #endif
 
diff --git a/base/file_test.cpp b/base/file_test.cpp
index 65ee235..120228d 100644
--- a/base/file_test.cpp
+++ b/base/file_test.cpp
@@ -30,7 +30,7 @@
 #if !defined(_WIN32)
 #include <pwd.h>
 #else
-#include <processenv.h>
+#include <windows.h>
 #endif
 
 #include "android-base/logging.h"  // and must be after windows.h for ERROR
@@ -99,6 +99,11 @@
   std::wstring old_tmp;
   old_tmp.resize(kMaxEnvVariableValueSize);
   old_tmp.resize(GetEnvironmentVariableW(L"TMP", old_tmp.data(), old_tmp.size()));
+  if (old_tmp.empty()) {
+    // Can't continue with empty TMP folder.
+    return;
+  }
+
   std::wstring new_tmp = old_tmp;
   if (new_tmp.back() != L'\\') {
     new_tmp.push_back(L'\\');
@@ -156,14 +161,18 @@
 TEST(file, RootDirectoryWindows) {
   constexpr auto kMaxEnvVariableValueSize = 32767;
   std::wstring old_tmp;
+  bool tmp_is_empty = false;
   old_tmp.resize(kMaxEnvVariableValueSize);
   old_tmp.resize(GetEnvironmentVariableW(L"TMP", old_tmp.data(), old_tmp.size()));
+  if (old_tmp.empty()) {
+    tmp_is_empty = (GetLastError() == ERROR_ENVVAR_NOT_FOUND);
+  }
   SetEnvironmentVariableW(L"TMP", L"C:");
 
   TemporaryFile tf;
   ASSERT_NE(tf.fd, -1) << tf.path;
 
-  SetEnvironmentVariableW(L"TMP", old_tmp.c_str());
+  SetEnvironmentVariableW(L"TMP", tmp_is_empty ? nullptr : old_tmp.c_str());
 }
 #endif
 
diff --git a/debuggerd/client/debuggerd_client.cpp b/debuggerd/client/debuggerd_client.cpp
index 1a5b435..7e35a2f 100644
--- a/debuggerd/client/debuggerd_client.cpp
+++ b/debuggerd/client/debuggerd_client.cpp
@@ -195,7 +195,10 @@
     return false;
   }
 
-  InterceptRequest req = {.pid = pid, .dump_type = dump_type};
+  InterceptRequest req = {
+      .dump_type = dump_type,
+      .pid = pid,
+  };
   if (!set_timeout(sockfd)) {
     PLOG(ERROR) << "libdebugger_client: failed to set timeout";
     return false;
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index c9a193c..99729dc 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -101,7 +101,10 @@
     FAIL() << "failed to contact tombstoned: " << strerror(errno);
   }
 
-  InterceptRequest req = {.pid = target_pid, .dump_type = intercept_type};
+  InterceptRequest req = {
+      .dump_type = intercept_type,
+      .pid = target_pid,
+  };
 
   unique_fd output_pipe_write;
   if (!Pipe(output_fd, &output_pipe_write)) {
diff --git a/debuggerd/handler/debuggerd_handler.cpp b/debuggerd/handler/debuggerd_handler.cpp
index 598ea85..b90ca80 100644
--- a/debuggerd/handler/debuggerd_handler.cpp
+++ b/debuggerd/handler/debuggerd_handler.cpp
@@ -525,8 +525,8 @@
   log_signal_summary(info);
 
   debugger_thread_info thread_info = {
-      .pseudothread_tid = -1,
       .crashing_tid = __gettid(),
+      .pseudothread_tid = -1,
       .siginfo = info,
       .ucontext = context,
       .abort_msg = reinterpret_cast<uintptr_t>(abort_message),
diff --git a/debuggerd/libdebuggerd/test/tombstone_test.cpp b/debuggerd/libdebuggerd/test/tombstone_test.cpp
index 88c206f..9dea7ac 100644
--- a/debuggerd/libdebuggerd/test/tombstone_test.cpp
+++ b/debuggerd/libdebuggerd/test/tombstone_test.cpp
@@ -345,9 +345,9 @@
 
 TEST_F(TombstoneTest, dump_thread_info_uid) {
   dump_thread_info(&log_, ThreadInfo{.uid = 1,
-                                     .pid = 2,
                                      .tid = 3,
                                      .thread_name = "some_thread",
+                                     .pid = 2,
                                      .process_name = "some_process"});
   std::string expected = "pid: 2, tid: 3, name: some_thread  >>> some_process <<<\nuid: 1\n";
   ASSERT_STREQ(expected.c_str(), amfd_data_.c_str());
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
index e50f7c3..2ff5243 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -112,13 +112,16 @@
 };
 
 void ParseFileEncryption(const std::string& arg, FstabEntry* entry) {
-    // The fileencryption flag is followed by an = and the mode of contents encryption, then
-    // optionally a and the mode of filenames encryption (defaults to aes-256-cts).  Get it and
-    // return it.
+    // The fileencryption flag is followed by an = and 1 to 3 colon-separated fields:
+    //
+    // 1. Contents encryption mode
+    // 2. Filenames encryption mode (defaults to "aes-256-cts" or "adiantum"
+    //    depending on the contents encryption mode)
+    // 3. Encryption policy version (defaults to "v1". Use "v2" on new devices.)
     entry->fs_mgr_flags.file_encryption = true;
 
     auto parts = Split(arg, ":");
-    if (parts.empty() || parts.size() > 2) {
+    if (parts.empty() || parts.size() > 3) {
         LWARNING << "Warning: fileencryption= flag malformed: " << arg;
         return;
     }
@@ -137,7 +140,7 @@
 
     entry->file_contents_mode = parts[0];
 
-    if (parts.size() == 2) {
+    if (parts.size() >= 2) {
         if (std::find(kFileNamesEncryptionMode.begin(), kFileNamesEncryptionMode.end(), parts[1]) ==
             kFileNamesEncryptionMode.end()) {
             LWARNING << "fileencryption= flag malformed, file names encryption mode not found: "
@@ -151,6 +154,16 @@
     } else {
         entry->file_names_mode = "aes-256-cts";
     }
+
+    if (parts.size() >= 3) {
+        if (!android::base::StartsWith(parts[2], 'v') ||
+            !android::base::ParseInt(&parts[2][1], &entry->file_policy_version)) {
+            LWARNING << "fileencryption= flag malformed, unknown options: " << arg;
+            return;
+        }
+    } else {
+        entry->file_policy_version = 1;
+    }
 }
 
 bool SetMountFlag(const std::string& flag, FstabEntry* entry) {
@@ -288,6 +301,7 @@
             entry->key_loc = arg;
             entry->file_contents_mode = "aes-256-xts";
             entry->file_names_mode = "aes-256-cts";
+            entry->file_policy_version = 1;
         } else if (StartsWith(flag, "max_comp_streams=")) {
             if (!ParseInt(arg, &entry->max_comp_streams)) {
                 LWARNING << "Warning: max_comp_streams= flag malformed: " << arg;
@@ -672,13 +686,14 @@
         if (entries.empty()) {
             FstabEntry entry = {
                     .blk_device = partition,
+                    // .logical_partition_name is required to look up AVB Hashtree descriptors.
+                    .logical_partition_name = "system",
                     .mount_point = mount_point,
                     .fs_type = "ext4",
                     .flags = MS_RDONLY,
                     .fs_options = "barrier=1",
                     .avb_keys = kGsiKeys,
-                    // .logical_partition_name is required to look up AVB Hashtree descriptors.
-                    .logical_partition_name = "system"};
+            };
             entry.fs_mgr_flags.wait = true;
             entry.fs_mgr_flags.logical = true;
             entry.fs_mgr_flags.first_stage_mount = true;
diff --git a/fs_mgr/fs_mgr_overlayfs.cpp b/fs_mgr/fs_mgr_overlayfs.cpp
index 358c980..0579a3d 100644
--- a/fs_mgr/fs_mgr_overlayfs.cpp
+++ b/fs_mgr/fs_mgr_overlayfs.cpp
@@ -782,6 +782,7 @@
     } else {
         fs_mgr_set_blk_ro(device_path, false);
     }
+    entry.fs_mgr_flags.check = true;
     auto save_errno = errno;
     auto mounted = fs_mgr_do_mount_one(entry) == 0;
     if (!mounted) {
diff --git a/fs_mgr/include_fstab/fstab/fstab.h b/fs_mgr/include_fstab/fstab/fstab.h
index d999ae1..3c517dc 100644
--- a/fs_mgr/include_fstab/fstab/fstab.h
+++ b/fs_mgr/include_fstab/fstab/fstab.h
@@ -47,6 +47,7 @@
     off64_t reserved_size = 0;
     std::string file_contents_mode;
     std::string file_names_mode;
+    int file_policy_version = 0;
     off64_t erase_blk_size = 0;
     off64_t logical_blk_size = 0;
     std::string sysfs_path;
diff --git a/fs_mgr/libdm/Android.bp b/fs_mgr/libdm/Android.bp
index dd95a5e..3ce909e 100644
--- a/fs_mgr/libdm/Android.bp
+++ b/fs_mgr/libdm/Android.bp
@@ -79,3 +79,19 @@
     require_root: true,
     test_min_api_level: 29,
 }
+
+cc_fuzz {
+  name: "dm_table_fuzzer",
+  defaults: ["fs_mgr_defaults"],
+  srcs: [
+    "dm_linear_fuzzer.cpp",
+    "test_util.cpp",
+  ],
+  static_libs: [
+        "libdm",
+        "libbase",
+        "libext2_uuid",
+        "libfs_mgr",
+        "liblog",
+  ],
+}
diff --git a/fs_mgr/libdm/dm_linear_fuzzer.cpp b/fs_mgr/libdm/dm_linear_fuzzer.cpp
new file mode 100644
index 0000000..b119635
--- /dev/null
+++ b/fs_mgr/libdm/dm_linear_fuzzer.cpp
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2019 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 <stddef.h>
+#include <stdint.h>
+#include <string.h>
+
+#include <chrono>
+
+#include <android-base/file.h>
+#include <android-base/unique_fd.h>
+#include <libdm/dm_table.h>
+#include <libdm/loop_control.h>
+
+#include "test_util.h"
+
+using namespace android;
+using namespace android::base;
+using namespace android::dm;
+using namespace std;
+using namespace std::chrono_literals;
+
+/*
+ * This test aims at making the library crash, so these functions are not
+ * really useful.
+ * Keeping them here for future use.
+ */
+template <class T, class C>
+void ASSERT_EQ(const T& /*a*/, const C& /*b*/) {
+    // if (a != b) {}
+}
+
+template <class T>
+void ASSERT_FALSE(const T& /*a*/) {
+    // if (a) {}
+}
+
+template <class T, class C>
+void ASSERT_GE(const T& /*a*/, const C& /*b*/) {
+    // if (a < b) {}
+}
+
+template <class T, class C>
+void ASSERT_NE(const T& /*a*/, const C& /*b*/) {
+    // if (a == b) {}
+}
+
+template <class T>
+void ASSERT_TRUE(const T& /*a*/) {
+    // if (!a) {}
+}
+
+template <class T, class C>
+void EXPECT_EQ(const T& a, const C& b) {
+    ASSERT_EQ(a, b);
+}
+
+template <class T>
+void EXPECT_TRUE(const T& a) {
+    ASSERT_TRUE(a);
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+    uint64_t val[6];
+
+    if (size != sizeof(*val)) {
+        return 0;
+    }
+
+    memcpy(&val, &data[0], sizeof(*val));
+
+    unique_fd tmp1(CreateTempFile("file_1", 4096));
+    ASSERT_GE(tmp1, 0);
+    unique_fd tmp2(CreateTempFile("file_2", 4096));
+    ASSERT_GE(tmp2, 0);
+
+    LoopDevice loop_a(tmp1, 10s);
+    ASSERT_TRUE(loop_a.valid());
+    LoopDevice loop_b(tmp2, 10s);
+    ASSERT_TRUE(loop_b.valid());
+
+    // Define a 2-sector device, with each sector mapping to the first sector
+    // of one of our loop devices.
+    DmTable table;
+    ASSERT_TRUE(table.Emplace<DmTargetLinear>(val[0], val[1], loop_a.device(), val[2]));
+    ASSERT_TRUE(table.Emplace<DmTargetLinear>(val[3], val[4], loop_b.device(), val[5]));
+    ASSERT_TRUE(table.valid());
+    ASSERT_EQ(2u, table.num_sectors());
+
+    TempDevice dev("libdm-test-dm-linear", table);
+    ASSERT_TRUE(dev.valid());
+    ASSERT_FALSE(dev.path().empty());
+
+    auto& dm = DeviceMapper::Instance();
+
+    dev_t dev_number;
+    ASSERT_TRUE(dm.GetDeviceNumber(dev.name(), &dev_number));
+    ASSERT_NE(dev_number, 0);
+
+    std::string dev_string;
+    ASSERT_TRUE(dm.GetDeviceString(dev.name(), &dev_string));
+    ASSERT_FALSE(dev_string.empty());
+
+    // Test GetTableStatus.
+    vector<DeviceMapper::TargetInfo> targets;
+    ASSERT_TRUE(dm.GetTableStatus(dev.name(), &targets));
+    ASSERT_EQ(targets.size(), 2);
+    EXPECT_EQ(strcmp(targets[0].spec.target_type, "linear"), 0);
+    EXPECT_TRUE(targets[0].data.empty());
+    EXPECT_EQ(targets[0].spec.sector_start, 0);
+    EXPECT_EQ(targets[0].spec.length, 1);
+    EXPECT_EQ(strcmp(targets[1].spec.target_type, "linear"), 0);
+    EXPECT_TRUE(targets[1].data.empty());
+    EXPECT_EQ(targets[1].spec.sector_start, 1);
+    EXPECT_EQ(targets[1].spec.length, 1);
+
+    // Test GetTargetType().
+    EXPECT_EQ(DeviceMapper::GetTargetType(targets[0].spec), std::string{"linear"});
+    EXPECT_EQ(DeviceMapper::GetTargetType(targets[1].spec), std::string{"linear"});
+
+    // Normally the TestDevice destructor would delete this, but at least one
+    // test should ensure that device deletion works.
+    ASSERT_TRUE(dev.Destroy());
+
+    return 0;
+}
diff --git a/fs_mgr/libdm/dm_table.cpp b/fs_mgr/libdm/dm_table.cpp
index 15c7ce1..efe03ab 100644
--- a/fs_mgr/libdm/dm_table.cpp
+++ b/fs_mgr/libdm/dm_table.cpp
@@ -26,6 +26,7 @@
     if (!target->Valid()) {
         return false;
     }
+    num_sectors_ += target->size();
     targets_.push_back(std::move(target));
     return true;
 }
diff --git a/fs_mgr/libdm/dm_test.cpp b/fs_mgr/libdm/dm_test.cpp
index eed21dc..ed2fa83 100644
--- a/fs_mgr/libdm/dm_test.cpp
+++ b/fs_mgr/libdm/dm_test.cpp
@@ -47,50 +47,6 @@
     ASSERT_TRUE(dm.GetTargetByName("linear", &info));
 }
 
-// Helper to ensure that device mapper devices are released.
-class TempDevice {
-  public:
-    TempDevice(const std::string& name, const DmTable& table)
-        : dm_(DeviceMapper::Instance()), name_(name), valid_(false) {
-        valid_ = dm_.CreateDevice(name, table, &path_, 5s);
-    }
-    TempDevice(TempDevice&& other) noexcept
-        : dm_(other.dm_), name_(other.name_), path_(other.path_), valid_(other.valid_) {
-        other.valid_ = false;
-    }
-    ~TempDevice() {
-        if (valid_) {
-            dm_.DeleteDevice(name_);
-        }
-    }
-    bool Destroy() {
-        if (!valid_) {
-            return false;
-        }
-        valid_ = false;
-        return dm_.DeleteDevice(name_);
-    }
-    std::string path() const { return path_; }
-    const std::string& name() const { return name_; }
-    bool valid() const { return valid_; }
-
-    TempDevice(const TempDevice&) = delete;
-    TempDevice& operator=(const TempDevice&) = delete;
-
-    TempDevice& operator=(TempDevice&& other) noexcept {
-        name_ = other.name_;
-        valid_ = other.valid_;
-        other.valid_ = false;
-        return *this;
-    }
-
-  private:
-    DeviceMapper& dm_;
-    std::string name_;
-    std::string path_;
-    bool valid_;
-};
-
 TEST(libdm, DmLinear) {
     unique_fd tmp1(CreateTempFile("file_1", 4096));
     ASSERT_GE(tmp1, 0);
@@ -114,6 +70,7 @@
     ASSERT_TRUE(table.Emplace<DmTargetLinear>(0, 1, loop_a.device(), 0));
     ASSERT_TRUE(table.Emplace<DmTargetLinear>(1, 1, loop_b.device(), 0));
     ASSERT_TRUE(table.valid());
+    ASSERT_EQ(2u, table.num_sectors());
 
     TempDevice dev("libdm-test-dm-linear", table);
     ASSERT_TRUE(dev.valid());
@@ -176,6 +133,7 @@
     DmTable table;
     ASSERT_TRUE(table.Emplace<DmTargetLinear>(0, 1, loop_a.device(), 0));
     ASSERT_TRUE(table.valid());
+    ASSERT_EQ(1u, table.num_sectors());
 
     TempDevice dev("libdm-test-dm-suspend-resume", table);
     ASSERT_TRUE(dev.valid());
@@ -292,6 +250,7 @@
     ASSERT_TRUE(origin_table.AddTarget(make_unique<DmTargetSnapshotOrigin>(
             0, kBaseDeviceSize / kSectorSize, base_loop_->device())));
     ASSERT_TRUE(origin_table.valid());
+    ASSERT_EQ(kBaseDeviceSize / kSectorSize, origin_table.num_sectors());
 
     origin_dev_ = std::make_unique<TempDevice>("libdm-test-dm-snapshot-origin", origin_table);
     ASSERT_TRUE(origin_dev_->valid());
@@ -303,6 +262,7 @@
             0, kBaseDeviceSize / kSectorSize, base_loop_->device(), cow_loop_->device(),
             SnapshotStorageMode::Persistent, 8)));
     ASSERT_TRUE(snap_table.valid());
+    ASSERT_EQ(kBaseDeviceSize / kSectorSize, snap_table.num_sectors());
 
     snapshot_dev_ = std::make_unique<TempDevice>("libdm-test-dm-snapshot", snap_table);
     ASSERT_TRUE(snapshot_dev_->valid());
@@ -322,6 +282,7 @@
             make_unique<DmTargetSnapshot>(0, kBaseDeviceSize / kSectorSize, base_loop_->device(),
                                           cow_loop_->device(), SnapshotStorageMode::Merge, 8)));
     ASSERT_TRUE(merge_table.valid());
+    ASSERT_EQ(kBaseDeviceSize / kSectorSize, merge_table.num_sectors());
 
     DeviceMapper& dm = DeviceMapper::Instance();
     ASSERT_TRUE(dm.LoadTableAndActivate("libdm-test-dm-snapshot", merge_table));
diff --git a/fs_mgr/libdm/include/libdm/loop_control.h b/fs_mgr/libdm/include/libdm/loop_control.h
index eeed6b5..ad53c11 100644
--- a/fs_mgr/libdm/include/libdm/loop_control.h
+++ b/fs_mgr/libdm/include/libdm/loop_control.h
@@ -64,7 +64,8 @@
   public:
     // Create a loop device for the given file descriptor. It is closed when
     // LoopDevice is destroyed only if auto_close is true.
-    LoopDevice(int fd, const std::chrono::milliseconds& timeout_ms, bool auto_close = false);
+    LoopDevice(android::base::borrowed_fd fd, const std::chrono::milliseconds& timeout_ms,
+               bool auto_close = false);
     // Create a loop device for the given file path. It will be opened for
     // reading and writing and closed when the loop device is detached.
     LoopDevice(const std::string& path, const std::chrono::milliseconds& timeout_ms);
@@ -81,8 +82,8 @@
   private:
     void Init(const std::chrono::milliseconds& timeout_ms);
 
-    android::base::unique_fd fd_;
-    bool owns_fd_;
+    android::base::borrowed_fd fd_;
+    android::base::unique_fd owned_fd_;
     std::string device_;
     LoopControl control_;
     bool valid_ = false;
diff --git a/fs_mgr/libdm/loop_control.cpp b/fs_mgr/libdm/loop_control.cpp
index edc9a45..2e40a18 100644
--- a/fs_mgr/libdm/loop_control.cpp
+++ b/fs_mgr/libdm/loop_control.cpp
@@ -133,18 +133,23 @@
     return true;
 }
 
-LoopDevice::LoopDevice(int fd, const std::chrono::milliseconds& timeout_ms, bool auto_close)
-    : fd_(fd), owns_fd_(auto_close) {
+LoopDevice::LoopDevice(android::base::borrowed_fd fd, const std::chrono::milliseconds& timeout_ms,
+                       bool auto_close)
+    : fd_(fd), owned_fd_(-1) {
+    if (auto_close) {
+        owned_fd_.reset(fd.get());
+    }
     Init(timeout_ms);
 }
 
 LoopDevice::LoopDevice(const std::string& path, const std::chrono::milliseconds& timeout_ms)
-    : fd_(-1), owns_fd_(true) {
-    fd_.reset(open(path.c_str(), O_RDWR | O_CLOEXEC));
-    if (fd_ < -1) {
+    : fd_(-1), owned_fd_(-1) {
+    owned_fd_.reset(open(path.c_str(), O_RDWR | O_CLOEXEC));
+    if (owned_fd_ == -1) {
         PLOG(ERROR) << "open failed for " << path;
         return;
     }
+    fd_ = owned_fd_;
     Init(timeout_ms);
 }
 
@@ -152,13 +157,10 @@
     if (valid()) {
         control_.Detach(device_);
     }
-    if (!owns_fd_) {
-        (void)fd_.release();
-    }
 }
 
 void LoopDevice::Init(const std::chrono::milliseconds& timeout_ms) {
-    valid_ = control_.Attach(fd_, timeout_ms, &device_);
+    valid_ = control_.Attach(fd_.get(), timeout_ms, &device_);
 }
 
 }  // namespace dm
diff --git a/fs_mgr/libdm/test_util.h b/fs_mgr/libdm/test_util.h
index 96b051c..6671364 100644
--- a/fs_mgr/libdm/test_util.h
+++ b/fs_mgr/libdm/test_util.h
@@ -20,8 +20,12 @@
 #include <android-base/unique_fd.h>
 #include <stddef.h>
 
+#include <chrono>
 #include <string>
 
+#include <libdm/dm.h>
+#include <libdm/dm_table.h>
+
 namespace android {
 namespace dm {
 
@@ -29,6 +33,50 @@
 // created with a fixed size.
 android::base::unique_fd CreateTempFile(const std::string& name, size_t size);
 
+// Helper to ensure that device mapper devices are released.
+class TempDevice {
+  public:
+    TempDevice(const std::string& name, const DmTable& table)
+        : dm_(DeviceMapper::Instance()), name_(name), valid_(false) {
+        valid_ = dm_.CreateDevice(name, table, &path_, std::chrono::seconds(5));
+    }
+    TempDevice(TempDevice&& other) noexcept
+        : dm_(other.dm_), name_(other.name_), path_(other.path_), valid_(other.valid_) {
+        other.valid_ = false;
+    }
+    ~TempDevice() {
+        if (valid_) {
+            dm_.DeleteDevice(name_);
+        }
+    }
+    bool Destroy() {
+        if (!valid_) {
+            return false;
+        }
+        valid_ = false;
+        return dm_.DeleteDevice(name_);
+    }
+    std::string path() const { return path_; }
+    const std::string& name() const { return name_; }
+    bool valid() const { return valid_; }
+
+    TempDevice(const TempDevice&) = delete;
+    TempDevice& operator=(const TempDevice&) = delete;
+
+    TempDevice& operator=(TempDevice&& other) noexcept {
+        name_ = other.name_;
+        valid_ = other.valid_;
+        other.valid_ = false;
+        return *this;
+    }
+
+  private:
+    DeviceMapper& dm_;
+    std::string name_;
+    std::string path_;
+    bool valid_;
+};
+
 }  // namespace dm
 }  // namespace android
 
diff --git a/fs_mgr/libfs_avb/tests/avb_util_test.cpp b/fs_mgr/libfs_avb/tests/avb_util_test.cpp
index 0d342d3..784eb9c 100644
--- a/fs_mgr/libfs_avb/tests/avb_util_test.cpp
+++ b/fs_mgr/libfs_avb/tests/avb_util_test.cpp
@@ -101,10 +101,10 @@
 TEST_F(AvbUtilTest, DeriveAvbPartitionName) {
     // The fstab_entry to test.
     FstabEntry fstab_entry = {
-        .blk_device = "/dev/block/dm-1",  // a dm-linear device (logical)
-        .mount_point = "/system",
-        .fs_type = "ext4",
-        .logical_partition_name = "system",
+            .blk_device = "/dev/block/dm-1",  // a dm-linear device (logical)
+            .logical_partition_name = "system",
+            .mount_point = "/system",
+            .fs_type = "ext4",
     };
 
     // Logical partitions.
diff --git a/fs_mgr/libsnapshot/Android.bp b/fs_mgr/libsnapshot/Android.bp
index 834bf3b..8cf0f3b 100644
--- a/fs_mgr/libsnapshot/Android.bp
+++ b/fs_mgr/libsnapshot/Android.bp
@@ -49,11 +49,17 @@
         "libfiemap_headers",
     ],
     export_include_dirs: ["include"],
+    proto: {
+        type: "lite",
+        export_proto_headers: true,
+        canonical_path_from_root: false,
+    },
 }
 
 filegroup {
     name: "libsnapshot_sources",
     srcs: [
+        "android/snapshot/snapshot.proto",
         "snapshot.cpp",
         "snapshot_metadata_updater.cpp",
         "partition_cow_creator.cpp",
@@ -132,9 +138,10 @@
         "libbinder",
         "libext4_utils",
         "libfs_mgr",
-        "libutils",
         "liblog",
         "liblp",
+        "libprotobuf-cpp-lite",
+        "libutils",
     ],
     init_rc: [
         "snapshotctl.rc",
diff --git a/fs_mgr/libsnapshot/android/snapshot/snapshot.proto b/fs_mgr/libsnapshot/android/snapshot/snapshot.proto
new file mode 100644
index 0000000..629c3a4
--- /dev/null
+++ b/fs_mgr/libsnapshot/android/snapshot/snapshot.proto
@@ -0,0 +1,87 @@
+// Copyright (C) 2019 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.
+
+syntax = "proto3";
+package android.snapshot;
+
+option optimize_for = LITE_RUNTIME;
+
+// Next: 4
+enum SnapshotState {
+    // No snapshot is found.
+    NONE = 0;
+
+    // The snapshot has been created and possibly written to. Rollbacks are
+    // possible by destroying the snapshot.
+    CREATED = 1;
+
+    // Changes are being merged. No rollbacks are possible beyond this point.
+    MERGING = 2;
+
+    // Changes have been merged, Future reboots may map the base device
+    // directly.
+    MERGE_COMPLETED = 3;
+}
+
+// Next: 9
+message SnapshotStatus {
+    // Name of the snapshot. This is usually the name of the snapshotted
+    // logical partition; for example, "system_b".
+    string name = 1;
+
+    SnapshotState state = 2;
+
+    // Size of the full (base) device.
+    uint64 device_size = 3;
+
+    // Size of the snapshot. This is the sum of lengths of ranges in the base
+    // device that needs to be snapshotted during the update.
+    // This must be less than or equal to |device_size|.
+    // This value is 0 if no snapshot is needed for this device because
+    // no changes
+    uint64 snapshot_size = 4;
+
+    // Size of the "COW partition". A COW partition is a special logical
+    // partition represented in the super partition metadata. This partition and
+    // the "COW image" form the "COW device" that supports the snapshot device.
+    //
+    // When SnapshotManager creates a COW device, it first searches for unused
+    // blocks in the super partition, and use those before creating the COW
+    // image if the COW partition is not big enough.
+    //
+    // This value is 0 if no space in super is left for the COW partition.
+    // |cow_partition_size + cow_file_size| must not be zero if |snapshot_size|
+    // is non-zero.
+    uint64 cow_partition_size = 5;
+
+    // Size of the "COW file", or "COW image". A COW file / image is created
+    // when the "COW partition" is not big enough to store changes to the
+    // snapshot device.
+    //
+    // This value is 0 if |cow_partition_size| is big enough to hold all changes
+    // to the snapshot device.
+    uint64 cow_file_size = 6;
+
+    // Sectors allocated for the COW device. Recording this value right after
+    // the update and before the merge allows us to infer the progress of the
+    // merge process.
+    // This is non-zero when |state| == MERGING or MERGE_COMPLETED.
+    uint64 sectors_allocated = 7;
+
+    // Metadata sectors allocated for the COW device. Recording this value right
+    // before the update and before the merge allows us to infer the progress of
+    // the merge process.
+    // This is non-zero when |state| == MERGING or MERGE_COMPLETED.
+    uint64 metadata_sectors = 8;
+}
diff --git a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
index 0d6aa2c..69f2895 100644
--- a/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
+++ b/fs_mgr/libsnapshot/include/libsnapshot/snapshot.h
@@ -53,8 +53,9 @@
 
 struct AutoDeleteCowImage;
 struct AutoDeleteSnapshot;
-struct PartitionCowCreator;
 struct AutoDeviceList;
+struct PartitionCowCreator;
+class SnapshotStatus;
 
 static constexpr const std::string_view kCowGroupName = "cow";
 
@@ -250,22 +251,6 @@
     std::unique_ptr<LockedFile> OpenFile(const std::string& file, int open_flags, int lock_flags);
     bool Truncate(LockedFile* file);
 
-    enum class SnapshotState : int { None, Created, Merging, MergeCompleted };
-    static std::string to_string(SnapshotState state);
-
-    // This state is persisted per-snapshot in /metadata/ota/snapshots/.
-    struct SnapshotStatus {
-        SnapshotState state = SnapshotState::None;
-        uint64_t device_size = 0;
-        uint64_t snapshot_size = 0;
-        uint64_t cow_partition_size = 0;
-        uint64_t cow_file_size = 0;
-
-        // These are non-zero when merging.
-        uint64_t sectors_allocated = 0;
-        uint64_t metadata_sectors = 0;
-    };
-
     // Create a new snapshot record. This creates the backing COW store and
     // persists information needed to map the device. The device can be mapped
     // with MapSnapshot().
@@ -282,7 +267,7 @@
     //
     // All sizes are specified in bytes, and the device, snapshot, COW partition and COW file sizes
     // must be a multiple of the sector size (512 bytes).
-    bool CreateSnapshot(LockedFile* lock, const std::string& name, SnapshotStatus status);
+    bool CreateSnapshot(LockedFile* lock, SnapshotStatus* status);
 
     // |name| should be the base partition name (e.g. "system_a"). Create the
     // backing COW image using the size previously passed to CreateSnapshot().
@@ -363,8 +348,7 @@
     UpdateState CheckTargetMergeState(LockedFile* lock, const std::string& name);
 
     // Interact with status files under /metadata/ota/snapshots.
-    bool WriteSnapshotStatus(LockedFile* lock, const std::string& name,
-                             const SnapshotStatus& status);
+    bool WriteSnapshotStatus(LockedFile* lock, const SnapshotStatus& status);
     bool ReadSnapshotStatus(LockedFile* lock, const std::string& name, SnapshotStatus* status);
     std::string GetSnapshotStatusFilePath(const std::string& name);
 
diff --git a/fs_mgr/libsnapshot/partition_cow_creator.cpp b/fs_mgr/libsnapshot/partition_cow_creator.cpp
index 404ef27..eedc1cd 100644
--- a/fs_mgr/libsnapshot/partition_cow_creator.cpp
+++ b/fs_mgr/libsnapshot/partition_cow_creator.cpp
@@ -18,6 +18,7 @@
 
 #include <android-base/logging.h>
 
+#include <android/snapshot/snapshot.pb.h>
 #include "utility.h"
 
 using android::dm::kSectorSize;
@@ -84,13 +85,14 @@
             << "logical_block_size is not power of 2";
 
     Return ret;
-    ret.snapshot_status.device_size = target_partition->size();
+    ret.snapshot_status.set_name(target_partition->name());
+    ret.snapshot_status.set_device_size(target_partition->size());
 
     // TODO(b/141889746): Optimize by using a smaller snapshot. Some ranges in target_partition
     // may be written directly.
-    ret.snapshot_status.snapshot_size = target_partition->size();
+    ret.snapshot_status.set_snapshot_size(target_partition->size());
 
-    auto cow_size = GetCowSize(ret.snapshot_status.snapshot_size);
+    auto cow_size = GetCowSize(ret.snapshot_status.snapshot_size());
     if (!cow_size.has_value()) return std::nullopt;
 
     // Compute regions that are free in both current and target metadata. These are the regions
@@ -106,18 +108,20 @@
     LOG(INFO) << "Remaining free space for COW: " << free_region_length << " bytes";
 
     // Compute the COW partition size.
-    ret.snapshot_status.cow_partition_size = std::min(*cow_size, free_region_length);
+    uint64_t cow_partition_size = std::min(*cow_size, free_region_length);
     // Round it down to the nearest logical block. Logical partitions must be a multiple
     // of logical blocks.
-    ret.snapshot_status.cow_partition_size &= ~(logical_block_size - 1);
+    cow_partition_size &= ~(logical_block_size - 1);
+    ret.snapshot_status.set_cow_partition_size(cow_partition_size);
     // Assign cow_partition_usable_regions to indicate what regions should the COW partition uses.
     ret.cow_partition_usable_regions = std::move(free_regions);
 
     // The rest of the COW space is allocated on ImageManager.
-    ret.snapshot_status.cow_file_size = (*cow_size) - ret.snapshot_status.cow_partition_size;
+    uint64_t cow_file_size = (*cow_size) - ret.snapshot_status.cow_partition_size();
     // Round it up to the nearest sector.
-    ret.snapshot_status.cow_file_size += kSectorSize - 1;
-    ret.snapshot_status.cow_file_size &= ~(kSectorSize - 1);
+    cow_file_size += kSectorSize - 1;
+    cow_file_size &= ~(kSectorSize - 1);
+    ret.snapshot_status.set_cow_file_size(cow_file_size);
 
     return ret;
 }
diff --git a/fs_mgr/libsnapshot/partition_cow_creator.h b/fs_mgr/libsnapshot/partition_cow_creator.h
index 0e645c6..8888f78 100644
--- a/fs_mgr/libsnapshot/partition_cow_creator.h
+++ b/fs_mgr/libsnapshot/partition_cow_creator.h
@@ -20,8 +20,9 @@
 #include <string>
 
 #include <liblp/builder.h>
+#include <update_engine/update_metadata.pb.h>
 
-#include <libsnapshot/snapshot.h>
+#include <android/snapshot/snapshot.pb.h>
 
 namespace android {
 namespace snapshot {
@@ -51,7 +52,7 @@
     const RepeatedPtrField<InstallOperation>* operations = nullptr;
 
     struct Return {
-        SnapshotManager::SnapshotStatus snapshot_status;
+        SnapshotStatus snapshot_status;
         std::vector<Interval> cow_partition_usable_regions;
     };
 
diff --git a/fs_mgr/libsnapshot/partition_cow_creator_test.cpp b/fs_mgr/libsnapshot/partition_cow_creator_test.cpp
index ccd087e..cf2d745 100644
--- a/fs_mgr/libsnapshot/partition_cow_creator_test.cpp
+++ b/fs_mgr/libsnapshot/partition_cow_creator_test.cpp
@@ -32,17 +32,20 @@
 };
 
 TEST_F(PartitionCowCreatorTest, IntersectSelf) {
-    auto builder_a = MetadataBuilder::New(1024 * 1024, 1024, 2);
+    constexpr uint64_t initial_size = 1_MiB;
+    constexpr uint64_t final_size = 40_KiB;
+
+    auto builder_a = MetadataBuilder::New(initial_size, 1_KiB, 2);
     ASSERT_NE(builder_a, nullptr);
     auto system_a = builder_a->AddPartition("system_a", LP_PARTITION_ATTR_READONLY);
     ASSERT_NE(system_a, nullptr);
-    ASSERT_TRUE(builder_a->ResizePartition(system_a, 40 * 1024));
+    ASSERT_TRUE(builder_a->ResizePartition(system_a, final_size));
 
-    auto builder_b = MetadataBuilder::New(1024 * 1024, 1024, 2);
+    auto builder_b = MetadataBuilder::New(initial_size, 1_KiB, 2);
     ASSERT_NE(builder_b, nullptr);
     auto system_b = builder_b->AddPartition("system_b", LP_PARTITION_ATTR_READONLY);
     ASSERT_NE(system_b, nullptr);
-    ASSERT_TRUE(builder_b->ResizePartition(system_b, 40 * 1024));
+    ASSERT_TRUE(builder_b->ResizePartition(system_b, final_size));
 
     PartitionCowCreator creator{.target_metadata = builder_b.get(),
                                 .target_suffix = "_b",
@@ -51,8 +54,8 @@
                                 .current_suffix = "_a"};
     auto ret = creator.Run();
     ASSERT_TRUE(ret.has_value());
-    ASSERT_EQ(40 * 1024, ret->snapshot_status.device_size);
-    ASSERT_EQ(40 * 1024, ret->snapshot_status.snapshot_size);
+    ASSERT_EQ(final_size, ret->snapshot_status.device_size());
+    ASSERT_EQ(final_size, ret->snapshot_status.snapshot_size());
 }
 
 TEST_F(PartitionCowCreatorTest, Holes) {
@@ -64,7 +67,7 @@
 
     BlockDeviceInfo super_device("super", kSuperSize, 0, 0, 4_KiB);
     std::vector<BlockDeviceInfo> devices = {super_device};
-    auto source = MetadataBuilder::New(devices, "super", 1024, 2);
+    auto source = MetadataBuilder::New(devices, "super", 1_KiB, 2);
     auto system = source->AddPartition("system_a", 0);
     ASSERT_NE(nullptr, system);
     ASSERT_TRUE(source->ResizePartition(system, big_size));
diff --git a/fs_mgr/libsnapshot/snapshot.cpp b/fs_mgr/libsnapshot/snapshot.cpp
index e085bc5..395fb40 100644
--- a/fs_mgr/libsnapshot/snapshot.cpp
+++ b/fs_mgr/libsnapshot/snapshot.cpp
@@ -38,6 +38,7 @@
 #include <libfiemap/image_manager.h>
 #include <liblp/liblp.h>
 
+#include <android/snapshot/snapshot.pb.h>
 #include "partition_cow_creator.h"
 #include "snapshot_metadata_updater.h"
 #include "utility.h"
@@ -70,8 +71,6 @@
 using namespace std::chrono_literals;
 using namespace std::string_literals;
 
-// Unit is sectors, this is a 4K chunk.
-static constexpr uint32_t kSnapshotChunkSize = 8;
 static constexpr char kBootIndicatorPath[] = "/metadata/ota/snapshot-boot";
 
 class DeviceInfo final : public SnapshotManager::IDeviceInfo {
@@ -234,42 +233,50 @@
     return WriteUpdateState(lock.get(), UpdateState::Unverified);
 }
 
-bool SnapshotManager::CreateSnapshot(LockedFile* lock, const std::string& name,
-                                     SnapshotManager::SnapshotStatus status) {
+bool SnapshotManager::CreateSnapshot(LockedFile* lock, SnapshotStatus* status) {
     CHECK(lock);
     CHECK(lock->lock_mode() == LOCK_EX);
+    CHECK(status);
+
+    if (status->name().empty()) {
+        LOG(ERROR) << "SnapshotStatus has no name.";
+        return false;
+    }
     // Sanity check these sizes. Like liblp, we guarantee the partition size
     // is respected, which means it has to be sector-aligned. (This guarantee
     // is useful for locating avb footers correctly). The COW file size, however,
     // can be arbitrarily larger than specified, so we can safely round it up.
-    if (status.device_size % kSectorSize != 0) {
-        LOG(ERROR) << "Snapshot " << name
-                   << " device size is not a multiple of the sector size: " << status.device_size;
+    if (status->device_size() % kSectorSize != 0) {
+        LOG(ERROR) << "Snapshot " << status->name()
+                   << " device size is not a multiple of the sector size: "
+                   << status->device_size();
         return false;
     }
-    if (status.snapshot_size % kSectorSize != 0) {
-        LOG(ERROR) << "Snapshot " << name << " snapshot size is not a multiple of the sector size: "
-                   << status.snapshot_size;
+    if (status->snapshot_size() % kSectorSize != 0) {
+        LOG(ERROR) << "Snapshot " << status->name()
+                   << " snapshot size is not a multiple of the sector size: "
+                   << status->snapshot_size();
         return false;
     }
-    if (status.cow_partition_size % kSectorSize != 0) {
-        LOG(ERROR) << "Snapshot " << name
+    if (status->cow_partition_size() % kSectorSize != 0) {
+        LOG(ERROR) << "Snapshot " << status->name()
                    << " cow partition size is not a multiple of the sector size: "
-                   << status.cow_partition_size;
+                   << status->cow_partition_size();
         return false;
     }
-    if (status.cow_file_size % kSectorSize != 0) {
-        LOG(ERROR) << "Snapshot " << name << " cow file size is not a multiple of the sector size: "
-                   << status.cow_partition_size;
+    if (status->cow_file_size() % kSectorSize != 0) {
+        LOG(ERROR) << "Snapshot " << status->name()
+                   << " cow file size is not a multiple of the sector size: "
+                   << status->cow_file_size();
         return false;
     }
 
-    status.state = SnapshotState::Created;
-    status.sectors_allocated = 0;
-    status.metadata_sectors = 0;
+    status->set_state(SnapshotState::CREATED);
+    status->set_sectors_allocated(0);
+    status->set_metadata_sectors(0);
 
-    if (!WriteSnapshotStatus(lock, name, status)) {
-        PLOG(ERROR) << "Could not write snapshot status: " << name;
+    if (!WriteSnapshotStatus(lock, *status)) {
+        PLOG(ERROR) << "Could not write snapshot status: " << status->name();
         return false;
     }
     return true;
@@ -287,15 +294,15 @@
 
     // The COW file size should have been rounded up to the nearest sector in CreateSnapshot.
     // Sanity check this.
-    if (status.cow_file_size % kSectorSize != 0) {
+    if (status.cow_file_size() % kSectorSize != 0) {
         LOG(ERROR) << "Snapshot " << name << " COW file size is not a multiple of the sector size: "
-                   << status.cow_file_size;
+                   << status.cow_file_size();
         return false;
     }
 
     std::string cow_image_name = GetCowImageDeviceName(name);
     int cow_flags = IImageManager::CREATE_IMAGE_DEFAULT;
-    return images_->CreateBackingImage(cow_image_name, status.cow_file_size, cow_flags);
+    return images_->CreateBackingImage(cow_image_name, status.cow_file_size(), cow_flags);
 }
 
 bool SnapshotManager::MapSnapshot(LockedFile* lock, const std::string& name,
@@ -309,7 +316,7 @@
     if (!ReadSnapshotStatus(lock, name, &status)) {
         return false;
     }
-    if (status.state == SnapshotState::MergeCompleted) {
+    if (status.state() == SnapshotState::MERGE_COMPLETED) {
         LOG(ERROR) << "Should not create a snapshot device for " << name
                    << " after merging has completed.";
         return false;
@@ -328,24 +335,23 @@
             PLOG(ERROR) << "Could not determine block device size: " << base_device;
             return false;
         }
-        if (status.device_size != dev_size) {
+        if (status.device_size() != dev_size) {
             LOG(ERROR) << "Block device size for " << base_device << " does not match"
-                       << "(expected " << status.device_size << ", got " << dev_size << ")";
+                       << "(expected " << status.device_size() << ", got " << dev_size << ")";
             return false;
         }
     }
-    if (status.device_size % kSectorSize != 0) {
-        LOG(ERROR) << "invalid blockdev size for " << base_device << ": " << status.device_size;
+    if (status.device_size() % kSectorSize != 0) {
+        LOG(ERROR) << "invalid blockdev size for " << base_device << ": " << status.device_size();
         return false;
     }
-    if (status.snapshot_size % kSectorSize != 0 || status.snapshot_size > status.device_size) {
-        LOG(ERROR) << "Invalid snapshot size for " << base_device << ": " << status.snapshot_size;
+    if (status.snapshot_size() % kSectorSize != 0 ||
+        status.snapshot_size() > status.device_size()) {
+        LOG(ERROR) << "Invalid snapshot size for " << base_device << ": " << status.snapshot_size();
         return false;
     }
-    uint64_t snapshot_sectors = status.snapshot_size / kSectorSize;
-    uint64_t linear_sectors = (status.device_size - status.snapshot_size) / kSectorSize;
-
-
+    uint64_t snapshot_sectors = status.snapshot_size() / kSectorSize;
+    uint64_t linear_sectors = (status.device_size() - status.snapshot_size()) / kSectorSize;
 
     auto& dm = DeviceMapper::Instance();
 
@@ -557,8 +563,9 @@
     if (!ReadSnapshotStatus(lock, name, &status)) {
         return false;
     }
-    if (status.state != SnapshotState::Created) {
-        LOG(WARNING) << "Snapshot " << name << " has unexpected state: " << to_string(status.state);
+    if (status.state() != SnapshotState::CREATED) {
+        LOG(WARNING) << "Snapshot " << name
+                     << " has unexpected state: " << SnapshotState_Name(status.state());
     }
 
     // After this, we return true because we technically did switch to a merge
@@ -568,15 +575,15 @@
         return false;
     }
 
-    status.state = SnapshotState::Merging;
+    status.set_state(SnapshotState::MERGING);
 
     DmTargetSnapshot::Status dm_status;
     if (!QuerySnapshotStatus(dm_name, nullptr, &dm_status)) {
         LOG(ERROR) << "Could not query merge status for snapshot: " << dm_name;
     }
-    status.sectors_allocated = dm_status.sectors_allocated;
-    status.metadata_sectors = dm_status.metadata_sectors;
-    if (!WriteSnapshotStatus(lock, name, status)) {
+    status.set_sectors_allocated(dm_status.sectors_allocated);
+    status.set_metadata_sectors(dm_status.metadata_sectors);
+    if (!WriteSnapshotStatus(lock, status)) {
         LOG(ERROR) << "Could not update status file for snapshot: " << name;
     }
     return true;
@@ -821,7 +828,7 @@
         // rebooted after this check, the device will still be a snapshot-merge
         // target. If the have rebooted, the device will now be a linear target,
         // and we can try cleanup again.
-        if (snapshot_status.state == SnapshotState::MergeCompleted) {
+        if (snapshot_status.state() == SnapshotState::MERGE_COMPLETED) {
             // NB: It's okay if this fails now, we gave cleanup our best effort.
             OnSnapshotMergeComplete(lock, name, snapshot_status);
             return UpdateState::MergeCompleted;
@@ -849,7 +856,7 @@
 
     // These two values are equal when merging is complete.
     if (status.sectors_allocated != status.metadata_sectors) {
-        if (snapshot_status.state == SnapshotState::MergeCompleted) {
+        if (snapshot_status.state() == SnapshotState::MERGE_COMPLETED) {
             LOG(ERROR) << "Snapshot " << name << " is merging after being marked merge-complete.";
             return UpdateState::MergeFailed;
         }
@@ -864,8 +871,8 @@
     // This makes it simpler to reason about the next reboot: no matter what
     // part of cleanup failed, first-stage init won't try to create another
     // snapshot device for this partition.
-    snapshot_status.state = SnapshotState::MergeCompleted;
-    if (!WriteSnapshotStatus(lock, name, snapshot_status)) {
+    snapshot_status.set_state(SnapshotState::MERGE_COMPLETED);
+    if (!WriteSnapshotStatus(lock, snapshot_status)) {
         return UpdateState::MergeFailed;
     }
     if (!OnSnapshotMergeComplete(lock, name, snapshot_status)) {
@@ -969,10 +976,10 @@
         return false;
     }
 
-    uint64_t snapshot_sectors = status.snapshot_size / kSectorSize;
-    if (snapshot_sectors * kSectorSize != status.snapshot_size) {
+    uint64_t snapshot_sectors = status.snapshot_size() / kSectorSize;
+    if (snapshot_sectors * kSectorSize != status.snapshot_size()) {
         LOG(ERROR) << "Snapshot " << name
-                   << " size is not sector aligned: " << status.snapshot_size;
+                   << " size is not sector aligned: " << status.snapshot_size();
         return false;
     }
 
@@ -1003,7 +1010,7 @@
                        << " sectors, got: " << outer_table[0].spec.length;
             return false;
         }
-        uint64_t expected_device_sectors = status.device_size / kSectorSize;
+        uint64_t expected_device_sectors = status.device_size() / kSectorSize;
         uint64_t actual_device_sectors = outer_table[0].spec.length + outer_table[1].spec.length;
         if (expected_device_sectors != actual_device_sectors) {
             LOG(ERROR) << "Outer device " << name << " should have " << expected_device_sectors
@@ -1289,7 +1296,7 @@
             return false;
         }
         // No live snapshot if merge is completed.
-        if (live_snapshot_status->state == SnapshotState::MergeCompleted) {
+        if (live_snapshot_status->state() == SnapshotState::MERGE_COMPLETED) {
             live_snapshot_status.reset();
         }
     } while (0);
@@ -1390,7 +1397,7 @@
                                     AutoDeviceList* created_devices, std::string* cow_name) {
     CHECK(lock);
     if (!EnsureImageManager()) return false;
-    CHECK(snapshot_status.cow_partition_size + snapshot_status.cow_file_size > 0);
+    CHECK(snapshot_status.cow_partition_size() + snapshot_status.cow_file_size() > 0);
     auto begin = std::chrono::steady_clock::now();
 
     std::string partition_name = params.GetPartitionName();
@@ -1400,7 +1407,7 @@
     auto& dm = DeviceMapper::Instance();
 
     // Map COW image if necessary.
-    if (snapshot_status.cow_file_size > 0) {
+    if (snapshot_status.cow_file_size() > 0) {
         auto remaining_time = GetRemainingTime(params.timeout_ms, begin);
         if (remaining_time.count() < 0) return false;
 
@@ -1411,7 +1418,7 @@
         created_devices->EmplaceBack<AutoUnmapImage>(images_.get(), cow_image_name);
 
         // If no COW partition exists, just return the image alone.
-        if (snapshot_status.cow_partition_size == 0) {
+        if (snapshot_status.cow_partition_size() == 0) {
             *cow_name = std::move(cow_image_name);
             LOG(INFO) << "Mapped COW image for " << partition_name << " at " << *cow_name;
             return true;
@@ -1421,7 +1428,7 @@
     auto remaining_time = GetRemainingTime(params.timeout_ms, begin);
     if (remaining_time.count() < 0) return false;
 
-    CHECK(snapshot_status.cow_partition_size > 0);
+    CHECK(snapshot_status.cow_partition_size() > 0);
 
     // Create the DmTable for the COW device. It is the DmTable of the COW partition plus
     // COW image device as the last extent.
@@ -1434,14 +1441,14 @@
         return false;
     }
     // If the COW image exists, append it as the last extent.
-    if (snapshot_status.cow_file_size > 0) {
+    if (snapshot_status.cow_file_size() > 0) {
         std::string cow_image_device;
         if (!dm.GetDeviceString(cow_image_name, &cow_image_device)) {
             LOG(ERROR) << "Cannot determine major/minor for: " << cow_image_name;
             return false;
         }
-        auto cow_partition_sectors = snapshot_status.cow_partition_size / kSectorSize;
-        auto cow_image_sectors = snapshot_status.cow_file_size / kSectorSize;
+        auto cow_partition_sectors = snapshot_status.cow_partition_size() / kSectorSize;
+        auto cow_image_sectors = snapshot_status.cow_file_size() / kSectorSize;
         table.Emplace<DmTargetLinear>(cow_partition_sectors, cow_image_sectors, cow_image_device,
                                       0);
     }
@@ -1602,101 +1609,38 @@
         return false;
     }
 
-    std::string contents;
-    if (!android::base::ReadFdToString(fd, &contents)) {
-        PLOG(ERROR) << "read failed: " << path;
-        return false;
-    }
-    auto pieces = android::base::Split(contents, " ");
-    if (pieces.size() != 7) {
-        LOG(ERROR) << "Invalid status line for snapshot: " << path;
+    if (!status->ParseFromFileDescriptor(fd.get())) {
+        PLOG(ERROR) << "Unable to parse " << path << " as SnapshotStatus";
         return false;
     }
 
-    if (pieces[0] == "none") {
-        status->state = SnapshotState::None;
-    } else if (pieces[0] == "created") {
-        status->state = SnapshotState::Created;
-    } else if (pieces[0] == "merging") {
-        status->state = SnapshotState::Merging;
-    } else if (pieces[0] == "merge-completed") {
-        status->state = SnapshotState::MergeCompleted;
-    } else {
-        LOG(ERROR) << "Unrecognized state " << pieces[0] << " for snapshot: " << name;
-        return false;
+    if (status->name() != name) {
+        LOG(WARNING) << "Found snapshot status named " << status->name() << " in " << path;
+        status->set_name(name);
     }
 
-    if (!android::base::ParseUint(pieces[1], &status->device_size)) {
-        LOG(ERROR) << "Invalid device size in status line for: " << path;
-        return false;
-    }
-    if (!android::base::ParseUint(pieces[2], &status->snapshot_size)) {
-        LOG(ERROR) << "Invalid snapshot size in status line for: " << path;
-        return false;
-    }
-    if (!android::base::ParseUint(pieces[3], &status->cow_partition_size)) {
-        LOG(ERROR) << "Invalid cow linear size in status line for: " << path;
-        return false;
-    }
-    if (!android::base::ParseUint(pieces[4], &status->cow_file_size)) {
-        LOG(ERROR) << "Invalid cow file size in status line for: " << path;
-        return false;
-    }
-    if (!android::base::ParseUint(pieces[5], &status->sectors_allocated)) {
-        LOG(ERROR) << "Invalid snapshot size in status line for: " << path;
-        return false;
-    }
-    if (!android::base::ParseUint(pieces[6], &status->metadata_sectors)) {
-        LOG(ERROR) << "Invalid snapshot size in status line for: " << path;
-        return false;
-    }
     return true;
 }
 
-std::string SnapshotManager::to_string(SnapshotState state) {
-    switch (state) {
-        case SnapshotState::None:
-            return "none";
-        case SnapshotState::Created:
-            return "created";
-        case SnapshotState::Merging:
-            return "merging";
-        case SnapshotState::MergeCompleted:
-            return "merge-completed";
-        default:
-            LOG(ERROR) << "Unknown snapshot state: " << (int)state;
-            return "unknown";
-    }
-}
-
-bool SnapshotManager::WriteSnapshotStatus(LockedFile* lock, const std::string& name,
-                                          const SnapshotStatus& status) {
+bool SnapshotManager::WriteSnapshotStatus(LockedFile* lock, const SnapshotStatus& status) {
     // The caller must take an exclusive lock to modify snapshots.
     CHECK(lock);
     CHECK(lock->lock_mode() == LOCK_EX);
+    CHECK(!status.name().empty());
 
-    auto path = GetSnapshotStatusFilePath(name);
-    unique_fd fd(open(path.c_str(), O_RDWR | O_CLOEXEC | O_NOFOLLOW | O_CREAT | O_SYNC, 0660));
+    auto path = GetSnapshotStatusFilePath(status.name());
+    unique_fd fd(
+            open(path.c_str(), O_RDWR | O_CLOEXEC | O_NOFOLLOW | O_CREAT | O_SYNC | O_TRUNC, 0660));
     if (fd < 0) {
         PLOG(ERROR) << "Open failed: " << path;
         return false;
     }
 
-    std::vector<std::string> pieces = {
-            to_string(status.state),
-            std::to_string(status.device_size),
-            std::to_string(status.snapshot_size),
-            std::to_string(status.cow_partition_size),
-            std::to_string(status.cow_file_size),
-            std::to_string(status.sectors_allocated),
-            std::to_string(status.metadata_sectors),
-    };
-    auto contents = android::base::Join(pieces, " ");
-
-    if (!android::base::WriteStringToFd(contents, fd)) {
-        PLOG(ERROR) << "write failed: " << path;
+    if (!status.SerializeToFileDescriptor(fd.get())) {
+        PLOG(ERROR) << "Unable to write SnapshotStatus to " << path;
         return false;
     }
+
     return true;
 }
 
@@ -1714,7 +1658,7 @@
 
 std::string SnapshotManager::GetSnapshotDeviceName(const std::string& snapshot_name,
                                                    const SnapshotStatus& status) {
-    if (status.device_size != status.snapshot_size) {
+    if (status.device_size() != status.snapshot_size()) {
         return GetSnapshotExtraDeviceName(snapshot_name);
     }
     return snapshot_name;
@@ -1884,11 +1828,11 @@
         }
 
         LOG(INFO) << "For partition " << target_partition->name()
-                  << ", device size = " << cow_creator_ret->snapshot_status.device_size
-                  << ", snapshot size = " << cow_creator_ret->snapshot_status.snapshot_size
+                  << ", device size = " << cow_creator_ret->snapshot_status.device_size()
+                  << ", snapshot size = " << cow_creator_ret->snapshot_status.snapshot_size()
                   << ", cow partition size = "
-                  << cow_creator_ret->snapshot_status.cow_partition_size
-                  << ", cow file size = " << cow_creator_ret->snapshot_status.cow_file_size;
+                  << cow_creator_ret->snapshot_status.cow_partition_size()
+                  << ", cow file size = " << cow_creator_ret->snapshot_status.cow_file_size();
 
         // Delete any existing snapshot before re-creating one.
         if (!DeleteSnapshot(lock, target_partition->name())) {
@@ -1899,9 +1843,9 @@
 
         // It is possible that the whole partition uses free space in super, and snapshot / COW
         // would not be needed. In this case, skip the partition.
-        bool needs_snapshot = cow_creator_ret->snapshot_status.snapshot_size > 0;
-        bool needs_cow = (cow_creator_ret->snapshot_status.cow_partition_size +
-                          cow_creator_ret->snapshot_status.cow_file_size) > 0;
+        bool needs_snapshot = cow_creator_ret->snapshot_status.snapshot_size() > 0;
+        bool needs_cow = (cow_creator_ret->snapshot_status.cow_partition_size() +
+                          cow_creator_ret->snapshot_status.cow_file_size()) > 0;
         CHECK(needs_snapshot == needs_cow);
 
         if (!needs_snapshot) {
@@ -1911,17 +1855,17 @@
         }
 
         // Store these device sizes to snapshot status file.
-        if (!CreateSnapshot(lock, target_partition->name(), cow_creator_ret->snapshot_status)) {
+        if (!CreateSnapshot(lock, &cow_creator_ret->snapshot_status)) {
             return false;
         }
         created_devices->EmplaceBack<AutoDeleteSnapshot>(this, lock, target_partition->name());
 
         // Create the COW partition. That is, use any remaining free space in super partition before
         // creating the COW images.
-        if (cow_creator_ret->snapshot_status.cow_partition_size > 0) {
-            CHECK(cow_creator_ret->snapshot_status.cow_partition_size % kSectorSize == 0)
+        if (cow_creator_ret->snapshot_status.cow_partition_size() > 0) {
+            CHECK(cow_creator_ret->snapshot_status.cow_partition_size() % kSectorSize == 0)
                     << "cow_partition_size == "
-                    << cow_creator_ret->snapshot_status.cow_partition_size
+                    << cow_creator_ret->snapshot_status.cow_partition_size()
                     << " is not a multiple of sector size " << kSectorSize;
             auto cow_partition = target_metadata->AddPartition(GetCowName(target_partition->name()),
                                                                kCowGroupName, 0 /* flags */);
@@ -1930,10 +1874,10 @@
             }
 
             if (!target_metadata->ResizePartition(
-                        cow_partition, cow_creator_ret->snapshot_status.cow_partition_size,
+                        cow_partition, cow_creator_ret->snapshot_status.cow_partition_size(),
                         cow_creator_ret->cow_partition_usable_regions)) {
                 LOG(ERROR) << "Cannot create COW partition on metadata with size "
-                           << cow_creator_ret->snapshot_status.cow_partition_size;
+                           << cow_creator_ret->snapshot_status.cow_partition_size();
                 return false;
             }
             // Only the in-memory target_metadata is modified; nothing to clean up if there is an
@@ -1941,7 +1885,7 @@
         }
 
         // Create the backing COW image if necessary.
-        if (cow_creator_ret->snapshot_status.cow_file_size > 0) {
+        if (cow_creator_ret->snapshot_status.cow_file_size() > 0) {
             if (!CreateCowImage(lock, target_partition->name())) {
                 return false;
             }
@@ -1978,7 +1922,7 @@
         }
 
         auto it = all_snapshot_status.find(target_partition->name());
-        CHECK(it != all_snapshot_status.end()) << target_partition->name();
+        if (it == all_snapshot_status.end()) continue;
         cow_params.partition_name = target_partition->name();
         std::string cow_name;
         if (!MapCowDevices(lock, cow_params, it->second, &created_devices_for_cow, &cow_name)) {
@@ -2049,13 +1993,13 @@
             ok = false;
             continue;
         }
-        ss << "    state: " << to_string(status.state) << std::endl;
-        ss << "    device size (bytes): " << status.device_size << std::endl;
-        ss << "    snapshot size (bytes): " << status.snapshot_size << std::endl;
-        ss << "    cow partition size (bytes): " << status.cow_partition_size << std::endl;
-        ss << "    cow file size (bytes): " << status.cow_file_size << std::endl;
-        ss << "    allocated sectors: " << status.sectors_allocated << std::endl;
-        ss << "    metadata sectors: " << status.metadata_sectors << std::endl;
+        ss << "    state: " << SnapshotState_Name(status.state()) << std::endl;
+        ss << "    device size (bytes): " << status.device_size() << std::endl;
+        ss << "    snapshot size (bytes): " << status.snapshot_size() << std::endl;
+        ss << "    cow partition size (bytes): " << status.cow_partition_size() << std::endl;
+        ss << "    cow file size (bytes): " << status.cow_file_size() << std::endl;
+        ss << "    allocated sectors: " << status.sectors_allocated() << std::endl;
+        ss << "    metadata sectors: " << status.metadata_sectors() << std::endl;
     }
     os << ss.rdbuf();
     return ok;
diff --git a/fs_mgr/libsnapshot/snapshot_test.cpp b/fs_mgr/libsnapshot/snapshot_test.cpp
index f3994c1..aea12be 100644
--- a/fs_mgr/libsnapshot/snapshot_test.cpp
+++ b/fs_mgr/libsnapshot/snapshot_test.cpp
@@ -33,6 +33,7 @@
 #include <liblp/builder.h>
 #include <storage_literals/storage_literals.h>
 
+#include <android/snapshot/snapshot.pb.h>
 #include "test_helpers.h"
 #include "utility.h"
 
@@ -202,9 +203,9 @@
                     .block_device = fake_super,
                     .metadata = metadata.get(),
                     .partition = &partition,
-                    .device_name = GetPartitionName(partition) + "-base",
                     .force_writable = true,
                     .timeout_ms = 10s,
+                    .device_name = GetPartitionName(partition) + "-base",
             };
             std::string ignore_path;
             if (!CreateLogicalPartition(params, &ignore_path)) {
@@ -272,10 +273,12 @@
     ASSERT_TRUE(AcquireLock());
 
     static const uint64_t kDeviceSize = 1024 * 1024;
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), "test-snapshot",
-                                   {.device_size = kDeviceSize,
-                                    .snapshot_size = kDeviceSize,
-                                    .cow_file_size = kDeviceSize}));
+    SnapshotStatus status;
+    status.set_name("test-snapshot");
+    status.set_device_size(kDeviceSize);
+    status.set_snapshot_size(kDeviceSize);
+    status.set_cow_file_size(kDeviceSize);
+    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
     ASSERT_TRUE(CreateCowImage("test-snapshot"));
 
     std::vector<std::string> snapshots;
@@ -285,11 +288,11 @@
 
     // Scope so delete can re-acquire the snapshot file lock.
     {
-        SnapshotManager::SnapshotStatus status;
+        SnapshotStatus status;
         ASSERT_TRUE(sm->ReadSnapshotStatus(lock_.get(), "test-snapshot", &status));
-        ASSERT_EQ(status.state, SnapshotManager::SnapshotState::Created);
-        ASSERT_EQ(status.device_size, kDeviceSize);
-        ASSERT_EQ(status.snapshot_size, kDeviceSize);
+        ASSERT_EQ(status.state(), SnapshotState::CREATED);
+        ASSERT_EQ(status.device_size(), kDeviceSize);
+        ASSERT_EQ(status.snapshot_size(), kDeviceSize);
     }
 
     ASSERT_TRUE(sm->UnmapSnapshot(lock_.get(), "test-snapshot"));
@@ -301,10 +304,12 @@
     ASSERT_TRUE(AcquireLock());
 
     static const uint64_t kDeviceSize = 1024 * 1024;
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), "test-snapshot",
-                                   {.device_size = kDeviceSize,
-                                    .snapshot_size = kDeviceSize,
-                                    .cow_file_size = kDeviceSize}));
+    SnapshotStatus status;
+    status.set_name("test-snapshot");
+    status.set_device_size(kDeviceSize);
+    status.set_snapshot_size(kDeviceSize);
+    status.set_cow_file_size(kDeviceSize);
+    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
     ASSERT_TRUE(CreateCowImage("test-snapshot"));
 
     std::string base_device;
@@ -324,10 +329,12 @@
 
     static const uint64_t kSnapshotSize = 1024 * 1024;
     static const uint64_t kDeviceSize = 1024 * 1024 * 2;
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), "test-snapshot",
-                                   {.device_size = kDeviceSize,
-                                    .snapshot_size = kSnapshotSize,
-                                    .cow_file_size = kSnapshotSize}));
+    SnapshotStatus status;
+    status.set_name("test-snapshot");
+    status.set_device_size(kDeviceSize);
+    status.set_snapshot_size(kSnapshotSize);
+    status.set_cow_file_size(kSnapshotSize);
+    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
     ASSERT_TRUE(CreateCowImage("test-snapshot"));
 
     std::string base_device;
@@ -377,10 +384,12 @@
     ASSERT_TRUE(CreatePartition("test_partition_a", kDeviceSize));
     ASSERT_TRUE(MapUpdatePartitions());
     ASSERT_TRUE(dm_.GetDmDevicePathByName("test_partition_b-base", &base_device));
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), "test_partition_b",
-                                   {.device_size = kDeviceSize,
-                                    .snapshot_size = kDeviceSize,
-                                    .cow_file_size = kDeviceSize}));
+    SnapshotStatus status;
+    status.set_name("test_partition_b");
+    status.set_device_size(kDeviceSize);
+    status.set_snapshot_size(kDeviceSize);
+    status.set_cow_file_size(kDeviceSize);
+    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
     ASSERT_TRUE(CreateCowImage("test_partition_b"));
     ASSERT_TRUE(MapCowImage("test_partition_b", 10s, &cow_device));
     ASSERT_TRUE(sm->MapSnapshot(lock_.get(), "test_partition_b", base_device, cow_device, 10s,
@@ -436,10 +445,12 @@
     ASSERT_TRUE(AcquireLock());
 
     static const uint64_t kDeviceSize = 1024 * 1024;
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), "test-snapshot",
-                                   {.device_size = kDeviceSize,
-                                    .snapshot_size = kDeviceSize,
-                                    .cow_file_size = kDeviceSize}));
+    SnapshotStatus status;
+    status.set_name("test-snapshot");
+    status.set_device_size(kDeviceSize);
+    status.set_snapshot_size(kDeviceSize);
+    status.set_cow_file_size(kDeviceSize);
+    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
     ASSERT_TRUE(CreateCowImage("test-snapshot"));
 
     std::string base_device, cow_device, snap_device;
@@ -492,10 +503,12 @@
 
     ASSERT_TRUE(CreatePartition("test_partition_a", kDeviceSize));
     ASSERT_TRUE(MapUpdatePartitions());
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), "test_partition_b",
-                                   {.device_size = kDeviceSize,
-                                    .snapshot_size = kDeviceSize,
-                                    .cow_file_size = kDeviceSize}));
+    SnapshotStatus status;
+    status.set_name("test_partition_b");
+    status.set_device_size(kDeviceSize);
+    status.set_snapshot_size(kDeviceSize);
+    status.set_cow_file_size(kDeviceSize);
+    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
     ASSERT_TRUE(CreateCowImage("test_partition_b"));
 
     // Simulate a reboot into the new slot.
@@ -511,9 +524,8 @@
     ASSERT_TRUE(AcquireLock());
 
     // Validate that we have a snapshot device.
-    SnapshotManager::SnapshotStatus status;
     ASSERT_TRUE(init->ReadSnapshotStatus(lock_.get(), "test_partition_b", &status));
-    ASSERT_EQ(status.state, SnapshotManager::SnapshotState::Created);
+    ASSERT_EQ(status.state(), SnapshotState::CREATED);
 
     DeviceMapper::TargetInfo target;
     auto dm_name = init->GetSnapshotDeviceName("test_partition_b", status);
@@ -528,10 +540,12 @@
 
     ASSERT_TRUE(CreatePartition("test_partition_a", kDeviceSize));
     ASSERT_TRUE(MapUpdatePartitions());
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), "test_partition_b",
-                                   {.device_size = kDeviceSize,
-                                    .snapshot_size = kDeviceSize,
-                                    .cow_file_size = kDeviceSize}));
+    SnapshotStatus status;
+    status.set_name("test_partition_b");
+    status.set_device_size(kDeviceSize);
+    status.set_snapshot_size(kDeviceSize);
+    status.set_cow_file_size(kDeviceSize);
+    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
     ASSERT_TRUE(CreateCowImage("test_partition_b"));
 
     // Simulate a reboot into the new slot.
@@ -550,7 +564,6 @@
 
     ASSERT_TRUE(AcquireLock());
 
-    SnapshotManager::SnapshotStatus status;
     ASSERT_TRUE(init->ReadSnapshotStatus(lock_.get(), "test_partition_b", &status));
 
     // We should not get a snapshot device now.
@@ -570,10 +583,12 @@
 
     ASSERT_TRUE(CreatePartition("test_partition_a", kDeviceSize));
     ASSERT_TRUE(MapUpdatePartitions());
-    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), "test_partition_b",
-                                   {.device_size = kDeviceSize,
-                                    .snapshot_size = kDeviceSize,
-                                    .cow_file_size = kDeviceSize}));
+    SnapshotStatus status;
+    status.set_name("test_partition_b");
+    status.set_device_size(kDeviceSize);
+    status.set_snapshot_size(kDeviceSize);
+    status.set_cow_file_size(kDeviceSize);
+    ASSERT_TRUE(sm->CreateSnapshot(lock_.get(), &status));
     ASSERT_TRUE(CreateCowImage("test_partition_b"));
 
     // Simulate a reboot into the new slot.
@@ -699,11 +714,11 @@
         }
         auto local_lock = std::move(lock_);
 
-        SnapshotManager::SnapshotStatus status;
+        SnapshotStatus status;
         if (!sm->ReadSnapshotStatus(local_lock.get(), name, &status)) {
             return std::nullopt;
         }
-        return status.snapshot_size;
+        return status.snapshot_size();
     }
 
     AssertionResult UnmapAll() {
@@ -869,8 +884,9 @@
     {
         ASSERT_TRUE(AcquireLock());
         auto local_lock = std::move(lock_);
-        ASSERT_TRUE(sm->WriteSnapshotStatus(local_lock.get(), "sys_b",
-                                            SnapshotManager::SnapshotStatus{}));
+        SnapshotStatus status;
+        status.set_name("sys_b");
+        ASSERT_TRUE(sm->WriteSnapshotStatus(local_lock.get(), status));
         ASSERT_TRUE(image_manager_->CreateBackingImage("sys_b-cow-img", 1_MiB,
                                                        IImageManager::CREATE_IMAGE_DEFAULT));
     }
diff --git a/fs_mgr/libsnapshot/utility.h b/fs_mgr/libsnapshot/utility.h
index 75c694c..3051184 100644
--- a/fs_mgr/libsnapshot/utility.h
+++ b/fs_mgr/libsnapshot/utility.h
@@ -27,6 +27,9 @@
 namespace android {
 namespace snapshot {
 
+// Unit is sectors, this is a 4K chunk.
+static constexpr uint32_t kSnapshotChunkSize = 8;
+
 struct AutoDevice {
     virtual ~AutoDevice(){};
     void Release();
diff --git a/fs_mgr/tests/adb-remount-test.sh b/fs_mgr/tests/adb-remount-test.sh
index f445703..4226e95 100755
--- a/fs_mgr/tests/adb-remount-test.sh
+++ b/fs_mgr/tests/adb-remount-test.sh
@@ -38,6 +38,8 @@
 
 EMPTY=""
 SPACE=" "
+# Line up wrap to [  XXXXXXX ] messages.
+INDENT="             "
 # A _real_ embedded tab character
 TAB="`echo | tr '\n' '\t'`"
 # A _real_ embedded escape character
@@ -159,8 +161,7 @@
     return
   fi
   echo "${ORANGE}[  WARNING ]${NORMAL} unlabeled sepolicy violations:" >&2
-  echo "${L}" |
-    sed 's/^/             /' >&2
+  echo "${L}" | sed "s/^/${INDENT}/" >&2
 }
 
 [ "USAGE: get_property <prop>
@@ -639,10 +640,10 @@
 *}" ]; then
       echo "${prefix} expected \"${lval}\""
       echo "${prefix} got \"${rval}\"" |
-        sed ': again
+        sed ": again
              N
-             s/\(\n\)\([^ ]\)/\1             \2/
-             t again'
+             s/\(\n\)\([^ ]\)/\1${INDENT}\2/
+             t again"
       if [ -n "${*}" ] ; then
         echo "${prefix} ${*}"
       fi
@@ -657,10 +658,10 @@
       if [ `echo ${lval}${rval}${*} | wc -c` -gt 60 -o "${rval}" != "${rval% *}" ]; then
         echo "${prefix} ok \"${lval}\""
         echo "       = \"${rval}\"" |
-          sed ': again
+          sed ": again
                N
-               s/\(\n\)\([^ ]\)/\1          \2/
-               t again'
+               s/\(\n\)\([^ ]\)/\1${INDENT}\2/
+               t again"
         if [ -n "${*}" ] ; then
           echo "${prefix} ${*}"
         fi
@@ -955,13 +956,24 @@
   echo "${GREEN}[ RUN      ]${NORMAL} Testing adb shell su root remount -R command" >&2
 
   avc_check
-  adb_su remount -R system </dev/null || true
+  T=`adb_date`
+  adb_su remount -R system </dev/null
+  err=${?}
+  if [ "${err}" != 0 ]; then
+    echo "${ORANGE}[  WARNING ]${NORMAL} adb shell su root remount -R system = ${err}, likely did not reboot!" >&2
+    T="-t ${T}"
+  else
+    # Rebooted, logcat will be meaningless, and last logcat will likely be clear
+    T=""
+  fi
   sleep 2
   adb_wait ${ADB_WAIT} ||
-    die "waiting for device after remount -R `usb_status`"
+    die "waiting for device after adb shell su root remount -R system `usb_status`"
   if [ "orange" != "`get_property ro.boot.verifiedbootstate`" -o \
        "2" = "`get_property partition.system.verified`" ]; then
-    die "remount -R command failed"
+    die ${T} "remount -R command failed
+${INDENT}ro.boot.verifiedbootstate=\"`get_property ro.boot.verifiedbootstate`\"
+${INDENT}partition.system.verified=\"`get_property partition.system.verified`\""
   fi
 
   echo "${GREEN}[       OK ]${NORMAL} adb shell su root remount -R command" >&2
@@ -1643,15 +1655,24 @@
 if ${overlayfs_supported}; then
   echo "${GREEN}[ RUN      ]${NORMAL} test 'adb remount -R'" >&2
   avc_check
-  adb_root &&
-    adb remount -R &&
-    adb_wait ${ADB_WAIT} ||
-    die "adb remount -R"
+  adb_root ||
+    die "adb root in preparation for adb remount -R"
+  T=`adb_date`
+  adb remount -R
+  err=${?}
+  if [ "${err}" != 0 ]; then
+    die -t ${T} "adb remount -R = ${err}"
+  fi
+  sleep 2
+  adb_wait ${ADB_WAIT} ||
+    die "waiting for device after adb remount -R `usb_status`"
   if [ "orange" != "`get_property ro.boot.verifiedbootstate`" -o \
        "2" = "`get_property partition.system.verified`" ] &&
      [ -n "`get_property ro.boot.verifiedbootstate`" -o \
        -n "`get_property partition.system.verified`" ]; then
-    die "remount -R command failed to disable verity"
+    die "remount -R command failed to disable verity
+${INDENT}ro.boot.verifiedbootstate=\"`get_property ro.boot.verifiedbootstate`\"
+${INDENT}partition.system.verified=\"`get_property partition.system.verified`\""
   fi
 
   echo "${GREEN}[       OK ]${NORMAL} 'adb remount -R' command" >&2
diff --git a/fs_mgr/tests/fs_mgr_test.cpp b/fs_mgr/tests/fs_mgr_test.cpp
index 6d87594..a7ea817 100644
--- a/fs_mgr/tests/fs_mgr_test.cpp
+++ b/fs_mgr/tests/fs_mgr_test.cpp
@@ -467,6 +467,7 @@
     }
     EXPECT_EQ("aes-256-xts", entry->file_contents_mode);
     EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
     EXPECT_EQ("", entry->key_loc);
 }
 
@@ -682,6 +683,7 @@
     EXPECT_EQ("/dir/key", entry->key_loc);
     EXPECT_EQ("aes-256-xts", entry->file_contents_mode);
     EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
 }
 
 TEST(fs_mgr, ReadFstabFromFile_FsMgrOptions_FileEncryption) {
@@ -698,14 +700,18 @@
 source none7       swap   defaults      fileencryption=ice:aes-256-cts
 source none8       swap   defaults      fileencryption=ice:aes-256-heh
 source none9       swap   defaults      fileencryption=ice:adiantum
-source none10      swap   defaults      fileencryption=ice:adiantum:
+source none10      swap   defaults      fileencryption=aes-256-xts:aes-256-cts:v1
+source none11      swap   defaults      fileencryption=aes-256-xts:aes-256-cts:v2
+source none12      swap   defaults      fileencryption=aes-256-xts:aes-256-cts:v2:
+source none13      swap   defaults      fileencryption=aes-256-xts:aes-256-cts:blah
+source none14      swap   defaults      fileencryption=aes-256-xts:aes-256-cts:vblah
 )fs";
 
     ASSERT_TRUE(android::base::WriteStringToFile(fstab_contents, tf.path));
 
     Fstab fstab;
     EXPECT_TRUE(ReadFstabFromFile(tf.path, &fstab));
-    ASSERT_EQ(11U, fstab.size());
+    ASSERT_EQ(15U, fstab.size());
 
     FstabEntry::FsMgrFlags flags = {};
     flags.file_encryption = true;
@@ -715,66 +721,105 @@
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("", entry->file_contents_mode);
     EXPECT_EQ("", entry->file_names_mode);
+    EXPECT_EQ(0, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none1", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("aes-256-xts", entry->file_contents_mode);
     EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none2", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("aes-256-xts", entry->file_contents_mode);
     EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none3", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("adiantum", entry->file_contents_mode);
     EXPECT_EQ("adiantum", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none4", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("adiantum", entry->file_contents_mode);
     EXPECT_EQ("aes-256-heh", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none5", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("ice", entry->file_contents_mode);
     EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none6", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("ice", entry->file_contents_mode);
     EXPECT_EQ("", entry->file_names_mode);
+    EXPECT_EQ(0, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none7", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("ice", entry->file_contents_mode);
     EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none8", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("ice", entry->file_contents_mode);
     EXPECT_EQ("aes-256-heh", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none9", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("ice", entry->file_contents_mode);
     EXPECT_EQ("adiantum", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
 
     entry++;
     EXPECT_EQ("none10", entry->mount_point);
     EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
+    EXPECT_EQ("aes-256-xts", entry->file_contents_mode);
+    EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(1, entry->file_policy_version);
+
+    entry++;
+    EXPECT_EQ("none11", entry->mount_point);
+    EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
+    EXPECT_EQ("aes-256-xts", entry->file_contents_mode);
+    EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(2, entry->file_policy_version);
+
+    entry++;
+    EXPECT_EQ("none12", entry->mount_point);
+    EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
     EXPECT_EQ("", entry->file_contents_mode);
     EXPECT_EQ("", entry->file_names_mode);
+    EXPECT_EQ(0, entry->file_policy_version);
+
+    entry++;
+    EXPECT_EQ("none13", entry->mount_point);
+    EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
+    EXPECT_EQ("aes-256-xts", entry->file_contents_mode);
+    EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(0, entry->file_policy_version);
+
+    entry++;
+    EXPECT_EQ("none14", entry->mount_point);
+    EXPECT_TRUE(CompareFlags(flags, entry->fs_mgr_flags));
+    EXPECT_EQ("aes-256-xts", entry->file_contents_mode);
+    EXPECT_EQ("aes-256-cts", entry->file_names_mode);
+    EXPECT_EQ(0, entry->file_policy_version);
 }
 
 TEST(fs_mgr, ReadFstabFromFile_FsMgrOptions_MaxCompStreams) {
diff --git a/init/Android.bp b/init/Android.bp
index b601075..9b2ddc0 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -76,7 +76,6 @@
         "libbase",
         "libbootloader_message",
         "libcutils",
-        "libcrypto",
         "libdl",
         "libext4_utils",
         "libfs_mgr",
diff --git a/init/Android.mk b/init/Android.mk
index 62e452f..8fc44da 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -113,6 +113,7 @@
     libbacktrace \
     libmodprobe \
     libext2_uuid \
+    libprotobuf-cpp-lite \
     libsnapshot_nobinder \
 
 LOCAL_SANITIZE := signed-integer-overflow
diff --git a/init/action_parser.cpp b/init/action_parser.cpp
index 9736824..a8e1e09 100644
--- a/init/action_parser.cpp
+++ b/init/action_parser.cpp
@@ -16,11 +16,14 @@
 
 #include "action_parser.h"
 
+#include <ctype.h>
+
 #include <android-base/properties.h>
 #include <android-base/strings.h>
 
 #if defined(__ANDROID__)
 #include "property_service.h"
+#include "selinux.h"
 #else
 #include "host_init_stubs.h"
 #endif
@@ -77,6 +80,17 @@
     return {};
 }
 
+Result<void> ValidateEventTrigger(const std::string& event_trigger) {
+    if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
+        for (const char& c : event_trigger) {
+            if (c != '_' && c != '-' && !std::isalnum(c)) {
+                return Error() << "Illegal character '" << c << "' in '" << event_trigger << "'";
+            }
+        }
+    }
+    return {};
+}
+
 Result<void> ParseTriggers(const std::vector<std::string>& args, Subcontext* subcontext,
                            std::string* event_trigger,
                            std::map<std::string, std::string>* property_triggers) {
@@ -103,6 +117,9 @@
             if (!event_trigger->empty()) {
                 return Error() << "multiple event triggers are not allowed";
             }
+            if (auto result = ValidateEventTrigger(args[i]); !result) {
+                return result;
+            }
 
             *event_trigger = args[i];
         }
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 42211b2..2f2ead0 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -138,7 +138,14 @@
     if (!write_bootloader_message(options, &err)) {
         return Error() << "Failed to set bootloader message: " << err;
     }
-    property_set("sys.powerctl", "reboot,recovery");
+    // This function should only be reached from init and not from vendor_init, and we want to
+    // immediately trigger reboot instead of relaying through property_service.  Older devices may
+    // still have paths that reach here from vendor_init, so we keep the property_set as a fallback.
+    if (getpid() == 1) {
+        TriggerShutdown("reboot,recovery");
+    } else {
+        property_set("sys.powerctl", "reboot,recovery");
+    }
     return {};
 }
 
diff --git a/init/fscrypt_init_extensions.cpp b/init/fscrypt_init_extensions.cpp
index bd23e31..bbebbe8 100644
--- a/init/fscrypt_init_extensions.cpp
+++ b/init/fscrypt_init_extensions.cpp
@@ -28,6 +28,7 @@
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/parseint.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <cutils/properties.h>
@@ -163,33 +164,59 @@
     return err;
 }
 
+static int parse_encryption_options_string(const std::string& options_string,
+                                           std::string* contents_mode_ret,
+                                           std::string* filenames_mode_ret,
+                                           int* policy_version_ret) {
+    auto parts = android::base::Split(options_string, ":");
+
+    if (parts.size() != 3) {
+        return -1;
+    }
+
+    *contents_mode_ret = parts[0];
+    *filenames_mode_ret = parts[1];
+    if (!android::base::StartsWith(parts[2], 'v') ||
+        !android::base::ParseInt(&parts[2][1], policy_version_ret)) {
+        return -1;
+    }
+
+    return 0;
+}
+
+// Set an encryption policy on the given directory.  The policy (key reference
+// and encryption options) to use is read from files that were written by vold.
 static int set_policy_on(const std::string& ref_basename, const std::string& dir) {
     std::string ref_filename = std::string("/data") + ref_basename;
-    std::string policy;
-    if (!android::base::ReadFileToString(ref_filename, &policy)) {
+    std::string key_ref;
+    if (!android::base::ReadFileToString(ref_filename, &key_ref)) {
         LOG(ERROR) << "Unable to read system policy to set on " << dir;
         return -1;
     }
 
-    auto type_filename = std::string("/data") + fscrypt_key_mode;
-    std::string modestring;
-    if (!android::base::ReadFileToString(type_filename, &modestring)) {
-        LOG(ERROR) << "Cannot read mode";
+    auto options_filename = std::string("/data") + fscrypt_key_mode;
+    std::string options_string;
+    if (!android::base::ReadFileToString(options_filename, &options_string)) {
+        LOG(ERROR) << "Cannot read encryption options string";
+        return -1;
     }
 
-    std::vector<std::string> modes = android::base::Split(modestring, ":");
+    std::string contents_mode;
+    std::string filenames_mode;
+    int policy_version = 0;
 
-    if (modes.size() < 1 || modes.size() > 2) {
-        LOG(ERROR) << "Invalid encryption mode string: " << modestring;
+    if (parse_encryption_options_string(options_string, &contents_mode, &filenames_mode,
+                                        &policy_version)) {
+        LOG(ERROR) << "Invalid encryption options string: " << options_string;
         return -1;
     }
 
     int result =
-            fscrypt_policy_ensure(dir.c_str(), policy.c_str(), policy.length(), modes[0].c_str(),
-                                  modes.size() >= 2 ? modes[1].c_str() : "aes-256-cts");
+            fscrypt_policy_ensure(dir.c_str(), key_ref.c_str(), key_ref.length(),
+                                  contents_mode.c_str(), filenames_mode.c_str(), policy_version);
     if (result) {
         LOG(ERROR) << android::base::StringPrintf("Setting %02x%02x%02x%02x policy on %s failed!",
-                                                  policy[0], policy[1], policy[2], policy[3],
+                                                  key_ref[0], key_ref[1], key_ref[2], key_ref[3],
                                                   dir.c_str());
         return -1;
     }
diff --git a/init/host_init_stubs.h b/init/host_init_stubs.h
index e3068b2..5dd5cf1 100644
--- a/init/host_init_stubs.h
+++ b/init/host_init_stubs.h
@@ -35,7 +35,7 @@
 namespace init {
 
 // init.h
-inline void EnterShutdown(const std::string&) {
+inline void TriggerShutdown(const std::string&) {
     abort();
 }
 
@@ -55,7 +55,7 @@
 
 // reboot_utils.h
 inline void SetFatalRebootTarget() {}
-inline void __attribute__((noreturn)) InitFatalReboot() {
+inline void __attribute__((noreturn)) InitFatalReboot(int signal_number) {
     abort();
 }
 
diff --git a/init/init.cpp b/init/init.cpp
index ad31fa0..f775d8f 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -98,7 +98,6 @@
 static std::unique_ptr<Timer> waiting_for_prop(nullptr);
 static std::string wait_prop_name;
 static std::string wait_prop_value;
-static bool shutting_down;
 static std::string shutdown_command;
 static bool do_shutdown = false;
 static bool load_debug_prop = false;
@@ -180,7 +179,7 @@
     waiting_for_prop.reset();
 }
 
-void EnterShutdown(const std::string& command) {
+void TriggerShutdown(const std::string& command) {
     // We can't call HandlePowerctlMessage() directly in this function,
     // because it modifies the contents of the action queue, which can cause the action queue
     // to get into a bad state if this function is called from a command being executed by the
@@ -198,7 +197,7 @@
     // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific
     // commands to be executed.
     if (name == "sys.powerctl") {
-        EnterShutdown(value);
+        TriggerShutdown(value);
     }
 
     if (property_triggers_enabled) ActionManager::GetInstance().QueuePropertyChange(name, value);
@@ -624,7 +623,15 @@
     auto init_message = InitMessage{};
     init_message.set_stop_sending_messages(true);
     if (auto result = SendMessage(property_fd, init_message); !result) {
-        LOG(ERROR) << "Failed to send load persistent properties message: " << result.error();
+        LOG(ERROR) << "Failed to send 'stop sending messages' message: " << result.error();
+    }
+}
+
+void SendStartSendingMessagesMessage() {
+    auto init_message = InitMessage{};
+    init_message.set_start_sending_messages(true);
+    if (auto result = SendMessage(property_fd, init_message); !result) {
+        LOG(ERROR) << "Failed to send 'start sending messages' message: " << result.error();
     }
 }
 
@@ -811,18 +818,16 @@
         // By default, sleep until something happens.
         auto epoll_timeout = std::optional<std::chrono::milliseconds>{};
 
-        if (do_shutdown && !shutting_down) {
+        if (do_shutdown && !IsShuttingDown()) {
             do_shutdown = false;
-            if (HandlePowerctlMessage(shutdown_command)) {
-                shutting_down = true;
-            }
+            HandlePowerctlMessage(shutdown_command);
         }
 
         if (!(waiting_for_prop || Service::is_exec_service_running())) {
             am.ExecuteOneCommand();
         }
         if (!(waiting_for_prop || Service::is_exec_service_running())) {
-            if (!shutting_down) {
+            if (!IsShuttingDown()) {
                 auto next_process_action_time = HandleProcessActions();
 
                 // If there's a process that needs restarting, wake up in time for that.
diff --git a/init/init.h b/init/init.h
index 61fb110..d884a94 100644
--- a/init/init.h
+++ b/init/init.h
@@ -31,7 +31,7 @@
 Parser CreateParser(ActionManager& action_manager, ServiceList& service_list);
 Parser CreateServiceOnlyParser(ServiceList& service_list);
 
-void EnterShutdown(const std::string& command);
+void TriggerShutdown(const std::string& command);
 
 bool start_waiting_for_property(const char *name, const char *value);
 
@@ -41,6 +41,7 @@
 
 void SendLoadPersistentPropertiesMessage();
 void SendStopSendingMessagesMessage();
+void SendStartSendingMessagesMessage();
 
 int SecondStageMain(int argc, char** argv);
 
diff --git a/init/init_test.cpp b/init/init_test.cpp
index 315d584..9f63e4f 100644
--- a/init/init_test.cpp
+++ b/init/init_test.cpp
@@ -93,6 +93,26 @@
     EXPECT_TRUE(expect_true);
 }
 
+TEST(init, WrongEventTrigger) {
+    std::string init_script =
+            R"init(
+on boot:
+pass_test
+)init";
+
+    TemporaryFile tf;
+    ASSERT_TRUE(tf.fd != -1);
+    ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
+
+    ActionManager am;
+
+    Parser parser;
+    parser.AddSectionParser("on", std::make_unique<ActionParser>(&am, nullptr));
+
+    ASSERT_TRUE(parser.ParseConfig(tf.path));
+    ASSERT_EQ(1u, parser.parse_error_count());
+}
+
 TEST(init, EventTriggerOrder) {
     std::string init_script =
         R"init(
diff --git a/init/property_service.cpp b/init/property_service.cpp
index f5d1143..c6bbc14 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -93,6 +93,7 @@
 
 static int property_set_fd = -1;
 static int init_socket = -1;
+static bool accept_messages = false;
 
 static PropertyInfoAreaFile property_info_area;
 
@@ -211,7 +212,7 @@
     }
     // If init hasn't started its main loop, then it won't be handling property changed messages
     // anyway, so there's no need to try to send them.
-    if (init_socket != -1) {
+    if (accept_messages) {
         SendPropertyChanged(name, value);
     }
     return PROP_SUCCESS;
@@ -389,7 +390,7 @@
 
 static uint32_t SendControlMessage(const std::string& msg, const std::string& name, pid_t pid,
                                    SocketConnection* socket, std::string* error) {
-    if (init_socket == -1) {
+    if (!accept_messages) {
         *error = "Received control message after shutdown, ignoring";
         return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
     }
@@ -963,6 +964,10 @@
         // Don't check for failure here, so we always have a sane list of properties.
         // E.g. In case of recovery, the vendor partition will not have mounted and we
         // still need the system / platform properties to function.
+        if (access("/system_ext/etc/selinux/system_ext_property_contexts", R_OK) != -1) {
+            LoadPropertyInfoFromFile("/system_ext/etc/selinux/system_ext_property_contexts",
+                                     &property_infos);
+        }
         if (!LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",
                                       &property_infos)) {
             // Fallback to nonplat_* if vendor_* doesn't exist.
@@ -980,6 +985,7 @@
         if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {
             return;
         }
+        LoadPropertyInfoFromFile("/system_ext_property_contexts", &property_infos);
         if (!LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos)) {
             // Fallback to nonplat_* if vendor_* doesn't exist.
             LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos);
@@ -1030,7 +1036,11 @@
             break;
         }
         case InitMessage::kStopSendingMessages: {
-            init_socket = -1;
+            accept_messages = false;
+            break;
+        }
+        case InitMessage::kStartSendingMessages: {
+            accept_messages = true;
             break;
         }
         default:
@@ -1073,6 +1083,7 @@
     }
     *epoll_socket = sockets[0];
     init_socket = sockets[1];
+    accept_messages = true;
 
     if (auto result = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
                                    false, 0666, 0, 0, {})) {
diff --git a/init/property_service.proto b/init/property_service.proto
index ea454d4..08268d9 100644
--- a/init/property_service.proto
+++ b/init/property_service.proto
@@ -40,5 +40,6 @@
     oneof msg {
         bool load_persistent_properties = 1;
         bool stop_sending_messages = 2;
+        bool start_sending_messages = 3;
     };
 }
diff --git a/init/reboot.cpp b/init/reboot.cpp
index 30836d2..d77b975 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -22,6 +22,7 @@
 #include <linux/loop.h>
 #include <mntent.h>
 #include <semaphore.h>
+#include <stdlib.h>
 #include <sys/cdefs.h>
 #include <sys/ioctl.h>
 #include <sys/mount.h>
@@ -31,6 +32,7 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 
+#include <chrono>
 #include <memory>
 #include <set>
 #include <thread>
@@ -41,6 +43,7 @@
 #include <android-base/logging.h>
 #include <android-base/macros.h>
 #include <android-base/properties.h>
+#include <android-base/scopeguard.h>
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
 #include <bootloader_message/bootloader_message.h>
@@ -50,13 +53,16 @@
 #include <private/android_filesystem_config.h>
 #include <selinux/selinux.h>
 
+#include "action.h"
 #include "action_manager.h"
+#include "builtin_arguments.h"
 #include "init.h"
 #include "property_service.h"
 #include "reboot_utils.h"
 #include "service.h"
 #include "service_list.h"
 #include "sigchld_handler.h"
+#include "util.h"
 
 #define PROC_SYSRQ "/proc/sysrq-trigger"
 
@@ -71,6 +77,21 @@
 namespace android {
 namespace init {
 
+static bool shutting_down = false;
+
+static const std::set<std::string> kDebuggingServices{"tombstoned", "logd", "adbd", "console"};
+
+static std::vector<Service*> GetDebuggingServices(bool only_post_data) {
+    std::vector<Service*> ret;
+    ret.reserve(kDebuggingServices.size());
+    for (const auto& s : ServiceList::GetInstance()) {
+        if (kDebuggingServices.count(s->name()) && (!only_post_data || s->is_post_data())) {
+            ret.push_back(s.get());
+        }
+    }
+    return ret;
+}
+
 // represents umount status during reboot / shutdown.
 enum UmountStat {
     /* umount succeeded. */
@@ -442,6 +463,49 @@
     LOG(INFO) << "zram_backing_dev: `" << backing_dev << "` is cleared successfully.";
 }
 
+// Stops given services, waits for them to be stopped for |timeout| ms.
+// If terminate is true, then SIGTERM is sent to services, otherwise SIGKILL is sent.
+static void StopServices(const std::vector<Service*>& services, std::chrono::milliseconds timeout,
+                         bool terminate) {
+    LOG(INFO) << "Stopping " << services.size() << " services by sending "
+              << (terminate ? "SIGTERM" : "SIGKILL");
+    std::vector<pid_t> pids;
+    pids.reserve(services.size());
+    for (const auto& s : services) {
+        if (s->pid() > 0) {
+            pids.push_back(s->pid());
+        }
+        if (terminate) {
+            s->Terminate();
+        } else {
+            s->Stop();
+        }
+    }
+    if (timeout > 0ms) {
+        WaitToBeReaped(pids, timeout);
+    } else {
+        // Even if we don't to wait for services to stop, we still optimistically reap zombies.
+        ReapAnyOutstandingChildren();
+    }
+}
+
+// Like StopServices, but also logs all the services that failed to stop after the provided timeout.
+// Returns number of violators.
+static int StopServicesAndLogViolations(const std::vector<Service*>& services,
+                                        std::chrono::milliseconds timeout, bool terminate) {
+    StopServices(services, timeout, terminate);
+    int still_running = 0;
+    for (const auto& s : services) {
+        if (s->IsRunning()) {
+            LOG(ERROR) << "[service-misbehaving] : service '" << s->name() << "' is still running "
+                       << timeout.count() << "ms after receiving "
+                       << (terminate ? "SIGTERM" : "SIGKILL");
+            still_running++;
+        }
+    }
+    return still_running;
+}
+
 //* Reboot / shutdown the system.
 // cmd ANDROID_RB_* as defined in android_reboot.h
 // reason Reason string like "reboot", "shutdown,userrequested"
@@ -506,12 +570,13 @@
     // Start reboot monitor thread
     sem_post(&reboot_semaphore);
 
-    // keep debugging tools until non critical ones are all gone.
-    const std::set<std::string> kill_after_apps{"tombstoned", "logd", "adbd"};
     // watchdogd is a vendor specific component but should be alive to complete shutdown safely.
     const std::set<std::string> to_starts{"watchdogd"};
+    std::vector<Service*> stop_first;
+    stop_first.reserve(ServiceList::GetInstance().services().size());
     for (const auto& s : ServiceList::GetInstance()) {
-        if (kill_after_apps.count(s->name())) {
+        if (kDebuggingServices.count(s->name())) {
+            // keep debugging tools until non critical ones are all gone.
             s->SetShutdownCritical();
         } else if (to_starts.count(s->name())) {
             if (auto result = s->Start(); !result) {
@@ -525,6 +590,8 @@
                 LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
                            << "': " << result.error();
             }
+        } else {
+            stop_first.push_back(s.get());
         }
     }
 
@@ -567,49 +634,12 @@
     // optional shutdown step
     // 1. terminate all services except shutdown critical ones. wait for delay to finish
     if (shutdown_timeout > 0ms) {
-        LOG(INFO) << "terminating init services";
-
-        // Ask all services to terminate except shutdown critical ones.
-        for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
-            if (!s->IsShutdownCritical()) s->Terminate();
-        }
-
-        int service_count = 0;
-        // Only wait up to half of timeout here
-        auto termination_wait_timeout = shutdown_timeout / 2;
-        while (t.duration() < termination_wait_timeout) {
-            ReapAnyOutstandingChildren();
-
-            service_count = 0;
-            for (const auto& s : ServiceList::GetInstance()) {
-                // Count the number of services running except shutdown critical.
-                // Exclude the console as it will ignore the SIGTERM signal
-                // and not exit.
-                // Note: SVC_CONSOLE actually means "requires console" but
-                // it is only used by the shell.
-                if (!s->IsShutdownCritical() && s->pid() != 0 && (s->flags() & SVC_CONSOLE) == 0) {
-                    service_count++;
-                }
-            }
-
-            if (service_count == 0) {
-                // All terminable services terminated. We can exit early.
-                break;
-            }
-
-            // Wait a bit before recounting the number or running services.
-            std::this_thread::sleep_for(50ms);
-        }
-        LOG(INFO) << "Terminating running services took " << t
-                  << " with remaining services:" << service_count;
+        StopServicesAndLogViolations(stop_first, shutdown_timeout / 2, true /* SIGTERM */);
     }
-
-    // minimum safety steps before restarting
-    // 2. kill all services except ones that are necessary for the shutdown sequence.
-    for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
-        if (!s->IsShutdownCritical()) s->Stop();
-    }
+    // Send SIGKILL to ones that didn't terminate cleanly.
+    StopServicesAndLogViolations(stop_first, 0ms, false /* SIGKILL */);
     SubcontextTerminate();
+    // Reap subcontext pids.
     ReapAnyOutstandingChildren();
 
     // 3. send volume shutdown to vold
@@ -621,9 +651,7 @@
         LOG(INFO) << "vold not running, skipping vold shutdown";
     }
     // logcat stopped here
-    for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
-        if (kill_after_apps.count(s->name())) s->Stop();
-    }
+    StopServices(GetDebuggingServices(false /* only_post_data */), 0ms, false /* SIGKILL */);
     // 4. sync, try umount, and optionally run fsck for user shutdown
     {
         Timer sync_timer;
@@ -655,12 +683,96 @@
     abort();
 }
 
-bool HandlePowerctlMessage(const std::string& command) {
+static void EnterShutdown() {
+    LOG(INFO) << "Entering shutdown mode";
+    shutting_down = true;
+    // Skip wait for prop if it is in progress
+    ResetWaitForProp();
+    // Clear EXEC flag if there is one pending
+    for (const auto& s : ServiceList::GetInstance()) {
+        s->UnSetExec();
+    }
+    // We no longer process messages about properties changing coming from property service, so we
+    // need to tell property service to stop sending us these messages, otherwise it'll fill the
+    // buffers and block indefinitely, causing future property sets, including those that init makes
+    // during shutdown in Service::NotifyStateChange() to also block indefinitely.
+    SendStopSendingMessagesMessage();
+}
+
+static void LeaveShutdown() {
+    LOG(INFO) << "Leaving shutdown mode";
+    shutting_down = false;
+    SendStartSendingMessagesMessage();
+}
+
+static Result<void> DoUserspaceReboot() {
+    LOG(INFO) << "Userspace reboot initiated";
+    auto guard = android::base::make_scope_guard([] {
+        // Leave shutdown so that we can handle a full reboot.
+        LeaveShutdown();
+        TriggerShutdown("reboot,abort-userspace-reboot");
+    });
+    // Triggering userspace-reboot-requested will result in a bunch of set_prop
+    // actions. We should make sure, that all of them are propagated before
+    // proceeding with userspace reboot.
+    // TODO(b/135984674): implement proper synchronization logic.
+    std::this_thread::sleep_for(500ms);
+    EnterShutdown();
+    std::vector<Service*> stop_first;
+    // Remember the services that were enabled. We will need to manually enable them again otherwise
+    // triggers like class_start won't restart them.
+    std::vector<Service*> were_enabled;
+    stop_first.reserve(ServiceList::GetInstance().services().size());
+    for (const auto& s : ServiceList::GetInstance().services_in_shutdown_order()) {
+        if (s->is_post_data() && !kDebuggingServices.count(s->name())) {
+            stop_first.push_back(s);
+        }
+        if (s->is_post_data() && s->IsEnabled()) {
+            were_enabled.push_back(s);
+        }
+    }
+    // TODO(b/135984674): do we need shutdown animation for userspace reboot?
+    // TODO(b/135984674): control userspace timeout via read-only property?
+    StopServicesAndLogViolations(stop_first, 10s, true /* SIGTERM */);
+    if (int r = StopServicesAndLogViolations(stop_first, 20s, false /* SIGKILL */); r > 0) {
+        // TODO(b/135984674): store information about offending services for debugging.
+        return Error() << r << " post-data services are still running";
+    }
+    // TODO(b/135984674): remount userdata
+    if (int r = StopServicesAndLogViolations(GetDebuggingServices(true /* only_post_data */), 5s,
+                                             false /* SIGKILL */);
+        r > 0) {
+        // TODO(b/135984674): store information about offending services for debugging.
+        return Error() << r << " debugging services are still running";
+    }
+    // TODO(b/135984674): deactivate APEX modules and switch back to bootstrap namespace.
+    // Re-enable services
+    for (const auto& s : were_enabled) {
+        LOG(INFO) << "Re-enabling service '" << s->name() << "'";
+        s->Enable();
+    }
+    LeaveShutdown();
+    ActionManager::GetInstance().QueueEventTrigger("userspace-reboot-resume");
+    guard.Disable();  // Go on with userspace reboot.
+    return {};
+}
+
+static void HandleUserspaceReboot() {
+    LOG(INFO) << "Clearing queue and starting userspace-reboot-requested trigger";
+    auto& am = ActionManager::GetInstance();
+    am.ClearQueue();
+    am.QueueEventTrigger("userspace-reboot-requested");
+    auto handler = [](const BuiltinArguments&) { return DoUserspaceReboot(); };
+    am.QueueBuiltinAction(handler, "userspace-reboot");
+}
+
+void HandlePowerctlMessage(const std::string& command) {
     unsigned int cmd = 0;
     std::vector<std::string> cmd_params = Split(command, ",");
     std::string reboot_target = "";
     bool run_fsck = false;
     bool command_invalid = false;
+    bool userspace_reboot = false;
 
     if (cmd_params[0] == "shutdown") {
         cmd = ANDROID_RB_POWEROFF;
@@ -680,6 +792,10 @@
         cmd = ANDROID_RB_RESTART2;
         if (cmd_params.size() >= 2) {
             reboot_target = cmd_params[1];
+            if (reboot_target == "userspace") {
+                LOG(INFO) << "Userspace reboot requested";
+                userspace_reboot = true;
+            }
             // adb reboot fastboot should boot into bootloader for devices not
             // supporting logical partitions.
             if (reboot_target == "fastboot" &&
@@ -706,7 +822,7 @@
                     strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
                     if (std::string err; !write_bootloader_message(boot, &err)) {
                         LOG(ERROR) << "Failed to set bootloader message: " << err;
-                        return false;
+                        return;
                     }
                 }
             } else if (reboot_target == "sideload" || reboot_target == "sideload-auto-reboot" ||
@@ -719,7 +835,7 @@
                 std::string err;
                 if (!write_bootloader_message(options, &err)) {
                     LOG(ERROR) << "Failed to set bootloader message: " << err;
-                    return false;
+                    return;
                 }
                 reboot_target = "recovery";
             }
@@ -734,7 +850,12 @@
     }
     if (command_invalid) {
         LOG(ERROR) << "powerctl: unrecognized command '" << command << "'";
-        return false;
+        return;
+    }
+
+    if (userspace_reboot) {
+        HandleUserspaceReboot();
+        return;
     }
 
     LOG(INFO) << "Clear action queue and start shutdown trigger";
@@ -748,21 +869,11 @@
     };
     ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
 
-    // Skip wait for prop if it is in progress
-    ResetWaitForProp();
+    EnterShutdown();
+}
 
-    // Clear EXEC flag if there is one pending
-    for (const auto& s : ServiceList::GetInstance()) {
-        s->UnSetExec();
-    }
-
-    // We no longer process messages about properties changing coming from property service, so we
-    // need to tell property service to stop sending us these messages, otherwise it'll fill the
-    // buffers and block indefinitely, causing future property sets, including those that init makes
-    // during shutdown in Service::NotifyStateChange() to also block indefinitely.
-    SendStopSendingMessagesMessage();
-
-    return true;
+bool IsShuttingDown() {
+    return shutting_down;
 }
 
 }  // namespace init
diff --git a/init/reboot.h b/init/reboot.h
index 07dcb6e..81c3edc 100644
--- a/init/reboot.h
+++ b/init/reboot.h
@@ -23,8 +23,9 @@
 namespace init {
 
 // Parses and handles a setprop sys.powerctl message.
-bool HandlePowerctlMessage(const std::string& command);
+void HandlePowerctlMessage(const std::string& command);
 
+bool IsShuttingDown();
 }  // namespace init
 }  // namespace android
 
diff --git a/init/reboot_utils.cpp b/init/reboot_utils.cpp
index de085cc..dac0cf4 100644
--- a/init/reboot_utils.cpp
+++ b/init/reboot_utils.cpp
@@ -109,7 +109,7 @@
     abort();
 }
 
-void __attribute__((noreturn)) InitFatalReboot() {
+void __attribute__((noreturn)) InitFatalReboot(int signal_number) {
     auto pid = fork();
 
     if (pid == -1) {
@@ -124,6 +124,7 @@
     }
 
     // In the parent, let's try to get a backtrace then shutdown.
+    LOG(ERROR) << __FUNCTION__ << ": signal " << signal_number;
     std::unique_ptr<Backtrace> backtrace(
             Backtrace::Create(BACKTRACE_CURRENT_PROCESS, BACKTRACE_CURRENT_THREAD));
     if (!backtrace->Unwind(0)) {
@@ -154,7 +155,7 @@
         // RebootSystem uses syscall() which isn't actually async-signal-safe, but our only option
         // and probably good enough given this is already an error case and only enabled for
         // development builds.
-        InitFatalReboot();
+        InitFatalReboot(signal);
     };
     action.sa_flags = SA_RESTART;
     sigaction(SIGABRT, &action, nullptr);
diff --git a/init/reboot_utils.h b/init/reboot_utils.h
index 3fd969e..878ad96 100644
--- a/init/reboot_utils.h
+++ b/init/reboot_utils.h
@@ -27,7 +27,7 @@
 bool IsRebootCapable();
 // This is a wrapper around the actual reboot calls.
 void __attribute__((noreturn)) RebootSystem(unsigned int cmd, const std::string& reboot_target);
-void __attribute__((noreturn)) InitFatalReboot();
+void __attribute__((noreturn)) InitFatalReboot(int signal_number);
 void InstallRebootSignalHandlers();
 
 }  // namespace init
diff --git a/init/service.cpp b/init/service.cpp
index 0b73dc5..c8568a0 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -255,7 +255,7 @@
 
     if ((siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) && on_failure_reboot_target_) {
         LOG(ERROR) << "Service with 'reboot_on_failure' option failed, shutting down system.";
-        EnterShutdown(*on_failure_reboot_target_);
+        TriggerShutdown(*on_failure_reboot_target_);
     }
 
     if (flags_ & SVC_EXEC) UnSetExec();
@@ -300,7 +300,7 @@
                     LOG(ERROR) << "updatable process '" << name_ << "' exited 4 times "
                                << (boot_completed ? "in 4 minutes" : "before boot completed");
                     // Notifies update_verifier and apexd
-                    property_set("ro.init.updatable_crashing", "1");
+                    property_set("sys.init.updatable_crashing", "1");
                 }
             }
         } else {
@@ -335,7 +335,7 @@
 Result<void> Service::ExecStart() {
     auto reboot_on_failure = make_scope_guard([this] {
         if (on_failure_reboot_target_) {
-            EnterShutdown(*on_failure_reboot_target_);
+            TriggerShutdown(*on_failure_reboot_target_);
         }
     });
 
@@ -366,7 +366,7 @@
 Result<void> Service::Start() {
     auto reboot_on_failure = make_scope_guard([this] {
         if (on_failure_reboot_target_) {
-            EnterShutdown(*on_failure_reboot_target_);
+            TriggerShutdown(*on_failure_reboot_target_);
         }
     });
 
diff --git a/init/service.h b/init/service.h
index 788f792..272c9f9 100644
--- a/init/service.h
+++ b/init/service.h
@@ -75,6 +75,7 @@
             const std::vector<std::string>& args);
 
     bool IsRunning() { return (flags_ & SVC_RUNNING) != 0; }
+    bool IsEnabled() { return (flags_ & SVC_DISABLED) == 0; }
     Result<void> ExecStart();
     Result<void> Start();
     Result<void> StartIfNotDisabled();
diff --git a/init/sigchld_handler.cpp b/init/sigchld_handler.cpp
index 984235d..9b2c7d9 100644
--- a/init/sigchld_handler.cpp
+++ b/init/sigchld_handler.cpp
@@ -28,28 +28,31 @@
 #include <android-base/scopeguard.h>
 #include <android-base/stringprintf.h>
 
+#include <thread>
+
 #include "init.h"
 #include "service.h"
 #include "service_list.h"
 
-using android::base::StringPrintf;
 using android::base::boot_clock;
 using android::base::make_scope_guard;
+using android::base::StringPrintf;
+using android::base::Timer;
 
 namespace android {
 namespace init {
 
-static bool ReapOneProcess() {
+static pid_t ReapOneProcess() {
     siginfo_t siginfo = {};
     // This returns a zombie pid or informs us that there are no zombies left to be reaped.
     // It does NOT reap the pid; that is done below.
     if (TEMP_FAILURE_RETRY(waitid(P_ALL, 0, &siginfo, WEXITED | WNOHANG | WNOWAIT)) != 0) {
         PLOG(ERROR) << "waitid failed";
-        return false;
+        return 0;
     }
 
     auto pid = siginfo.si_pid;
-    if (pid == 0) return false;
+    if (pid == 0) return 0;
 
     // At this point we know we have a zombie pid, so we use this scopeguard to reap the pid
     // whenever the function returns from this point forward.
@@ -92,7 +95,7 @@
         LOG(INFO) << name << " received signal " << siginfo.si_status << wait_string;
     }
 
-    if (!service) return true;
+    if (!service) return pid;
 
     service->Reap(siginfo);
 
@@ -100,13 +103,33 @@
         ServiceList::GetInstance().RemoveService(*service);
     }
 
-    return true;
+    return pid;
 }
 
 void ReapAnyOutstandingChildren() {
-    while (ReapOneProcess()) {
+    while (ReapOneProcess() != 0) {
     }
 }
 
+void WaitToBeReaped(const std::vector<pid_t>& pids, std::chrono::milliseconds timeout) {
+    Timer t;
+    std::vector<pid_t> alive_pids(pids.begin(), pids.end());
+    while (!alive_pids.empty() && t.duration() < timeout) {
+        pid_t pid;
+        while ((pid = ReapOneProcess()) != 0) {
+            auto it = std::find(alive_pids.begin(), alive_pids.end(), pid);
+            if (it != alive_pids.end()) {
+                alive_pids.erase(it);
+            }
+        }
+        if (alive_pids.empty()) {
+            break;
+        }
+        std::this_thread::sleep_for(50ms);
+    }
+    LOG(INFO) << "Waiting for " << pids.size() << " pids to be reaped took " << t << " with "
+              << alive_pids.size() << " of them still running";
+}
+
 }  // namespace init
 }  // namespace android
diff --git a/init/sigchld_handler.h b/init/sigchld_handler.h
index 30063f2..fac1020 100644
--- a/init/sigchld_handler.h
+++ b/init/sigchld_handler.h
@@ -17,11 +17,16 @@
 #ifndef _INIT_SIGCHLD_HANDLER_H_
 #define _INIT_SIGCHLD_HANDLER_H_
 
+#include <chrono>
+#include <vector>
+
 namespace android {
 namespace init {
 
 void ReapAnyOutstandingChildren();
 
+void WaitToBeReaped(const std::vector<pid_t>& pids, std::chrono::milliseconds timeout);
+
 }  // namespace init
 }  // namespace android
 
diff --git a/init/util.cpp b/init/util.cpp
index 0532375..40db838 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -20,6 +20,7 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <pwd.h>
+#include <signal.h>
 #include <stdarg.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -481,7 +482,7 @@
         return;
     }
 
-    InitFatalReboot();
+    InitFatalReboot(SIGABRT);
 }
 
 // The kernel opens /dev/console and uses that fd for stdin/stdout/stderr if there is a serial
diff --git a/libcutils/fs_config.cpp b/libcutils/fs_config.cpp
index d0d83de..5fb11a5 100644
--- a/libcutils/fs_config.cpp
+++ b/libcutils/fs_config.cpp
@@ -161,7 +161,6 @@
     { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/crash_dump32" },
     { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/crash_dump64" },
     { 00755, AID_ROOT,      AID_SHELL,     0, "system/bin/debuggerd" },
-    { 00750, AID_ROOT,      AID_ROOT,      0, "system/bin/install-recovery.sh" },
     { 00550, AID_LOGD,      AID_LOGD,      0, "system/bin/logd" },
     { 00700, AID_ROOT,      AID_ROOT,      0, "system/bin/secilc" },
     { 00750, AID_ROOT,      AID_ROOT,      0, "system/bin/uncrypt" },
@@ -173,9 +172,10 @@
     { 00550, AID_ROOT,      AID_SHELL,     0, "system/etc/init.ril" },
     { 00555, AID_ROOT,      AID_ROOT,      0, "system/etc/ppp/*" },
     { 00555, AID_ROOT,      AID_ROOT,      0, "system/etc/rc.*" },
-    { 00440, AID_ROOT,      AID_ROOT,      0, "system/etc/recovery.img" },
+    { 00750, AID_ROOT,      AID_ROOT,      0, "vendor/bin/install-recovery.sh" },
     { 00600, AID_ROOT,      AID_ROOT,      0, "vendor/build.prop" },
     { 00600, AID_ROOT,      AID_ROOT,      0, "vendor/default.prop" },
+    { 00440, AID_ROOT,      AID_ROOT,      0, "vendor/etc/recovery.img" },
     { 00444, AID_ROOT,      AID_ROOT,      0, ven_conf_dir + 1 },
     { 00444, AID_ROOT,      AID_ROOT,      0, ven_conf_file + 1 },
 
diff --git a/libcutils/trace-dev.cpp b/libcutils/trace-dev.cpp
index 4da8215..bff16c1 100644
--- a/libcutils/trace-dev.cpp
+++ b/libcutils/trace-dev.cpp
@@ -34,12 +34,9 @@
     if (atrace_marker_fd == -1) {
         ALOGE("Error opening trace file: %s (%d)", strerror(errno), errno);
         atrace_enabled_tags = 0;
-        goto done;
+    } else {
+      atrace_enabled_tags = atrace_get_property();
     }
-
-    atrace_enabled_tags = atrace_get_property();
-
-done:
     atomic_store_explicit(&atrace_is_ready, true, memory_order_release);
 }
 
diff --git a/libion/include/ion/ion.h b/libion/include/ion/ion.h
index a60d24e..1480bd9 100644
--- a/libion/include/ion/ion.h
+++ b/libion/include/ion/ion.h
@@ -49,6 +49,7 @@
 int ion_query_get_heaps(int fd, int cnt, void* buffers);
 
 int ion_is_legacy(int fd);
+int ion_is_using_modular_heaps(int fd);
 
 __END_DECLS
 
diff --git a/libion/ion.c b/libion/ion.c
index 1ecfc78..07b4caf 100644
--- a/libion/ion.c
+++ b/libion/ion.c
@@ -31,10 +31,12 @@
 #include <unistd.h>
 
 #include <ion/ion.h>
-#include "ion_4.12.h"
+#include <linux/ion_4.19.h>
 
 #include <log/log.h>
 
+#define ION_ABI_VERSION_MODULAR_HEAPS 2
+
 enum ion_version { ION_VERSION_UNKNOWN, ION_VERSION_MODERN, ION_VERSION_LEGACY };
 
 static atomic_int g_ion_version = ATOMIC_VAR_INIT(ION_VERSION_UNKNOWN);
@@ -75,6 +77,14 @@
     return ret;
 }
 
+int ion_is_using_modular_heaps(int fd) {
+    int ion_abi_version = 0;
+    int ret = 0;
+
+    ret = ion_ioctl(fd, ION_IOC_ABI_VERSION, &ion_abi_version);
+    return (ret == 0 && ion_abi_version >= ION_ABI_VERSION_MODULAR_HEAPS);
+}
+
 int ion_alloc(int fd, size_t len, size_t align, unsigned int heap_mask, unsigned int flags,
               ion_user_handle_t* handle) {
     int ret = 0;
diff --git a/libion/ion_4.12.h b/libion/kernel-headers/linux/ion_4.12.h
similarity index 81%
rename from libion/ion_4.12.h
rename to libion/kernel-headers/linux/ion_4.12.h
index 614510c..1af8284 100644
--- a/libion/ion_4.12.h
+++ b/libion/kernel-headers/linux/ion_4.12.h
@@ -22,27 +22,27 @@
 #include <linux/types.h>
 #define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8)
 struct ion_new_allocation_data {
-  __u64 len;
-  __u32 heap_id_mask;
-  __u32 flags;
-  __u32 fd;
-  __u32 unused;
+    __u64 len;
+    __u32 heap_id_mask;
+    __u32 flags;
+    __u32 fd;
+    __u32 unused;
 };
 #define MAX_HEAP_NAME 32
 struct ion_heap_data {
-  char name[MAX_HEAP_NAME];
-  __u32 type;
-  __u32 heap_id;
-  __u32 reserved0;
-  __u32 reserved1;
-  __u32 reserved2;
+    char name[MAX_HEAP_NAME];
+    __u32 type;
+    __u32 heap_id;
+    __u32 reserved0;
+    __u32 reserved1;
+    __u32 reserved2;
 };
 struct ion_heap_query {
-  __u32 cnt;
-  __u32 reserved0;
-  __u64 heaps;
-  __u32 reserved1;
-  __u32 reserved2;
+    __u32 cnt;
+    __u32 reserved0;
+    __u64 heaps;
+    __u32 reserved1;
+    __u32 reserved2;
 };
 #define ION_IOC_MAGIC 'I'
 #define ION_IOC_NEW_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_new_allocation_data)
diff --git a/libion/kernel-headers/linux/ion_4.19.h b/libion/kernel-headers/linux/ion_4.19.h
new file mode 100644
index 0000000..f5b59f1
--- /dev/null
+++ b/libion/kernel-headers/linux/ion_4.19.h
@@ -0,0 +1,67 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   This header was automatically generated from a Linux kernel header
+ ***   of the same name, to make information necessary for userspace to
+ ***   call into the kernel available to libc.  It contains only constants,
+ ***   structures, and macros generated from the original header, and thus,
+ ***   contains no copyrightable information.
+ ***
+ ***   To edit the content of this header, modify the corresponding
+ ***   source file (e.g. under external/kernel-headers/original/) then
+ ***   run bionic/libc/kernel/tools/update_all.py
+ ***
+ ***   Any manual change here will be lost the next time this script will
+ ***   be run. You've been warned!
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#ifndef _UAPI_LINUX_ION_NEW_H
+#define _UAPI_LINUX_ION_NEW_H
+#include <linux/ioctl.h>
+#include <linux/types.h>
+#define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8)
+enum ion_heap_type_ext {
+    ION_HEAP_TYPE_CUSTOM_EXT = 16,
+    ION_HEAP_TYPE_MAX = 31,
+};
+enum ion_heap_id {
+    ION_HEAP_SYSTEM = (1 << ION_HEAP_TYPE_SYSTEM),
+    ION_HEAP_SYSTEM_CONTIG = (ION_HEAP_SYSTEM << 1),
+    ION_HEAP_CARVEOUT_START = (ION_HEAP_SYSTEM_CONTIG << 1),
+    ION_HEAP_CARVEOUT_END = (ION_HEAP_CARVEOUT_START << 4),
+    ION_HEAP_CHUNK = (ION_HEAP_CARVEOUT_END << 1),
+    ION_HEAP_DMA_START = (ION_HEAP_CHUNK << 1),
+    ION_HEAP_DMA_END = (ION_HEAP_DMA_START << 7),
+    ION_HEAP_CUSTOM_START = (ION_HEAP_DMA_END << 1),
+    ION_HEAP_CUSTOM_END = (ION_HEAP_CUSTOM_START << 15),
+};
+#define ION_NUM_MAX_HEAPS (32)
+struct ion_new_allocation_data {
+    __u64 len;
+    __u32 heap_id_mask;
+    __u32 flags;
+    __u32 fd;
+    __u32 unused;
+};
+#define MAX_HEAP_NAME 32
+struct ion_heap_data {
+    char name[MAX_HEAP_NAME];
+    __u32 type;
+    __u32 heap_id;
+    __u32 reserved0;
+    __u32 reserved1;
+    __u32 reserved2;
+};
+struct ion_heap_query {
+    __u32 cnt;
+    __u32 reserved0;
+    __u64 heaps;
+    __u32 reserved1;
+    __u32 reserved2;
+};
+#define ION_IOC_MAGIC 'I'
+#define ION_IOC_NEW_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_new_allocation_data)
+#define ION_IOC_HEAP_QUERY _IOWR(ION_IOC_MAGIC, 8, struct ion_heap_query)
+#define ION_IOC_ABI_VERSION _IOR(ION_IOC_MAGIC, 9, __u32)
+#endif
diff --git a/libion/original-kernel-headers/linux/ion_4.19.h b/libion/original-kernel-headers/linux/ion_4.19.h
new file mode 100644
index 0000000..75fef39
--- /dev/null
+++ b/libion/original-kernel-headers/linux/ion_4.19.h
@@ -0,0 +1,170 @@
+/*
+ * Adapted from drivers/staging/android/uapi/ion.h
+ *
+ * Copyright (C) 2019 Google, Inc.
+ *
+ * This software is licensed under the terms of the GNU General Public
+ * License version 2, as published by the Free Software Foundation, and
+ * may be copied, distributed, and modified under those terms.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#ifndef _UAPI_LINUX_ION_NEW_H
+#define _UAPI_LINUX_ION_NEW_H
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+#define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8)
+
+enum ion_heap_type_ext {
+    ION_HEAP_TYPE_CUSTOM_EXT = 16,
+    ION_HEAP_TYPE_MAX = 31,
+};
+
+/**
+ * ion_heap_id - list of standard heap ids that Android can use
+ *
+ * @ION_HEAP_SYSTEM		Id for the ION_HEAP_TYPE_SYSTEM
+ * @ION_HEAP_SYSTEM_CONTIG	Id for the ION_HEAP_TYPE_SYSTEM_CONTIG
+ * @ION_HEAP_CHUNK		Id for the ION_HEAP_TYPE_CHUNK
+ * @ION_HEAP_CARVEOUT_START	Start of reserved id range for heaps of type
+ *				ION_HEAP_TYPE_CARVEOUT
+ * @ION_HEAP_CARVEOUT_END	End of reserved id range for heaps of type
+ *				ION_HEAP_TYPE_CARVEOUT
+ * @ION_HEAP_DMA_START 		Start of reserved id range for heaps of type
+ *				ION_HEAP_TYPE_DMA
+ * @ION_HEAP_DMA_END		End of reserved id range for heaps of type
+ *				ION_HEAP_TYPE_DMA
+ * @ION_HEAP_CUSTOM_START	Start of reserved id range for heaps of custom
+ *				type
+ * @ION_HEAP_CUSTOM_END		End of reserved id range for heaps of custom
+ *				type
+ */
+enum ion_heap_id {
+    ION_HEAP_SYSTEM = (1 << ION_HEAP_TYPE_SYSTEM),
+    ION_HEAP_SYSTEM_CONTIG = (ION_HEAP_SYSTEM << 1),
+    ION_HEAP_CARVEOUT_START = (ION_HEAP_SYSTEM_CONTIG << 1),
+    ION_HEAP_CARVEOUT_END = (ION_HEAP_CARVEOUT_START << 4),
+    ION_HEAP_CHUNK = (ION_HEAP_CARVEOUT_END << 1),
+    ION_HEAP_DMA_START = (ION_HEAP_CHUNK << 1),
+    ION_HEAP_DMA_END = (ION_HEAP_DMA_START << 7),
+    ION_HEAP_CUSTOM_START = (ION_HEAP_DMA_END << 1),
+    ION_HEAP_CUSTOM_END = (ION_HEAP_CUSTOM_START << 15),
+};
+
+#define ION_NUM_MAX_HEAPS (32)
+
+/**
+ * DOC: Ion Userspace API
+ *
+ * create a client by opening /dev/ion
+ * most operations handled via following ioctls
+ *
+ */
+
+/**
+ * struct ion_new_allocation_data - metadata passed from userspace for allocations
+ * @len:		size of the allocation
+ * @heap_id_mask:	mask of heap ids to allocate from
+ * @flags:		flags passed to heap
+ * @handle:		pointer that will be populated with a cookie to use to
+ *			refer to this allocation
+ *
+ * Provided by userspace as an argument to the ioctl - added _new to denote
+ * this belongs to the new ION interface.
+ */
+struct ion_new_allocation_data {
+    __u64 len;
+    __u32 heap_id_mask;
+    __u32 flags;
+    __u32 fd;
+    __u32 unused;
+};
+
+#define MAX_HEAP_NAME 32
+
+/**
+ * struct ion_heap_data - data about a heap
+ * @name - first 32 characters of the heap name
+ * @type - heap type
+ * @heap_id - heap id for the heap
+ */
+struct ion_heap_data {
+    char name[MAX_HEAP_NAME];
+    __u32 type;
+    __u32 heap_id;
+    __u32 reserved0;
+    __u32 reserved1;
+    __u32 reserved2;
+};
+
+/**
+ * struct ion_heap_query - collection of data about all heaps
+ * @cnt - total number of heaps to be copied
+ * @heaps - buffer to copy heap data
+ */
+struct ion_heap_query {
+    __u32 cnt;       /* Total number of heaps to be copied */
+    __u32 reserved0; /* align to 64bits */
+    __u64 heaps;     /* buffer to be populated */
+    __u32 reserved1;
+    __u32 reserved2;
+};
+
+#define ION_IOC_MAGIC 'I'
+
+/**
+ * DOC: ION_IOC_NEW_ALLOC - allocate memory
+ *
+ * Takes an ion_allocation_data struct and returns it with the handle field
+ * populated with the opaque handle for the allocation.
+ * TODO: This IOCTL will clash by design; however, only one of
+ *  ION_IOC_ALLOC or ION_IOC_NEW_ALLOC paths will be exercised,
+ *  so this should not conflict.
+ */
+#define ION_IOC_NEW_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_new_allocation_data)
+
+/**
+ * DOC: ION_IOC_FREE - free memory
+ *
+ * Takes an ion_handle_data struct and frees the handle.
+ *
+ * #define ION_IOC_FREE		_IOWR(ION_IOC_MAGIC, 1, struct ion_handle_data)
+ * This will come from the older kernels, so don't redefine here
+ */
+
+/**
+ * DOC: ION_IOC_SHARE - creates a file descriptor to use to share an allocation
+ *
+ * Takes an ion_fd_data struct with the handle field populated with a valid
+ * opaque handle.  Returns the struct with the fd field set to a file
+ * descriptor open in the current address space.  This file descriptor
+ * can then be passed to another process.  The corresponding opaque handle can
+ * be retrieved via ION_IOC_IMPORT.
+ *
+ * #define ION_IOC_SHARE		_IOWR(ION_IOC_MAGIC, 4, struct ion_fd_data)
+ * This will come from the older kernels, so don't redefine here
+ */
+
+/**
+ * DOC: ION_IOC_HEAP_QUERY - information about available heaps
+ *
+ * Takes an ion_heap_query structure and populates information about
+ * available Ion heaps.
+ */
+#define ION_IOC_HEAP_QUERY _IOWR(ION_IOC_MAGIC, 8, struct ion_heap_query)
+
+/**
+ * DOC: ION_IOC_HEAP_ABI_VERSION - return ABI version
+ *
+ * Returns ABI version for this driver
+ */
+#define ION_IOC_ABI_VERSION _IOR(ION_IOC_MAGIC, 9, __u32)
+
+#endif /* _UAPI_LINUX_ION_NEW_H */
diff --git a/libion/tests/Android.bp b/libion/tests/Android.bp
index 5600702..989e029 100644
--- a/libion/tests/Android.bp
+++ b/libion/tests/Android.bp
@@ -29,5 +29,6 @@
         "invalid_values_test.cpp",
         "ion_test_fixture.cpp",
         "map_test.cpp",
+        "modular_heap_check.cpp",
     ],
 }
diff --git a/libion/tests/ion_4.12.h b/libion/tests/ion_4.12.h
deleted file mode 100644
index 614510c..0000000
--- a/libion/tests/ion_4.12.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************************
- ****************************************************************************
- ***
- ***   This header was automatically generated from a Linux kernel header
- ***   of the same name, to make information necessary for userspace to
- ***   call into the kernel available to libc.  It contains only constants,
- ***   structures, and macros generated from the original header, and thus,
- ***   contains no copyrightable information.
- ***
- ***   To edit the content of this header, modify the corresponding
- ***   source file (e.g. under external/kernel-headers/original/) then
- ***   run bionic/libc/kernel/tools/update_all.py
- ***
- ***   Any manual change here will be lost the next time this script will
- ***   be run. You've been warned!
- ***
- ****************************************************************************
- ****************************************************************************/
-#ifndef _UAPI_LINUX_ION_NEW_H
-#define _UAPI_LINUX_ION_NEW_H
-#include <linux/ioctl.h>
-#include <linux/types.h>
-#define ION_NUM_HEAP_IDS (sizeof(unsigned int) * 8)
-struct ion_new_allocation_data {
-  __u64 len;
-  __u32 heap_id_mask;
-  __u32 flags;
-  __u32 fd;
-  __u32 unused;
-};
-#define MAX_HEAP_NAME 32
-struct ion_heap_data {
-  char name[MAX_HEAP_NAME];
-  __u32 type;
-  __u32 heap_id;
-  __u32 reserved0;
-  __u32 reserved1;
-  __u32 reserved2;
-};
-struct ion_heap_query {
-  __u32 cnt;
-  __u32 reserved0;
-  __u64 heaps;
-  __u32 reserved1;
-  __u32 reserved2;
-};
-#define ION_IOC_MAGIC 'I'
-#define ION_IOC_NEW_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_new_allocation_data)
-#define ION_IOC_HEAP_QUERY _IOWR(ION_IOC_MAGIC, 8, struct ion_heap_query)
-#endif
diff --git a/libion/tests/ion_test_fixture.h b/libion/tests/ion_test_fixture.h
index 4f254b8..c78fe41 100644
--- a/libion/tests/ion_test_fixture.h
+++ b/libion/tests/ion_test_fixture.h
@@ -18,8 +18,8 @@
 #define ION_TEST_FIXTURE_H_
 
 #include <gtest/gtest.h>
+#include <linux/ion_4.12.h>
 #include <vector>
-#include "ion_4.12.h"
 
 using ::testing::Test;
 
diff --git a/libnativeloader/utils.h b/libion/tests/modular_heap_check.cpp
similarity index 63%
rename from libnativeloader/utils.h
rename to libion/tests/modular_heap_check.cpp
index a1c2be5..5505c5a 100644
--- a/libnativeloader/utils.h
+++ b/libion/tests/modular_heap_check.cpp
@@ -13,14 +13,18 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#pragma once
 
-namespace android::nativeloader {
+#include <gtest/gtest.h>
 
-#if defined(__LP64__)
-#define LIB "lib64"
-#else
-#define LIB "lib"
-#endif
+#include <ion/ion.h>
+#include "ion_test_fixture.h"
 
-}  // namespace android::nativeloader
+class ModularHeapCheck : public IonTest {};
+
+TEST_F(ModularHeapCheck, ModularHeapCheckSimple) {
+    if (ion_is_using_modular_heaps(ionfd)) {
+        std::cout << "Heaps are modular." << std::endl;
+    } else {
+        std::cout << "Heaps are built-in." << std::endl;
+    }
+}
diff --git a/liblog/fake_writer.cpp b/liblog/fake_writer.cpp
index 4d07caa..f1ddff1 100644
--- a/liblog/fake_writer.cpp
+++ b/liblog/fake_writer.cpp
@@ -24,6 +24,7 @@
 #include "log_portability.h"
 #include "logger.h"
 
+static int fakeAvailable(log_id_t);
 static int fakeOpen();
 static void fakeClose();
 static int fakeWrite(log_id_t log_id, struct timespec* ts, struct iovec* vec, size_t nr);
@@ -34,12 +35,16 @@
     .name = "fake",
     .logMask = 0,
     .context.priv = &logFds,
-    .available = NULL,
+    .available = fakeAvailable,
     .open = fakeOpen,
     .close = fakeClose,
     .write = fakeWrite,
 };
 
+static int fakeAvailable(log_id_t) {
+  return 0;
+}
+
 static int fakeOpen() {
   int i;
 
diff --git a/liblog/include/log/log_time.h b/liblog/include/log/log_time.h
index 09c9910..1b33331 100644
--- a/liblog/include/log/log_time.h
+++ b/liblog/include/log/log_time.h
@@ -35,11 +35,6 @@
 
 extern "C" {
 
-/*
- * NB: we did NOT define a copy constructor. This will result in structure
- * no longer being compatible with pass-by-value which is desired
- * efficient behavior. Also, pass-by-reference breaks C/C++ ABI.
- */
 struct log_time {
  public:
   uint32_t tv_sec = 0; /* good to Feb 5 2106 */
diff --git a/liblog/include/private/android_logger.h b/liblog/include/private/android_logger.h
index 5e04148..d3cb571 100644
--- a/liblog/include/private/android_logger.h
+++ b/liblog/include/private/android_logger.h
@@ -57,6 +57,18 @@
   int32_t tag;  // Little Endian Order
 } android_event_header_t;
 
+// Event payload EVENT_TYPE_LIST
+typedef struct __attribute__((__packed__)) {
+  int8_t type;  // EVENT_TYPE_LIST
+  int8_t element_count;
+} android_event_list_t;
+
+// Event payload EVENT_TYPE_FLOAT
+typedef struct __attribute__((__packed__)) {
+  int8_t type;  // EVENT_TYPE_FLOAT
+  float data;
+} android_event_float_t;
+
 /* Event payload EVENT_TYPE_INT */
 typedef struct __attribute__((__packed__)) {
   int8_t type;   // EVENT_TYPE_INT
diff --git a/liblog/log_event_list.cpp b/liblog/log_event_list.cpp
index 18ea930..7882c96 100644
--- a/liblog/log_event_list.cpp
+++ b/liblog/log_event_list.cpp
@@ -51,11 +51,9 @@
 typedef struct android_log_context_internal android_log_context_internal;
 
 static void init_context(android_log_context_internal* context, uint32_t tag) {
-  size_t needed;
-
   context->tag = tag;
   context->read_write_flag = kAndroidLoggerWrite;
-  needed = sizeof(uint8_t) + sizeof(uint8_t);
+  size_t needed = sizeof(android_event_list_t);
   if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
     context->overflow = true;
   }
@@ -143,7 +141,6 @@
 }
 
 int android_log_write_list_begin(android_log_context ctx) {
-  size_t needed;
   android_log_context_internal* context;
 
   context = (android_log_context_internal*)ctx;
@@ -154,7 +151,7 @@
     context->overflow = true;
     return -EOVERFLOW;
   }
-  needed = sizeof(uint8_t) + sizeof(uint8_t);
+  size_t needed = sizeof(android_event_list_t);
   if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
     context->overflow = true;
     return -EIO;
@@ -168,8 +165,9 @@
   if (context->overflow) {
     return -EIO;
   }
-  context->storage[context->pos + 0] = EVENT_TYPE_LIST;
-  context->storage[context->pos + 1] = 0;
+  auto* event_list = reinterpret_cast<android_event_list_t*>(&context->storage[context->pos]);
+  event_list->type = EVENT_TYPE_LIST;
+  event_list->element_count = 0;
   context->list[context->list_nest_depth] = context->pos + 1;
   context->count[context->list_nest_depth] = 0;
   context->pos += needed;
@@ -177,57 +175,49 @@
 }
 
 int android_log_write_int32(android_log_context ctx, int32_t value) {
-  size_t needed;
-  android_log_context_internal* context;
-
-  context = (android_log_context_internal*)ctx;
+  android_log_context_internal* context = (android_log_context_internal*)ctx;
   if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
     return -EBADF;
   }
   if (context->overflow) {
     return -EIO;
   }
-  needed = sizeof(uint8_t) + sizeof(value);
+  size_t needed = sizeof(android_event_int_t);
   if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
     context->overflow = true;
     return -EIO;
   }
   context->count[context->list_nest_depth]++;
-  context->storage[context->pos + 0] = EVENT_TYPE_INT;
-  *reinterpret_cast<int32_t*>(&context->storage[context->pos + 1]) = value;
+  auto* event_int = reinterpret_cast<android_event_int_t*>(&context->storage[context->pos]);
+  event_int->type = EVENT_TYPE_INT;
+  event_int->data = value;
   context->pos += needed;
   return 0;
 }
 
 int android_log_write_int64(android_log_context ctx, int64_t value) {
-  size_t needed;
-  android_log_context_internal* context;
-
-  context = (android_log_context_internal*)ctx;
+  android_log_context_internal* context = (android_log_context_internal*)ctx;
   if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
     return -EBADF;
   }
   if (context->overflow) {
     return -EIO;
   }
-  needed = sizeof(uint8_t) + sizeof(value);
+  size_t needed = sizeof(android_event_long_t);
   if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
     context->overflow = true;
     return -EIO;
   }
   context->count[context->list_nest_depth]++;
-  context->storage[context->pos + 0] = EVENT_TYPE_LONG;
-  *reinterpret_cast<int64_t*>(&context->storage[context->pos + 1]) = value;
+  auto* event_long = reinterpret_cast<android_event_long_t*>(&context->storage[context->pos]);
+  event_long->type = EVENT_TYPE_LONG;
+  event_long->data = value;
   context->pos += needed;
   return 0;
 }
 
 int android_log_write_string8_len(android_log_context ctx, const char* value, size_t maxlen) {
-  size_t needed;
-  ssize_t len;
-  android_log_context_internal* context;
-
-  context = (android_log_context_internal*)ctx;
+  android_log_context_internal* context = (android_log_context_internal*)ctx;
   if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
     return -EBADF;
   }
@@ -237,8 +227,8 @@
   if (!value) {
     value = "";
   }
-  len = strnlen(value, maxlen);
-  needed = sizeof(uint8_t) + sizeof(int32_t) + len;
+  int32_t len = strnlen(value, maxlen);
+  size_t needed = sizeof(android_event_string_t) + len;
   if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
     /* Truncate string for delivery */
     len = MAX_EVENT_PAYLOAD - context->pos - 1 - sizeof(int32_t);
@@ -248,10 +238,11 @@
     }
   }
   context->count[context->list_nest_depth]++;
-  context->storage[context->pos + 0] = EVENT_TYPE_STRING;
-  *reinterpret_cast<ssize_t*>(&context->storage[context->pos + 1]) = len;
+  auto* event_string = reinterpret_cast<android_event_string_t*>(&context->storage[context->pos]);
+  event_string->type = EVENT_TYPE_STRING;
+  event_string->length = len;
   if (len) {
-    memcpy(&context->storage[context->pos + 5], value, len);
+    memcpy(&event_string->data, value, len);
   }
   context->pos += needed;
   return len;
@@ -262,26 +253,22 @@
 }
 
 int android_log_write_float32(android_log_context ctx, float value) {
-  size_t needed;
-  uint32_t ivalue;
-  android_log_context_internal* context;
-
-  context = (android_log_context_internal*)ctx;
+  android_log_context_internal* context = (android_log_context_internal*)ctx;
   if (!context || (kAndroidLoggerWrite != context->read_write_flag)) {
     return -EBADF;
   }
   if (context->overflow) {
     return -EIO;
   }
-  needed = sizeof(uint8_t) + sizeof(ivalue);
+  size_t needed = sizeof(android_event_float_t);
   if ((context->pos + needed) > MAX_EVENT_PAYLOAD) {
     context->overflow = true;
     return -EIO;
   }
-  ivalue = *(uint32_t*)&value;
   context->count[context->list_nest_depth]++;
-  context->storage[context->pos + 0] = EVENT_TYPE_FLOAT;
-  *reinterpret_cast<uint32_t*>(&context->storage[context->pos + 1]) = ivalue;
+  auto* event_float = reinterpret_cast<android_event_float_t*>(&context->storage[context->pos]);
+  event_float->type = EVENT_TYPE_FLOAT;
+  event_float->data = value;
   context->pos += needed;
   return 0;
 }
@@ -443,20 +430,22 @@
     return elem;
   }
 
-  elem.type = static_cast<AndroidEventLogType>(context->storage[pos++]);
+  elem.type = static_cast<AndroidEventLogType>(context->storage[pos]);
   switch ((int)elem.type) {
     case EVENT_TYPE_FLOAT:
     /* Rely on union to translate elem.data.int32 into elem.data.float32 */
     /* FALLTHRU */
-    case EVENT_TYPE_INT:
+    case EVENT_TYPE_INT: {
       elem.len = sizeof(int32_t);
-      if ((pos + elem.len) > context->len) {
+      if ((pos + sizeof(android_event_int_t)) > context->len) {
         elem.type = EVENT_TYPE_UNKNOWN;
         return elem;
       }
-      elem.data.int32 = *reinterpret_cast<int32_t*>(&context->storage[pos]);
+
+      auto* event_int = reinterpret_cast<android_event_int_t*>(&context->storage[pos]);
+      pos += sizeof(android_event_int_t);
+      elem.data.int32 = event_int->data;
       /* common tangeable object suffix */
-      pos += elem.len;
       elem.complete = !context->list_nest_depth && !context->count[0];
       if (!peek) {
         if (!context->count[context->list_nest_depth] ||
@@ -466,16 +455,19 @@
         context->pos = pos;
       }
       return elem;
+    }
 
-    case EVENT_TYPE_LONG:
+    case EVENT_TYPE_LONG: {
       elem.len = sizeof(int64_t);
-      if ((pos + elem.len) > context->len) {
+      if ((pos + sizeof(android_event_long_t)) > context->len) {
         elem.type = EVENT_TYPE_UNKNOWN;
         return elem;
       }
-      elem.data.int64 = *reinterpret_cast<int64_t*>(&context->storage[pos]);
+
+      auto* event_long = reinterpret_cast<android_event_long_t*>(&context->storage[pos]);
+      pos += sizeof(android_event_long_t);
+      elem.data.int64 = event_long->data;
       /* common tangeable object suffix */
-      pos += elem.len;
       elem.complete = !context->list_nest_depth && !context->count[0];
       if (!peek) {
         if (!context->count[context->list_nest_depth] ||
@@ -485,15 +477,22 @@
         context->pos = pos;
       }
       return elem;
+    }
 
-    case EVENT_TYPE_STRING:
-      if ((pos + sizeof(int32_t)) > context->len) {
+    case EVENT_TYPE_STRING: {
+      if ((pos + sizeof(android_event_string_t)) > context->len) {
         elem.type = EVENT_TYPE_UNKNOWN;
         elem.complete = true;
         return elem;
       }
-      elem.len = *reinterpret_cast<int32_t*>(&context->storage[pos]);
-      pos += sizeof(int32_t);
+      auto* event_string = reinterpret_cast<android_event_string_t*>(&context->storage[pos]);
+      pos += sizeof(android_event_string_t);
+      // Wire format is int32_t, but elem.len is uint16_t...
+      if (event_string->length >= UINT16_MAX) {
+        elem.type = EVENT_TYPE_UNKNOWN;
+        return elem;
+      }
+      elem.len = event_string->length;
       if ((pos + elem.len) > context->len) {
         elem.len = context->len - pos; /* truncate string */
         elem.complete = true;
@@ -502,7 +501,7 @@
           return elem;
         }
       }
-      elem.data.string = (char*)&context->storage[pos];
+      elem.data.string = event_string->data;
       /* common tangeable object suffix */
       pos += elem.len;
       elem.complete = !context->list_nest_depth && !context->count[0];
@@ -514,13 +513,16 @@
         context->pos = pos;
       }
       return elem;
+    }
 
-    case EVENT_TYPE_LIST:
-      if ((pos + sizeof(uint8_t)) > context->len) {
+    case EVENT_TYPE_LIST: {
+      if ((pos + sizeof(android_event_list_t)) > context->len) {
         elem.type = EVENT_TYPE_UNKNOWN;
         elem.complete = true;
         return elem;
       }
+      auto* event_list = reinterpret_cast<android_event_list_t*>(&context->storage[pos]);
+      pos += sizeof(android_event_list_t);
       elem.complete = context->list_nest_depth >= ANDROID_MAX_LIST_NEST_DEPTH;
       if (peek) {
         return elem;
@@ -528,15 +530,17 @@
       if (context->count[context->list_nest_depth]) {
         context->count[context->list_nest_depth]--;
       }
-      context->list_stop = !context->storage[pos];
+      context->list_stop = event_list->element_count == 0;
       context->list_nest_depth++;
       if (context->list_nest_depth <= ANDROID_MAX_LIST_NEST_DEPTH) {
-        context->count[context->list_nest_depth] = context->storage[pos];
+        context->count[context->list_nest_depth] = event_list->element_count;
       }
-      context->pos = pos + sizeof(uint8_t);
+      context->pos = pos;
       return elem;
+    }
 
     case EVENT_TYPE_LIST_STOP: /* Suprise Newline terminates lists. */
+      pos++;
       if (!peek) {
         context->pos = pos;
       }
diff --git a/liblog/logd_reader.cpp b/liblog/logd_reader.cpp
index 916a428..619cf8c 100644
--- a/liblog/logd_reader.cpp
+++ b/liblog/logd_reader.cpp
@@ -67,12 +67,12 @@
     .name = "logd",
     .available = logdAvailable,
     .version = logdVersion,
+    .close = logdClose,
     .read = logdRead,
     .poll = logdPoll,
-    .close = logdClose,
     .clear = logdClear,
-    .getSize = logdGetSize,
     .setSize = logdSetSize,
+    .getSize = logdGetSize,
     .getReadableSize = logdGetReadableSize,
     .getPrune = logdGetPrune,
     .setPrune = logdSetPrune,
@@ -107,7 +107,7 @@
   strlcpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path));
 
   int fd = socket(AF_LOCAL, type | SOCK_CLOEXEC, 0);
-  if (fd == 0) {
+  if (fd == -1) {
     return -1;
   }
 
@@ -316,16 +316,11 @@
   return check_log_success(buf, send_log_msg(NULL, NULL, buf, len));
 }
 
-static void caught_signal(int signum __unused) {}
-
 static int logdOpen(struct android_log_logger_list* logger_list,
                     struct android_log_transport_context* transp) {
   struct android_log_logger* logger;
-  struct sigaction ignore;
-  struct sigaction old_sigaction;
-  unsigned int old_alarm = 0;
   char buffer[256], *cp, c;
-  int e, ret, remaining, sock;
+  int ret, remaining, sock;
 
   if (!logger_list) {
     return -EINVAL;
@@ -337,12 +332,6 @@
   }
 
   sock = socket_local_client("logdr", SOCK_SEQPACKET);
-  if (sock == 0) {
-    /* Guarantee not file descriptor zero */
-    int newsock = socket_local_client("logdr", SOCK_SEQPACKET);
-    close(sock);
-    sock = newsock;
-  }
   if (sock <= 0) {
     if ((sock == -1) && errno) {
       return -errno;
@@ -393,29 +382,13 @@
     cp += ret;
   }
 
-  if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
-    /* Deal with an unresponsive logd */
-    memset(&ignore, 0, sizeof(ignore));
-    ignore.sa_handler = caught_signal;
-    sigemptyset(&ignore.sa_mask);
-    /* particularily useful if tombstone is reporting for logd */
-    sigaction(SIGALRM, &ignore, &old_sigaction);
-    old_alarm = alarm(30);
-  }
-  ret = write(sock, buffer, cp - buffer);
-  e = errno;
-  if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
-    if (e == EINTR) {
-      e = ETIMEDOUT;
-    }
-    alarm(old_alarm);
-    sigaction(SIGALRM, &old_sigaction, NULL);
-  }
+  ret = TEMP_FAILURE_RETRY(write(sock, buffer, cp - buffer));
+  int write_errno = errno;
 
   if (ret <= 0) {
     close(sock);
-    if ((ret == -1) && e) {
-      return -e;
+    if (ret == -1) {
+      return -write_errno;
     }
     if (ret == 0) {
       return -EIO;
@@ -433,52 +406,21 @@
 /* Read from the selected logs */
 static int logdRead(struct android_log_logger_list* logger_list,
                     struct android_log_transport_context* transp, struct log_msg* log_msg) {
-  int ret, e;
-  struct sigaction ignore;
-  struct sigaction old_sigaction;
-  unsigned int old_alarm = 0;
-
-  ret = logdOpen(logger_list, transp);
+  int ret = logdOpen(logger_list, transp);
   if (ret < 0) {
     return ret;
   }
 
   memset(log_msg, 0, sizeof(*log_msg));
 
-  unsigned int new_alarm = 0;
-  if (logger_list->mode & ANDROID_LOG_NONBLOCK) {
-    if ((logger_list->mode & ANDROID_LOG_WRAP) &&
-        (logger_list->start.tv_sec || logger_list->start.tv_nsec)) {
-      /* b/64143705 */
-      new_alarm = (ANDROID_LOG_WRAP_DEFAULT_TIMEOUT * 11) / 10 + 10;
-      logger_list->mode &= ~ANDROID_LOG_WRAP;
-    } else {
-      new_alarm = 30;
-    }
-
-    memset(&ignore, 0, sizeof(ignore));
-    ignore.sa_handler = caught_signal;
-    sigemptyset(&ignore.sa_mask);
-    /* particularily useful if tombstone is reporting for logd */
-    sigaction(SIGALRM, &ignore, &old_sigaction);
-    old_alarm = alarm(new_alarm);
-  }
-
   /* NOTE: SOCK_SEQPACKET guarantees we read exactly one full entry */
-  ret = recv(ret, log_msg, LOGGER_ENTRY_MAX_LEN, 0);
-  e = errno;
-
-  if (new_alarm) {
-    if ((ret == 0) || (e == EINTR)) {
-      e = EAGAIN;
-      ret = -1;
-    }
-    alarm(old_alarm);
-    sigaction(SIGALRM, &old_sigaction, NULL);
+  ret = TEMP_FAILURE_RETRY(recv(ret, log_msg, LOGGER_ENTRY_MAX_LEN, 0));
+  if ((logger_list->mode & ANDROID_LOG_NONBLOCK) && ret == 0) {
+    return -EAGAIN;
   }
 
-  if ((ret == -1) && e) {
-    return -e;
+  if (ret == -1) {
+    return -errno;
   }
   return ret;
 }
diff --git a/liblog/logger_write.cpp b/liblog/logger_write.cpp
index abcead7..e1772f1 100644
--- a/liblog/logger_write.cpp
+++ b/liblog/logger_write.cpp
@@ -34,8 +34,18 @@
 
 #define LOG_BUF_SIZE 1024
 
-android_log_transport_write* android_log_write = nullptr;
+#if (FAKE_LOG_DEVICE == 0)
+extern struct android_log_transport_write logdLoggerWrite;
+extern struct android_log_transport_write pmsgLoggerWrite;
+
+android_log_transport_write* android_log_write = &logdLoggerWrite;
+android_log_transport_write* android_log_persist_write = &pmsgLoggerWrite;
+#else
+extern android_log_transport_write fakeLoggerWrite;
+
+android_log_transport_write* android_log_write = &fakeLoggerWrite;
 android_log_transport_write* android_log_persist_write = nullptr;
+#endif
 
 static int __write_to_log_init(log_id_t, struct iovec* vec, size_t nr);
 static int (*write_to_log)(log_id_t, struct iovec* vec, size_t nr) = __write_to_log_init;
@@ -90,9 +100,8 @@
   }
 
   for (i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
-    if (node->write && (i != LOG_ID_KERNEL) &&
-        ((i != LOG_ID_SECURITY) || (check_log_uid_permissions() == 0)) &&
-        (!node->available || ((*node->available)(static_cast<log_id_t>(i)) >= 0))) {
+    if (i != LOG_ID_KERNEL && (i != LOG_ID_SECURITY || check_log_uid_permissions() == 0) &&
+        (*node->available)(static_cast<log_id_t>(i)) >= 0) {
       node->logMask |= 1 << i;
     }
   }
@@ -132,9 +141,6 @@
     android_log_persist_write->close();
   }
 
-  android_log_write = nullptr;
-  android_log_persist_write = nullptr;
-
 #if defined(__ANDROID__)
   /*
    * Additional risk here somewhat mitigated by immediately unlock flushing
@@ -179,26 +185,11 @@
 
 /* log_init_lock assumed */
 static int __write_to_log_initialize() {
-#if (FAKE_LOG_DEVICE == 0)
-  extern struct android_log_transport_write logdLoggerWrite;
-  extern struct android_log_transport_write pmsgLoggerWrite;
-
-  android_log_write = &logdLoggerWrite;
-  android_log_persist_write = &pmsgLoggerWrite;
-#else
-  extern struct android_log_transport_write fakeLoggerWrite;
-
-  android_log_write = &fakeLoggerWrite;
-#endif
-
   if (!transport_initialize(android_log_write)) {
-    android_log_write = nullptr;
     return -ENODEV;
   }
 
-  if (!transport_initialize(android_log_persist_write)) {
-    android_log_persist_write = nullptr;
-  }
+  transport_initialize(android_log_persist_write);
 
   return 1;
 }
@@ -206,14 +197,6 @@
 static int __write_to_log_daemon(log_id_t log_id, struct iovec* vec, size_t nr) {
   int ret, save_errno;
   struct timespec ts;
-  size_t len, i;
-
-  for (len = i = 0; i < nr; ++i) {
-    len += vec[i].iov_len;
-  }
-  if (!len) {
-    return -EINVAL;
-  }
 
   save_errno = errno;
 #if defined(__ANDROID__)
@@ -283,10 +266,6 @@
     int prio = *static_cast<int*>(vec[0].iov_base);
     const char* tag = static_cast<const char*>(vec[1].iov_base);
     size_t len = vec[1].iov_len;
-    /* tag must be nul terminated */
-    if (strnlen(tag, len) >= len) {
-      tag = NULL;
-    }
 
     if (!__android_log_is_loggable_len(prio, tag, len - 1, ANDROID_LOG_VERBOSE)) {
       errno = save_errno;
@@ -304,7 +283,7 @@
 #endif
 
   ret = 0;
-  i = 1 << log_id;
+  size_t i = 1 << log_id;
 
   if (android_log_write != nullptr && (android_log_write->logMask & i)) {
     ssize_t retval;
diff --git a/liblog/logprint.cpp b/liblog/logprint.cpp
index dd2c797..82fbafd 100644
--- a/liblog/logprint.cpp
+++ b/liblog/logprint.cpp
@@ -35,8 +35,10 @@
 #include <wchar.h>
 
 #include <cutils/list.h>
+
 #include <log/log.h>
 #include <log/logprint.h>
+#include <private/android_logger.h>
 
 #include "log_portability.h"
 
@@ -635,8 +637,7 @@
 
   if (eventDataLen < 1) return -1;
 
-  type = *eventData++;
-  eventDataLen--;
+  type = *eventData;
 
   cp = NULL;
   len = 0;
@@ -725,22 +726,24 @@
     case EVENT_TYPE_INT:
       /* 32-bit signed int */
       {
-        int32_t ival;
-
-        if (eventDataLen < 4) return -1;
-        ival = *reinterpret_cast<const int32_t*>(eventData);
-        eventData += 4;
-        eventDataLen -= 4;
-
-        lval = ival;
+        if (eventDataLen < sizeof(android_event_int_t)) return -1;
+        auto* event_int = reinterpret_cast<const android_event_int_t*>(eventData);
+        lval = event_int->data;
+        eventData += sizeof(android_event_int_t);
+        eventDataLen -= sizeof(android_event_int_t);
       }
       goto pr_lval;
     case EVENT_TYPE_LONG:
       /* 64-bit signed long */
-      if (eventDataLen < 8) return -1;
-      lval = *reinterpret_cast<const int64_t*>(eventData);
-      eventData += 8;
-      eventDataLen -= 8;
+      if (eventDataLen < sizeof(android_event_long_t)) {
+        return -1;
+      }
+      {
+        auto* event_long = reinterpret_cast<const android_event_long_t*>(eventData);
+        lval = event_long->data;
+      }
+      eventData += sizeof(android_event_long_t);
+      eventDataLen -= sizeof(android_event_long_t);
     pr_lval:
       outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
       if (outCount < outBufLen) {
@@ -754,14 +757,11 @@
     case EVENT_TYPE_FLOAT:
       /* float */
       {
-        uint32_t ival;
-        float fval;
-
-        if (eventDataLen < 4) return -1;
-        ival = *reinterpret_cast<const uint32_t*>(eventData);
-        fval = *(float*)&ival;
-        eventData += 4;
-        eventDataLen -= 4;
+        if (eventDataLen < sizeof(android_event_float_t)) return -1;
+        auto* event_float = reinterpret_cast<const android_event_float_t*>(eventData);
+        float fval = event_float->data;
+        eventData += sizeof(android_event_int_t);
+        eventDataLen -= sizeof(android_event_int_t);
 
         outCount = snprintf(outBuf, outBufLen, "%f", fval);
         if (outCount < outBufLen) {
@@ -776,12 +776,11 @@
     case EVENT_TYPE_STRING:
       /* UTF-8 chars, not NULL-terminated */
       {
-        unsigned int strLen;
-
-        if (eventDataLen < 4) return -1;
-        strLen = *reinterpret_cast<const uint32_t*>(eventData);
-        eventData += 4;
-        eventDataLen -= 4;
+        if (eventDataLen < sizeof(android_event_string_t)) return -1;
+        auto* event_string = reinterpret_cast<const android_event_string_t*>(eventData);
+        unsigned int strLen = event_string->length;
+        eventData += sizeof(android_event_string_t);
+        eventDataLen -= sizeof(android_event_string_t);
 
         if (eventDataLen < strLen) {
           result = -1; /* mark truncated */
@@ -814,20 +813,19 @@
     case EVENT_TYPE_LIST:
       /* N items, all different types */
       {
-        unsigned char count;
-        int i;
+        if (eventDataLen < sizeof(android_event_list_t)) return -1;
+        auto* event_list = reinterpret_cast<const android_event_list_t*>(eventData);
 
-        if (eventDataLen < 1) return -1;
-
-        count = *eventData++;
-        eventDataLen--;
+        int8_t count = event_list->element_count;
+        eventData += sizeof(android_event_list_t);
+        eventDataLen -= sizeof(android_event_list_t);
 
         if (outBufLen <= 0) goto no_room;
 
         *outBuf++ = '[';
         outBufLen--;
 
-        for (i = 0; i < count; i++) {
+        for (int i = 0; i < count; i++) {
           result = android_log_printBinaryEvent(&eventData, &eventDataLen, &outBuf, &outBufLen,
                                                 fmtStr, fmtLen);
           if (result != 0) goto bail;
@@ -1017,10 +1015,11 @@
     }
   }
   inCount = buf->len;
-  if (inCount < 4) return -1;
-  tagIndex = *reinterpret_cast<const uint32_t*>(eventData);
-  eventData += 4;
-  inCount -= 4;
+  if (inCount < sizeof(android_event_header_t)) return -1;
+  auto* event_header = reinterpret_cast<const android_event_header_t*>(eventData);
+  tagIndex = event_header->tag;
+  eventData += sizeof(android_event_header_t);
+  inCount -= sizeof(android_event_header_t);
 
   entry->tagLen = 0;
   entry->tag = NULL;
diff --git a/liblog/pmsg_reader.cpp b/liblog/pmsg_reader.cpp
index 2db45a1..9c5bc95 100644
--- a/liblog/pmsg_reader.cpp
+++ b/liblog/pmsg_reader.cpp
@@ -40,9 +40,9 @@
     .name = "pmsg",
     .available = pmsgAvailable,
     .version = pmsgVersion,
+    .close = pmsgClose,
     .read = pmsgRead,
     .poll = NULL,
-    .close = pmsgClose,
     .clear = pmsgClear,
     .setSize = NULL,
     .getSize = NULL,
diff --git a/liblog/tests/Android.bp b/liblog/tests/Android.bp
index 45f09f2..394fa93 100644
--- a/liblog/tests/Android.bp
+++ b/liblog/tests/Android.bp
@@ -68,6 +68,7 @@
         "libbase",
     ],
     static_libs: ["liblog"],
+    isolated: true,
 }
 
 // Build tests for the device (with .so). Run with:
diff --git a/liblog/tests/liblog_test.cpp b/liblog/tests/liblog_test.cpp
index 34fb909..063c132 100644
--- a/liblog/tests/liblog_test.cpp
+++ b/liblog/tests/liblog_test.cpp
@@ -27,10 +27,12 @@
 #include <sys/types.h>
 #include <unistd.h>
 
+#include <memory>
 #include <string>
 
 #include <android-base/file.h>
 #include <android-base/macros.h>
+#include <android-base/scopeguard.h>
 #include <android-base/stringprintf.h>
 #ifdef __ANDROID__  // includes sys/properties.h which does not exist outside
 #include <cutils/properties.h>
@@ -42,6 +44,10 @@
 #include <private/android_filesystem_config.h>
 #include <private/android_logger.h>
 
+using android::base::make_scope_guard;
+
+// #define ENABLE_FLAKY_TESTS
+
 // enhanced version of LOG_FAILURE_RETRY to add support for EAGAIN and
 // non-syscall libs. Since we are only using this in the emergency of
 // a signal to stuff a terminating code into the logs, we will spin rather
@@ -56,6 +62,79 @@
     _rc;                                                                 \
   })
 
+// This function is meant to be used for most log tests, it does the following:
+// 1) Open the log_buffer with a blocking reader
+// 2) Write the messages via write_messages
+// 3) Set an alarm for 2 seconds as a timeout
+// 4) Read until check_message returns true, which should be used to indicate the target message
+//    is found
+// 5) Open log_buffer with a non_blocking reader and dump all messages
+// 6) Count the number of times check_messages returns true for these messages and assert it's
+//    only 1.
+template <typename FWrite, typename FCheck>
+static void RunLogTests(log_id_t log_buffer, FWrite write_messages, FCheck check_message) {
+  pid_t pid = getpid();
+
+  // std::unique_ptr doesn't let you provide a pointer to a deleter (android_logger_list_close()) if
+  // the type (struct logger_list) is an incomplete type, so we create ListCloser instead.
+  struct ListCloser {
+    void operator()(struct logger_list* list) { android_logger_list_close(list); }
+  };
+  auto logger_list = std::unique_ptr<struct logger_list, ListCloser>{
+      android_logger_list_open(log_buffer, ANDROID_LOG_RDONLY, 1000, pid)};
+  ASSERT_TRUE(logger_list);
+
+  write_messages();
+
+  alarm(2);
+  auto alarm_guard = android::base::make_scope_guard([] { alarm(0); });
+  bool found = false;
+  while (!found) {
+    log_msg log_msg;
+    ASSERT_GT(android_logger_list_read(logger_list.get(), &log_msg), 0);
+
+    ASSERT_EQ(log_buffer, log_msg.id());
+    ASSERT_EQ(pid, log_msg.entry.pid);
+
+    // TODO: Should this be an assert?
+    if (log_msg.msg() == nullptr) {
+      continue;
+    }
+
+    check_message(log_msg, &found);
+  }
+
+  auto logger_list_non_block = std::unique_ptr<struct logger_list, ListCloser>{
+      android_logger_list_open(log_buffer, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)};
+  ASSERT_TRUE(logger_list_non_block);
+
+  size_t count = 0;
+  while (true) {
+    log_msg log_msg;
+    auto ret = android_logger_list_read(logger_list_non_block.get(), &log_msg);
+    if (ret == -EAGAIN) {
+      break;
+    }
+    ASSERT_GT(ret, 0);
+
+    ASSERT_EQ(log_buffer, log_msg.id());
+    ASSERT_EQ(pid, log_msg.entry.pid);
+
+    // TODO: Should this be an assert?
+    if (log_msg.msg() == nullptr) {
+      continue;
+    }
+
+    found = false;
+    check_message(log_msg, &found);
+    if (found) {
+      ++count;
+    }
+  }
+
+  EXPECT_EQ(1U, count);
+}
+
 TEST(liblog, __android_log_btwrite) {
   int intBuf = 0xDEADBEEF;
   EXPECT_LT(0,
@@ -63,11 +142,9 @@
   long long longBuf = 0xDEADBEEFA55A5AA5;
   EXPECT_LT(
       0, __android_log_btwrite(0, EVENT_TYPE_LONG, &longBuf, sizeof(longBuf)));
-  usleep(1000);
   char Buf[] = "\20\0\0\0DeAdBeEfA55a5aA5";
   EXPECT_LT(0,
             __android_log_btwrite(0, EVENT_TYPE_STRING, Buf, sizeof(Buf) - 1));
-  usleep(1000);
 }
 
 #if defined(__ANDROID__)
@@ -141,73 +218,60 @@
 
 TEST(liblog, __android_log_btwrite__android_logger_list_read) {
 #ifdef __ANDROID__
-  struct logger_list* logger_list;
-
-  pid_t pid = getpid();
-
-  ASSERT_TRUE(NULL !=
-              (logger_list = android_logger_list_open(
-                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
-                   1000, pid)));
-
   log_time ts(CLOCK_MONOTONIC);
-  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
-  // Check that we can close and reopen the logger
-  bool logdwActiveAfter__android_log_btwrite;
-  if (getuid() == AID_ROOT) {
-    tested__android_log_close = true;
-#ifndef NO_PSTORE
-    bool pmsgActiveAfter__android_log_btwrite = isPmsgActive();
-    EXPECT_TRUE(pmsgActiveAfter__android_log_btwrite);
-#endif /* NO_PSTORE */
-    logdwActiveAfter__android_log_btwrite = isLogdwActive();
-    EXPECT_TRUE(logdwActiveAfter__android_log_btwrite);
-  } else if (!tested__android_log_close) {
-    fprintf(stderr, "WARNING: can not test __android_log_close()\n");
-  }
-  __android_log_close();
-  if (getuid() == AID_ROOT) {
-#ifndef NO_PSTORE
-    bool pmsgActiveAfter__android_log_close = isPmsgActive();
-    EXPECT_FALSE(pmsgActiveAfter__android_log_close);
-#endif /* NO_PSTORE */
-    bool logdwActiveAfter__android_log_close = isLogdwActive();
-    EXPECT_FALSE(logdwActiveAfter__android_log_close);
-  }
+  log_time ts1(ts);
 
-  log_time ts1(CLOCK_MONOTONIC);
-  EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts1, sizeof(ts1)));
-  if (getuid() == AID_ROOT) {
+  auto write_function = [&] {
+    EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
+    // Check that we can close and reopen the logger
+    bool logdwActiveAfter__android_log_btwrite;
+    if (getuid() == AID_ROOT) {
+      tested__android_log_close = true;
 #ifndef NO_PSTORE
-    bool pmsgActiveAfter__android_log_btwrite = isPmsgActive();
-    EXPECT_TRUE(pmsgActiveAfter__android_log_btwrite);
+      bool pmsgActiveAfter__android_log_btwrite = isPmsgActive();
+      EXPECT_TRUE(pmsgActiveAfter__android_log_btwrite);
 #endif /* NO_PSTORE */
-    logdwActiveAfter__android_log_btwrite = isLogdwActive();
-    EXPECT_TRUE(logdwActiveAfter__android_log_btwrite);
-  }
-  usleep(1000000);
+      logdwActiveAfter__android_log_btwrite = isLogdwActive();
+      EXPECT_TRUE(logdwActiveAfter__android_log_btwrite);
+    } else if (!tested__android_log_close) {
+      fprintf(stderr, "WARNING: can not test __android_log_close()\n");
+    }
+    __android_log_close();
+    if (getuid() == AID_ROOT) {
+#ifndef NO_PSTORE
+      bool pmsgActiveAfter__android_log_close = isPmsgActive();
+      EXPECT_FALSE(pmsgActiveAfter__android_log_close);
+#endif /* NO_PSTORE */
+      bool logdwActiveAfter__android_log_close = isLogdwActive();
+      EXPECT_FALSE(logdwActiveAfter__android_log_close);
+    }
+
+    ts1 = log_time(CLOCK_MONOTONIC);
+    EXPECT_LT(0, __android_log_btwrite(0, EVENT_TYPE_LONG, &ts1, sizeof(ts1)));
+    if (getuid() == AID_ROOT) {
+#ifndef NO_PSTORE
+      bool pmsgActiveAfter__android_log_btwrite = isPmsgActive();
+      EXPECT_TRUE(pmsgActiveAfter__android_log_btwrite);
+#endif /* NO_PSTORE */
+      logdwActiveAfter__android_log_btwrite = isLogdwActive();
+      EXPECT_TRUE(logdwActiveAfter__android_log_btwrite);
+    }
+  };
 
   int count = 0;
   int second_count = 0;
 
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-      break;
-    }
-
-    EXPECT_EQ(log_msg.entry.pid, pid);
-
+  auto check_function = [&](log_msg log_msg, bool* found) {
     if ((log_msg.entry.len != sizeof(android_log_event_long_t)) ||
         (log_msg.id() != LOG_ID_EVENTS)) {
-      continue;
+      return;
     }
 
     android_log_event_long_t* eventData;
     eventData = reinterpret_cast<android_log_event_long_t*>(log_msg.msg());
 
     if (!eventData || (eventData->payload.type != EVENT_TYPE_LONG)) {
-      continue;
+      return;
     }
 
     log_time tx(reinterpret_cast<char*>(&eventData->payload.data));
@@ -216,12 +280,50 @@
     } else if (ts1 == tx) {
       ++second_count;
     }
-  }
 
-  EXPECT_EQ(1, count);
-  EXPECT_EQ(1, second_count);
+    if (count == 1 && second_count == 1) {
+      count = 0;
+      second_count = 0;
+      *found = true;
+    }
+  };
 
-  android_logger_list_close(logger_list);
+  RunLogTests(LOG_ID_EVENTS, write_function, check_function);
+
+#else
+  GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+}
+
+TEST(liblog, __android_log_write__android_logger_list_read) {
+#ifdef __ANDROID__
+  pid_t pid = getpid();
+
+  struct timespec ts;
+  clock_gettime(CLOCK_MONOTONIC, &ts);
+  std::string buf = android::base::StringPrintf("pid=%u ts=%ld.%09ld", pid, ts.tv_sec, ts.tv_nsec);
+  static const char tag[] = "liblog.__android_log_write__android_logger_list_read";
+  static const char prio = ANDROID_LOG_DEBUG;
+
+  std::string expected_message =
+      std::string(&prio, sizeof(prio)) + tag + std::string("", 1) + buf + std::string("", 1);
+
+  auto write_function = [&] { ASSERT_LT(0, __android_log_write(prio, tag, buf.c_str())); };
+
+  auto check_function = [&](log_msg log_msg, bool* found) {
+    if (log_msg.entry.len != expected_message.length()) {
+      return;
+    }
+
+    if (expected_message != std::string(log_msg.msg(), log_msg.entry.len)) {
+      return;
+    }
+
+    *found = true;
+  };
+
+  RunLogTests(LOG_ID_MAIN, write_function, check_function);
+
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
@@ -229,18 +331,10 @@
 
 static void bswrite_test(const char* message) {
 #ifdef __ANDROID__
-  struct logger_list* logger_list;
-
   pid_t pid = getpid();
 
-  ASSERT_TRUE(NULL !=
-              (logger_list = android_logger_list_open(
-                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
-                   1000, pid)));
-
   log_time ts(android_log_clockid());
 
-  EXPECT_LT(0, __android_log_bswrite(0, message));
   size_t num_lines = 1, size = 0, length = 0, total = 0;
   const char* cp = message;
   while (*cp) {
@@ -262,36 +356,25 @@
     ++cp;
     ++total;
   }
-  usleep(1000000);
 
-  int count = 0;
+  auto write_function = [&] { EXPECT_LT(0, __android_log_bswrite(0, message)); };
 
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-      break;
-    }
-
-    EXPECT_EQ(log_msg.entry.pid, pid);
-
-    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
-        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
-        ((size_t)log_msg.entry.len !=
-         (sizeof(android_log_event_string_t) + length)) ||
-        (log_msg.id() != LOG_ID_EVENTS)) {
-      continue;
+  auto check_function = [&](log_msg log_msg, bool* found) {
+    if ((size_t)log_msg.entry.len != (sizeof(android_log_event_string_t) + length) ||
+        log_msg.id() != LOG_ID_EVENTS) {
+      return;
     }
 
     android_log_event_string_t* eventData;
     eventData = reinterpret_cast<android_log_event_string_t*>(log_msg.msg());
 
     if (!eventData || (eventData->type != EVENT_TYPE_STRING)) {
-      continue;
+      return;
     }
 
     size_t len = eventData->length;
     if (len == total) {
-      ++count;
+      *found = true;
 
       AndroidLogFormat* logformat = android_log_format_new();
       EXPECT_TRUE(NULL != logformat);
@@ -318,11 +401,10 @@
       }
       android_log_format_free(logformat);
     }
-  }
+  };
 
-  EXPECT_EQ(1, count);
+  RunLogTests(LOG_ID_EVENTS, write_function, check_function);
 
-  android_logger_list_close(logger_list);
 #else
   message = NULL;
   GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -351,20 +433,14 @@
 
 static void buf_write_test(const char* message) {
 #ifdef __ANDROID__
-  struct logger_list* logger_list;
-
   pid_t pid = getpid();
 
-  ASSERT_TRUE(
-      NULL !=
-      (logger_list = android_logger_list_open(
-           LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
   static const char tag[] = "TEST__android_log_buf_write";
   log_time ts(android_log_clockid());
 
-  EXPECT_LT(
-      0, __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_INFO, tag, message));
+  auto write_function = [&] {
+    EXPECT_LT(0, __android_log_buf_write(LOG_ID_MAIN, ANDROID_LOG_INFO, tag, message));
+  };
   size_t num_lines = 1, size = 0, length = 0;
   const char* cp = message;
   while (*cp) {
@@ -381,26 +457,13 @@
     }
     ++cp;
   }
-  usleep(1000000);
 
-  int count = 0;
-
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-      break;
+  auto check_function = [&](log_msg log_msg, bool* found) {
+    if ((size_t)log_msg.entry.len != (sizeof(tag) + length + 2) || log_msg.id() != LOG_ID_MAIN) {
+      return;
     }
 
-    ASSERT_EQ(log_msg.entry.pid, pid);
-
-    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
-        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
-        ((size_t)log_msg.entry.len != (sizeof(tag) + length + 2)) ||
-        (log_msg.id() != LOG_ID_MAIN)) {
-      continue;
-    }
-
-    ++count;
+    *found = true;
 
     AndroidLogFormat* logformat = android_log_format_new();
     EXPECT_TRUE(NULL != logformat);
@@ -417,11 +480,10 @@
                 android_log_printLogLine(logformat, fileno(stderr), &entry));
     }
     android_log_format_free(logformat);
-  }
+  };
 
-  EXPECT_EQ(1, count);
+  RunLogTests(LOG_ID_MAIN, write_function, check_function);
 
-  android_logger_list_close(logger_list);
 #else
   message = NULL;
   GTEST_LOG_(INFO) << "This test does nothing.\n";
@@ -440,6 +502,7 @@
   buf_write_test("\n Hello World \n");
 }
 
+#ifdef ENABLE_FLAKY_TESTS
 #ifdef __ANDROID__
 static unsigned signaled;
 static log_time signal_time;
@@ -749,12 +812,8 @@
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif  // ENABLE_FLAKY_TESTS
 
-#ifdef __ANDROID__
-static const char max_payload_tag[] = "TEST_max_payload_and_longish_tag_XXXX";
-#define SIZEOF_MAX_PAYLOAD_BUF \
-  (LOGGER_ENTRY_MAX_PAYLOAD - sizeof(max_payload_tag) - 1)
-#endif
 static const char max_payload_buf[] =
     "LEONATO\n\
 I learn in this letter that Don Peter of Arragon\n\
@@ -887,39 +946,28 @@
 when you depart from me, sorrow abides and happiness\n\
 takes his leave.";
 
+#ifdef ENABLE_FLAKY_TESTS
 TEST(liblog, max_payload) {
 #ifdef __ANDROID__
+  static const char max_payload_tag[] = "TEST_max_payload_and_longish_tag_XXXX";
+#define SIZEOF_MAX_PAYLOAD_BUF (LOGGER_ENTRY_MAX_PAYLOAD - sizeof(max_payload_tag) - 1)
+
   pid_t pid = getpid();
   char tag[sizeof(max_payload_tag)];
   memcpy(tag, max_payload_tag, sizeof(tag));
   snprintf(tag + sizeof(tag) - 5, 5, "%04X", pid & 0xFFFF);
 
-  LOG_FAILURE_RETRY(__android_log_buf_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO,
-                                            tag, max_payload_buf));
-  sleep(2);
+  auto write_function = [&] {
+    LOG_FAILURE_RETRY(
+        __android_log_buf_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO, tag, max_payload_buf));
+  };
 
-  struct logger_list* logger_list;
-
-  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-                           LOG_ID_SYSTEM, ANDROID_LOG_RDONLY, 100, 0)));
-
-  bool matches = false;
   ssize_t max_len = 0;
-
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-      break;
-    }
-
-    if ((log_msg.entry.pid != pid) || (log_msg.id() != LOG_ID_SYSTEM)) {
-      continue;
-    }
-
+  auto check_function = [&](log_msg log_msg, bool* found) {
     char* data = log_msg.msg();
 
     if (!data || strcmp(++data, tag)) {
-      continue;
+      return;
     }
 
     data += strlen(data) + 1;
@@ -936,56 +984,32 @@
     }
 
     if (max_len > 512) {
-      matches = true;
-      break;
+      *found = true;
     }
-  }
+  };
 
-  android_logger_list_close(logger_list);
-
-  EXPECT_EQ(true, matches);
+  RunLogTests(LOG_ID_SYSTEM, write_function, check_function);
 
   EXPECT_LE(SIZEOF_MAX_PAYLOAD_BUF, static_cast<size_t>(max_len));
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif  // ENABLE_FLAKY_TESTS
 
 TEST(liblog, __android_log_buf_print__maxtag) {
 #ifdef __ANDROID__
-  struct logger_list* logger_list;
+  auto write_function = [&] {
+    EXPECT_LT(0, __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO, max_payload_buf,
+                                         max_payload_buf));
+  };
 
-  pid_t pid = getpid();
-
-  ASSERT_TRUE(
-      NULL !=
-      (logger_list = android_logger_list_open(
-           LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-  log_time ts(android_log_clockid());
-
-  EXPECT_LT(0, __android_log_buf_print(LOG_ID_MAIN, ANDROID_LOG_INFO,
-                                       max_payload_buf, max_payload_buf));
-  usleep(1000000);
-
-  int count = 0;
-
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-      break;
+  auto check_function = [&](log_msg log_msg, bool* found) {
+    if ((size_t)log_msg.entry.len < LOGGER_ENTRY_MAX_PAYLOAD) {
+      return;
     }
 
-    ASSERT_EQ(log_msg.entry.pid, pid);
-
-    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
-        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
-        ((size_t)log_msg.entry.len < LOGGER_ENTRY_MAX_PAYLOAD) ||
-        (log_msg.id() != LOG_ID_MAIN)) {
-      continue;
-    }
-
-    ++count;
+    *found = true;
 
     AndroidLogFormat* logformat = android_log_format_new();
     EXPECT_TRUE(NULL != logformat);
@@ -1003,16 +1027,18 @@
       EXPECT_GT(LOGGER_ENTRY_MAX_PAYLOAD * 13 / 8, printLogLine);
     }
     android_log_format_free(logformat);
-  }
+  };
 
-  EXPECT_EQ(1, count);
+  RunLogTests(LOG_ID_MAIN, write_function, check_function);
 
-  android_logger_list_close(logger_list);
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
 
+// TODO: This test is tautological. android_logger_list_read() calls recv() with
+// LOGGER_ENTRY_MAX_PAYLOAD as its size argument, so it's not possible for this test to read a
+// payload larger than that size.
 TEST(liblog, too_big_payload) {
 #ifdef __ANDROID__
   pid_t pid = getpid();
@@ -1022,32 +1048,18 @@
   snprintf(tag + sizeof(tag) - 5, 5, "%04X", pid & 0xFFFF);
 
   std::string longString(3266519, 'x');
+  ssize_t ret;
 
-  ssize_t ret = LOG_FAILURE_RETRY(__android_log_buf_write(
-      LOG_ID_SYSTEM, ANDROID_LOG_INFO, tag, longString.c_str()));
+  auto write_function = [&] {
+    ret = LOG_FAILURE_RETRY(
+        __android_log_buf_write(LOG_ID_SYSTEM, ANDROID_LOG_INFO, tag, longString.c_str()));
+  };
 
-  struct logger_list* logger_list;
-
-  ASSERT_TRUE(NULL != (logger_list = android_logger_list_open(
-                           LOG_ID_SYSTEM,
-                           ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 100, 0)));
-
-  ssize_t max_len = 0;
-
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-      break;
-    }
-
-    if ((log_msg.entry.pid != pid) || (log_msg.id() != LOG_ID_SYSTEM)) {
-      continue;
-    }
-
+  auto check_function = [&](log_msg log_msg, bool* found) {
     char* data = log_msg.msg();
 
     if (!data || strcmp(++data, tag)) {
-      continue;
+      return;
     }
 
     data += strlen(data) + 1;
@@ -1059,28 +1071,25 @@
       ++right;
     }
 
-    if (max_len <= (left - data)) {
-      max_len = left - data + 1;
+    ssize_t len = left - data + 1;
+    // Check that we don't see any entries larger than the max payload.
+    EXPECT_LE(static_cast<size_t>(len), LOGGER_ENTRY_MAX_PAYLOAD - sizeof(big_payload_tag));
+
+    // Once we've found our expected entry, break.
+    if (len == LOGGER_ENTRY_MAX_PAYLOAD - sizeof(big_payload_tag)) {
+      EXPECT_EQ(ret, len + static_cast<ssize_t>(sizeof(big_payload_tag)));
+      *found = true;
     }
-  }
+  };
 
-  android_logger_list_close(logger_list);
+  RunLogTests(LOG_ID_SYSTEM, write_function, check_function);
 
-  EXPECT_LE(LOGGER_ENTRY_MAX_PAYLOAD - sizeof(big_payload_tag),
-            static_cast<size_t>(max_len));
-
-  // SLOP: Allow the underlying interface to optionally place a
-  // terminating nul at the LOGGER_ENTRY_MAX_PAYLOAD's last byte
-  // or not.
-  if (ret == (max_len + static_cast<ssize_t>(sizeof(big_payload_tag)) - 1)) {
-    --max_len;
-  }
-  EXPECT_EQ(ret, max_len + static_cast<ssize_t>(sizeof(big_payload_tag)));
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
 
+#ifdef ENABLE_FLAKY_TESTS
 TEST(liblog, dual_reader) {
 #ifdef __ANDROID__
 
@@ -1143,7 +1152,9 @@
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif  // ENABLE_FLAKY_TESTS
 
+#ifdef ENABLE_FLAKY_TESTS
 static bool checkPriForTag(AndroidLogFormat* p_format, const char* tag,
                            android_LogPriority pri) {
   return android_log_shouldPrintLine(p_format, tag, pri) &&
@@ -1219,7 +1230,9 @@
 
   android_log_format_free(p_format);
 }
+#endif  // ENABLE_FLAKY_TESTS
 
+#ifdef ENABLE_FLAKY_TESTS
 TEST(liblog, is_loggable) {
 #ifdef __ANDROID__
   static const char tag[] = "is_loggable";
@@ -1507,7 +1520,9 @@
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif  // ENABLE_FLAKY_TESTS
 
+#ifdef ENABLE_FLAKY_TESTS
 // Following tests the specific issues surrounding error handling wrt logd.
 // Kills logd and toss all collected data, equivalent to logcat -b all -c,
 // except we also return errors to the logging callers.
@@ -1604,9 +1619,11 @@
 #endif
 }
 #endif  // __ANDROID__
+#endif  // ENABLE_FLAKY_TESTS
 
 // Below this point we run risks of setuid(AID_SYSTEM) which may affect others.
 
+#ifdef ENABLE_FLAKY_TESTS
 // Do not retest properties, and cannot log into LOG_ID_SECURITY
 TEST(liblog, __security) {
 #ifdef __ANDROID__
@@ -1864,111 +1881,74 @@
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif  // ENABLE_FLAKY_TESTS
 
 #ifdef __ANDROID__
-static void android_errorWriteWithInfoLog_helper(int TAG, const char* SUBTAG,
-                                                 int UID, const char* payload,
-                                                 int DATA_LEN, int& count) {
-  struct logger_list* logger_list;
+static void android_errorWriteWithInfoLog_helper(int tag, const char* subtag, int uid,
+                                                 const char* payload, int data_len) {
+  auto write_function = [&] {
+    int ret = android_errorWriteWithInfoLog(tag, subtag, uid, payload, data_len);
+    ASSERT_LT(0, ret);
+  };
 
-  pid_t pid = getpid();
-
-  count = 0;
-
-  ASSERT_TRUE(NULL !=
-              (logger_list = android_logger_list_open(
-                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
-                   1000, pid)));
-
-  int retval_android_errorWriteWithinInfoLog =
-      android_errorWriteWithInfoLog(TAG, SUBTAG, UID, payload, DATA_LEN);
-  if (payload) {
-    ASSERT_LT(0, retval_android_errorWriteWithinInfoLog);
-  } else {
-    ASSERT_GT(0, retval_android_errorWriteWithinInfoLog);
-  }
-
-  sleep(2);
-
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-      break;
-    }
-
-    char* eventData = log_msg.msg();
-    if (!eventData) {
-      continue;
-    }
-
-    char* original = eventData;
+  auto check_function = [&](log_msg log_msg, bool* found) {
+    char* event_data = log_msg.msg();
+    char* original = event_data;
 
     // Tag
-    int tag = *reinterpret_cast<int32_t*>(eventData);
-    eventData += 4;
-
-    if (tag != TAG) {
-      continue;
-    }
-
-    if (!payload) {
-      // This tag should not have been written because the data was null
-      ++count;
-      break;
+    auto* event_header = reinterpret_cast<android_event_header_t*>(event_data);
+    event_data += sizeof(android_event_header_t);
+    if (event_header->tag != tag) {
+      return;
     }
 
     // List type
-    ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
-    eventData++;
-
-    // Number of elements in list
-    ASSERT_EQ(3, eventData[0]);
-    eventData++;
+    auto* event_list = reinterpret_cast<android_event_list_t*>(event_data);
+    ASSERT_EQ(EVENT_TYPE_LIST, event_list->type);
+    ASSERT_EQ(3, event_list->element_count);
+    event_data += sizeof(android_event_list_t);
 
     // Element #1: string type for subtag
-    ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-    eventData++;
-
-    unsigned subtag_len = strlen(SUBTAG);
-    if (subtag_len > 32) subtag_len = 32;
-    ASSERT_EQ(subtag_len, *reinterpret_cast<uint32_t*>(eventData));
-    eventData += 4;
-
-    if (memcmp(SUBTAG, eventData, subtag_len)) {
-      continue;
+    auto* event_string_subtag = reinterpret_cast<android_event_string_t*>(event_data);
+    ASSERT_EQ(EVENT_TYPE_STRING, event_string_subtag->type);
+    int32_t subtag_len = strlen(subtag);
+    if (subtag_len > 32) {
+      subtag_len = 32;
     }
-    eventData += subtag_len;
+    ASSERT_EQ(subtag_len, event_string_subtag->length);
+    if (memcmp(subtag, &event_string_subtag->data, subtag_len)) {
+      return;
+    }
+    event_data += sizeof(android_event_string_t) + subtag_len;
 
     // Element #2: int type for uid
-    ASSERT_EQ(EVENT_TYPE_INT, eventData[0]);
-    eventData++;
-
-    ASSERT_EQ(UID, *reinterpret_cast<int32_t*>(eventData));
-    eventData += 4;
+    auto* event_int_uid = reinterpret_cast<android_event_int_t*>(event_data);
+    ASSERT_EQ(EVENT_TYPE_INT, event_int_uid->type);
+    ASSERT_EQ(uid, event_int_uid->data);
+    event_data += sizeof(android_event_int_t);
 
     // Element #3: string type for data
-    ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-    eventData++;
-
-    size_t dataLen = *reinterpret_cast<int32_t*>(eventData);
-    eventData += 4;
-    if (DATA_LEN < 512) ASSERT_EQ(DATA_LEN, (int)dataLen);
-
-    if (memcmp(payload, eventData, dataLen)) {
-      continue;
+    auto* event_string_data = reinterpret_cast<android_event_string_t*>(event_data);
+    ASSERT_EQ(EVENT_TYPE_STRING, event_string_data->type);
+    int32_t message_data_len = event_string_data->length;
+    if (data_len < 512) {
+      ASSERT_EQ(data_len, message_data_len);
     }
+    if (memcmp(payload, &event_string_data->data, message_data_len) != 0) {
+      return;
+    }
+    event_data += sizeof(android_event_string_t);
 
-    if (DATA_LEN >= 512) {
-      eventData += dataLen;
+    if (data_len >= 512) {
+      event_data += message_data_len;
       // 4 bytes for the tag, and max_payload_buf should be truncated.
-      ASSERT_LE(4 + 512, eventData - original);       // worst expectations
-      ASSERT_GT(4 + DATA_LEN, eventData - original);  // must be truncated
+      ASSERT_LE(4 + 512, event_data - original);       // worst expectations
+      ASSERT_GT(4 + data_len, event_data - original);  // must be truncated
     }
+    *found = true;
+  };
 
-    ++count;
-  }
-
-  android_logger_list_close(logger_list);
+  RunLogTests(LOG_ID_EVENTS, write_function, check_function);
 }
 #endif
 
@@ -1983,10 +1963,7 @@
 
 TEST(liblog, android_errorWriteWithInfoLog__android_logger_list_read__typical) {
 #ifdef __ANDROID__
-  int count;
-  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(1), "test-subtag", -1,
-                                       max_payload_buf, 200, count);
-  EXPECT_EQ(1, count);
+  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(1), "test-subtag", -1, max_payload_buf, 200);
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
@@ -1995,23 +1972,20 @@
 TEST(liblog,
      android_errorWriteWithInfoLog__android_logger_list_read__data_too_large) {
 #ifdef __ANDROID__
-  int count;
-  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(2), "test-subtag", -1,
-                                       max_payload_buf, sizeof(max_payload_buf),
-                                       count);
-  EXPECT_EQ(1, count);
+  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(2), "test-subtag", -1, max_payload_buf,
+                                       sizeof(max_payload_buf));
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
 
+// TODO: Do we need to check that we didn't actually write anything if we return a failure here?
 TEST(liblog,
      android_errorWriteWithInfoLog__android_logger_list_read__null_data) {
 #ifdef __ANDROID__
-  int count;
-  android_errorWriteWithInfoLog_helper(UNIQUE_TAG(3), "test-subtag", -1, NULL,
-                                       200, count);
-  EXPECT_EQ(0, count);
+  int retval_android_errorWriteWithinInfoLog =
+      android_errorWriteWithInfoLog(UNIQUE_TAG(3), "test-subtag", -1, nullptr, 200);
+  ASSERT_GT(0, retval_android_errorWriteWithinInfoLog);
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
@@ -2020,11 +1994,8 @@
 TEST(liblog,
      android_errorWriteWithInfoLog__android_logger_list_read__subtag_too_long) {
 #ifdef __ANDROID__
-  int count;
   android_errorWriteWithInfoLog_helper(
-      UNIQUE_TAG(4), "abcdefghijklmnopqrstuvwxyz now i know my abc", -1,
-      max_payload_buf, 200, count);
-  EXPECT_EQ(1, count);
+      UNIQUE_TAG(4), "abcdefghijklmnopqrstuvwxyz now i know my abc", -1, max_payload_buf, 200);
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
@@ -2038,126 +2009,44 @@
   buf_write_test(max_payload_buf);
 }
 
-#ifdef __ANDROID__
-static void android_errorWriteLog_helper(int TAG, const char* SUBTAG,
-                                         int& count) {
-  struct logger_list* logger_list;
-
-  pid_t pid = getpid();
-
-  count = 0;
-
-  // Do a Before and After on the count to measure the effect. Decrement
-  // what we find in Before to set the stage.
-  ASSERT_TRUE(NULL !=
-              (logger_list = android_logger_list_open(
-                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
-                   1000, pid)));
-
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) break;
-
-    char* eventData = log_msg.msg();
-    if (!eventData) continue;
-
-    // Tag
-    int tag = *reinterpret_cast<int32_t*>(eventData);
-    eventData += 4;
-
-    if (tag != TAG) continue;
-
-    if (!SUBTAG) {
-      // This tag should not have been written because the data was null
-      --count;
-      break;
-    }
-
-    // List type
-    eventData++;
-    // Number of elements in list
-    eventData++;
-    // Element #1: string type for subtag
-    eventData++;
-
-    eventData += 4;
-
-    if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) continue;
-    --count;
-  }
-
-  android_logger_list_close(logger_list);
-
-  // Do an After on the count to measure the effect.
-  ASSERT_TRUE(NULL !=
-              (logger_list = android_logger_list_open(
-                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
-                   1000, pid)));
-
-  int retval_android_errorWriteLog = android_errorWriteLog(TAG, SUBTAG);
-  if (SUBTAG) {
-    ASSERT_LT(0, retval_android_errorWriteLog);
-  } else {
-    ASSERT_GT(0, retval_android_errorWriteLog);
-  }
-
-  sleep(2);
-
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-      break;
-    }
-
-    char* eventData = log_msg.msg();
-    if (!eventData) {
-      continue;
-    }
-
-    // Tag
-    int tag = *reinterpret_cast<int32_t*>(eventData);
-    eventData += 4;
-
-    if (tag != TAG) {
-      continue;
-    }
-
-    if (!SUBTAG) {
-      // This tag should not have been written because the data was null
-      ++count;
-      break;
-    }
-
-    // List type
-    ASSERT_EQ(EVENT_TYPE_LIST, eventData[0]);
-    eventData++;
-
-    // Number of elements in list
-    ASSERT_EQ(3, eventData[0]);
-    eventData++;
-
-    // Element #1: string type for subtag
-    ASSERT_EQ(EVENT_TYPE_STRING, eventData[0]);
-    eventData++;
-
-    ASSERT_EQ(strlen(SUBTAG), *reinterpret_cast<uint32_t*>(eventData));
-    eventData += 4;
-
-    if (memcmp(SUBTAG, eventData, strlen(SUBTAG))) {
-      continue;
-    }
-    ++count;
-  }
-
-  android_logger_list_close(logger_list);
-}
-#endif
-
 TEST(liblog, android_errorWriteLog__android_logger_list_read__success) {
 #ifdef __ANDROID__
-  int count;
-  android_errorWriteLog_helper(UNIQUE_TAG(5), "test-subtag", count);
-  EXPECT_EQ(1, count);
+  int kTag = UNIQUE_TAG(5);
+  const char* kSubTag = "test-subtag";
+
+  auto write_function = [&] {
+    int retval_android_errorWriteLog = android_errorWriteLog(kTag, kSubTag);
+    ASSERT_LT(0, retval_android_errorWriteLog);
+  };
+
+  auto check_function = [&](log_msg log_msg, bool* found) {
+    char* event_data = log_msg.msg();
+
+    // Tag
+    auto* event_header = reinterpret_cast<android_event_header_t*>(event_data);
+    event_data += sizeof(android_event_header_t);
+    if (event_header->tag != kTag) {
+      return;
+    }
+
+    // List type
+    auto* event_list = reinterpret_cast<android_event_list_t*>(event_data);
+    ASSERT_EQ(EVENT_TYPE_LIST, event_list->type);
+    ASSERT_EQ(3, event_list->element_count);
+    event_data += sizeof(android_event_list_t);
+
+    // Element #1: string type for subtag
+    auto* event_string_subtag = reinterpret_cast<android_event_string_t*>(event_data);
+    ASSERT_EQ(EVENT_TYPE_STRING, event_string_subtag->type);
+    int32_t subtag_len = strlen(kSubTag);
+    ASSERT_EQ(subtag_len, event_string_subtag->length);
+    if (memcmp(kSubTag, &event_string_subtag->data, subtag_len) == 0) {
+      *found = true;
+    }
+  };
+
+  RunLogTests(LOG_ID_EVENTS, write_function, check_function);
+
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
@@ -2165,9 +2054,7 @@
 
 TEST(liblog, android_errorWriteLog__android_logger_list_read__null_subtag) {
 #ifdef __ANDROID__
-  int count;
-  android_errorWriteLog_helper(UNIQUE_TAG(6), NULL, count);
-  EXPECT_EQ(0, count);
+  EXPECT_LT(android_errorWriteLog(UNIQUE_TAG(6), nullptr), 0);
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
@@ -2585,52 +2472,21 @@
 
 static void create_android_logger(const char* (*fn)(uint32_t tag,
                                                     size_t& expected_len)) {
-  struct logger_list* logger_list;
+  size_t expected_len;
+  const char* expected_string;
+  auto write_function = [&] {
+    expected_string = (*fn)(1005, expected_len);
+    ASSERT_NE(nullptr, expected_string);
+  };
 
   pid_t pid = getpid();
-
-  ASSERT_TRUE(NULL !=
-              (logger_list = android_logger_list_open(
-                   LOG_ID_EVENTS, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK,
-                   1000, pid)));
-
-#ifdef __ANDROID__
-  log_time ts(android_log_clockid());
-#else
-  log_time ts(CLOCK_REALTIME);
-#endif
-
-  size_t expected_len;
-  const char* expected_string = (*fn)(1005, expected_len);
-
-  if (!expected_string) {
-    android_logger_list_close(logger_list);
-    return;
-  }
-
-  usleep(1000000);
-
-  int count = 0;
-
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) {
-      break;
-    }
-
-    ASSERT_EQ(log_msg.entry.pid, pid);
-
-    if ((log_msg.entry.sec < (ts.tv_sec - 1)) ||
-        ((ts.tv_sec + 1) < log_msg.entry.sec) ||
-        ((size_t)log_msg.entry.len != expected_len) ||
-        (log_msg.id() != LOG_ID_EVENTS)) {
-      continue;
+  auto check_function = [&](log_msg log_msg, bool* found) {
+    if (static_cast<size_t>(log_msg.entry.len) != expected_len) {
+      return;
     }
 
     char* eventData = log_msg.msg();
 
-    ++count;
-
     AndroidLogFormat* logformat = android_log_format_new();
     EXPECT_TRUE(NULL != logformat);
     AndroidLogEntry entry;
@@ -2653,24 +2509,23 @@
     // test buffer reading API
     int buffer_to_string = -1;
     if (eventData) {
-      snprintf(msgBuf, sizeof(msgBuf), "I/[%" PRIu32 "]", *reinterpret_cast<uint32_t*>(eventData));
+      auto* event_header = reinterpret_cast<android_event_header_t*>(eventData);
+      eventData += sizeof(android_event_header_t);
+      snprintf(msgBuf, sizeof(msgBuf), "I/[%" PRId32 "]", event_header->tag);
       print_barrier();
       fprintf(stderr, "%-10s(%5u): ", msgBuf, pid);
       memset(msgBuf, 0, sizeof(msgBuf));
-      buffer_to_string = android_log_buffer_to_string(
-          eventData + sizeof(uint32_t), log_msg.entry.len - sizeof(uint32_t),
-          msgBuf, sizeof(msgBuf));
+      buffer_to_string =
+          android_log_buffer_to_string(eventData, log_msg.entry.len, msgBuf, sizeof(msgBuf));
       fprintf(stderr, "%s\n", msgBuf);
       print_barrier();
     }
     EXPECT_EQ(0, buffer_to_string);
-    EXPECT_EQ(strlen(expected_string), strlen(msgBuf));
-    EXPECT_EQ(0, strcmp(expected_string, msgBuf));
-  }
+    EXPECT_STREQ(expected_string, msgBuf);
+    *found = true;
+  };
 
-  EXPECT_EQ(1, count);
-
-  android_logger_list_close(logger_list);
+  RunLogTests(LOG_ID_EVENTS, write_function, check_function);
 }
 #endif
 
@@ -2754,6 +2609,7 @@
 #endif
 }
 
+#ifdef ENABLE_FLAKY_TESTS
 TEST(liblog, create_android_logger_overflow) {
   android_log_context ctx;
 
@@ -2780,7 +2636,9 @@
   EXPECT_LE(0, android_log_destroy(&ctx));
   ASSERT_TRUE(NULL == ctx);
 }
+#endif  // ENABLE_FLAKY_TESTS
 
+#ifdef ENABLE_FLAKY_TESTS
 #ifdef __ANDROID__
 #ifndef NO_PSTORE
 static const char __pmsg_file[] =
@@ -2858,7 +2716,7 @@
   EXPECT_EQ(ANDROID_LOG_VERBOSE, prio);
   EXPECT_FALSE(NULL == strstr(__pmsg_file, filename));
   EXPECT_EQ(len, sizeof(max_payload_buf));
-  EXPECT_EQ(0, strcmp(max_payload_buf, buf));
+  EXPECT_STREQ(max_payload_buf, buf);
 
   ++signaled;
   if ((len != sizeof(max_payload_buf)) || strcmp(max_payload_buf, buf)) {
@@ -2917,7 +2775,9 @@
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif  // ENABLE_FLAKY_TESTS
 
+#ifdef ENABLE_FLAKY_TESTS
 TEST(liblog, android_lookupEventTagNum) {
 #ifdef __ANDROID__
   EventTagMap* map = android_openEventTagMap(NULL);
@@ -2934,3 +2794,4 @@
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
 }
+#endif  // ENABLE_FLAKY_TESTS
diff --git a/liblog/tests/log_read_test.cpp b/liblog/tests/log_read_test.cpp
index 443c3ea..1be99aa 100644
--- a/liblog/tests/log_read_test.cpp
+++ b/liblog/tests/log_read_test.cpp
@@ -29,54 +29,6 @@
 // Do not use anything in log/log_time.h despite side effects of the above.
 #include <private/android_logger.h>
 
-TEST(liblog, __android_log_write__android_logger_list_read) {
-#ifdef __ANDROID__
-  pid_t pid = getpid();
-
-  struct logger_list* logger_list;
-  ASSERT_TRUE(
-      NULL !=
-      (logger_list = android_logger_list_open(
-           LOG_ID_MAIN, ANDROID_LOG_RDONLY | ANDROID_LOG_NONBLOCK, 1000, pid)));
-
-  struct timespec ts;
-  clock_gettime(CLOCK_MONOTONIC, &ts);
-  std::string buf = android::base::StringPrintf("pid=%u ts=%ld.%09ld", pid,
-                                                ts.tv_sec, ts.tv_nsec);
-  static const char tag[] =
-      "liblog.__android_log_write__android_logger_list_read";
-  static const char prio = ANDROID_LOG_DEBUG;
-  ASSERT_LT(0, __android_log_write(prio, tag, buf.c_str()));
-  usleep(1000000);
-
-  buf = std::string(&prio, sizeof(prio)) + tag + std::string("", 1) + buf +
-        std::string("", 1);
-
-  int count = 0;
-
-  for (;;) {
-    log_msg log_msg;
-    if (android_logger_list_read(logger_list, &log_msg) <= 0) break;
-
-    EXPECT_EQ(log_msg.entry.pid, pid);
-    // There may be a future where we leak "liblog" tagged LOG_ID_EVENT
-    // binary messages through so that logger losses can be correlated?
-    EXPECT_EQ(log_msg.id(), LOG_ID_MAIN);
-
-    if (log_msg.entry.len != buf.length()) continue;
-
-    if (buf != std::string(log_msg.msg(), log_msg.entry.len)) continue;
-
-    ++count;
-  }
-  android_logger_list_close(logger_list);
-
-  EXPECT_EQ(1, count);
-#else
-  GTEST_LOG_(INFO) << "This test does nothing.\n";
-#endif
-}
-
 TEST(liblog, android_logger_get_) {
 #ifdef __ANDROID__
   // This test assumes the log buffers are filled with noise from
diff --git a/liblog/tests/log_wrap_test.cpp b/liblog/tests/log_wrap_test.cpp
index c7dd8e8..e06964f 100644
--- a/liblog/tests/log_wrap_test.cpp
+++ b/liblog/tests/log_wrap_test.cpp
@@ -58,60 +58,27 @@
 
   android_logger_list_close(logger_list);
 }
-
-static void caught_signal(int /* signum */) {
-}
 #endif
 
 // b/64143705 confirm fixed
 TEST(liblog, wrap_mode_blocks) {
 #ifdef __ANDROID__
+  // The read call is expected to take up to 2 hours in the happy case.  There was a previous bug
+  // where it would take only 30 seconds due to an alarm() in logd_reader.cpp.  That alarm has been
+  // removed, so we check here that the read call blocks for a reasonable amount of time (5s).
+
+  struct sigaction ignore = {.sa_handler = [](int) { _exit(0); }};
+  struct sigaction old_sigaction;
+  sigaction(SIGALRM, &ignore, &old_sigaction);
+  alarm(5);
 
   android::base::Timer timer;
+  read_with_wrap();
 
-  // The read call is expected to take up to 2 hours in the happy case.
-  // We only want to make sure it waits for longer than 30s, but we can't
-  // use an alarm as the implementation uses it. So we run the test in
-  // a separate process.
-  pid_t pid = fork();
-
-  if (pid == 0) {
-    // child
-    read_with_wrap();
-    _exit(0);
-  }
-
-  struct sigaction ignore, old_sigaction;
-  memset(&ignore, 0, sizeof(ignore));
-  ignore.sa_handler = caught_signal;
-  sigemptyset(&ignore.sa_mask);
-  sigaction(SIGALRM, &ignore, &old_sigaction);
-  alarm(45);
-
-  bool killed = false;
-  for (;;) {
-    siginfo_t info = {};
-    // This wait will succeed if the child exits, or fail with EINTR if the
-    // alarm goes off first - a loose approximation to a timed wait.
-    int ret = waitid(P_PID, pid, &info, WEXITED);
-    if (ret >= 0 || errno != EINTR) {
-      EXPECT_EQ(ret, 0);
-      if (!killed) {
-        EXPECT_EQ(info.si_status, 0);
-      }
-      break;
-    }
-    unsigned int alarm_left = alarm(0);
-    if (alarm_left > 0) {
-      alarm(alarm_left);
-    } else {
-      kill(pid, SIGTERM);
-      killed = true;
-    }
-  }
+  FAIL() << "read_with_wrap() should not return before the alarm is triggered.";
 
   alarm(0);
-  EXPECT_GT(timer.duration(), std::chrono::seconds(40));
+  sigaction(SIGALRM, &old_sigaction, nullptr);
 #else
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif
diff --git a/libmeminfo/include/meminfo/procmeminfo.h b/libmeminfo/include/meminfo/procmeminfo.h
index f782ec5..8c1280f 100644
--- a/libmeminfo/include/meminfo/procmeminfo.h
+++ b/libmeminfo/include/meminfo/procmeminfo.h
@@ -48,6 +48,10 @@
     // Same as Maps() except, do not read the usage stats for each map.
     const std::vector<Vma>& MapsWithoutUsageStats();
 
+    // If MapsWithoutUsageStats was called, this function will fill in
+    // usage stats for this single vma.
+    bool FillInVmaStats(Vma& vma);
+
     // Collect all 'vma' or 'maps' from /proc/<pid>/smaps and store them in 'maps_'. Returns a
     // constant reference to the vma vector after the collection is done.
     //
diff --git a/libmeminfo/libmeminfo_test.cpp b/libmeminfo/libmeminfo_test.cpp
index cf5341d..378a4cd 100644
--- a/libmeminfo/libmeminfo_test.cpp
+++ b/libmeminfo/libmeminfo_test.cpp
@@ -101,6 +101,33 @@
     }
 }
 
+TEST(ProcMemInfo, MapsUsageFillInLater) {
+    ProcMemInfo proc_mem(pid);
+    const std::vector<Vma>& maps = proc_mem.MapsWithoutUsageStats();
+    EXPECT_FALSE(maps.empty());
+    for (auto& map : maps) {
+        Vma update_map(map);
+        ASSERT_EQ(map.start, update_map.start);
+        ASSERT_EQ(map.end, update_map.end);
+        ASSERT_EQ(map.offset, update_map.offset);
+        ASSERT_EQ(map.flags, update_map.flags);
+        ASSERT_EQ(map.name, update_map.name);
+        ASSERT_EQ(0, update_map.usage.vss);
+        ASSERT_EQ(0, update_map.usage.rss);
+        ASSERT_EQ(0, update_map.usage.pss);
+        ASSERT_EQ(0, update_map.usage.uss);
+        ASSERT_EQ(0, update_map.usage.swap);
+        ASSERT_EQ(0, update_map.usage.swap_pss);
+        ASSERT_EQ(0, update_map.usage.private_clean);
+        ASSERT_EQ(0, update_map.usage.private_dirty);
+        ASSERT_EQ(0, update_map.usage.shared_clean);
+        ASSERT_EQ(0, update_map.usage.shared_dirty);
+        ASSERT_TRUE(proc_mem.FillInVmaStats(update_map));
+        // Check that at least one usage stat was updated.
+        ASSERT_NE(0, update_map.usage.vss);
+    }
+}
+
 TEST(ProcMemInfo, PageMapPresent) {
     static constexpr size_t kNumPages = 20;
     size_t pagesize = getpagesize();
diff --git a/libmeminfo/procmeminfo.cpp b/libmeminfo/procmeminfo.cpp
index 6f68ab4..9e9a705 100644
--- a/libmeminfo/procmeminfo.cpp
+++ b/libmeminfo/procmeminfo.cpp
@@ -244,6 +244,15 @@
     return true;
 }
 
+static int GetPagemapFd(pid_t pid) {
+    std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid);
+    int fd = TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC));
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open " << pagemap_file;
+    }
+    return fd;
+}
+
 bool ProcMemInfo::ReadMaps(bool get_wss, bool use_pageidle, bool get_usage_stats) {
     // Each object reads /proc/<pid>/maps only once. This is done to make sure programs that are
     // running for the lifetime of the system can recycle the objects and don't have to
@@ -269,11 +278,8 @@
         return true;
     }
 
-    std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid_);
-    ::android::base::unique_fd pagemap_fd(
-            TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC)));
-    if (pagemap_fd < 0) {
-        PLOG(ERROR) << "Failed to open " << pagemap_file;
+    ::android::base::unique_fd pagemap_fd(GetPagemapFd(pid_));
+    if (pagemap_fd == -1) {
         return false;
     }
 
@@ -290,6 +296,20 @@
     return true;
 }
 
+bool ProcMemInfo::FillInVmaStats(Vma& vma) {
+    ::android::base::unique_fd pagemap_fd(GetPagemapFd(pid_));
+    if (pagemap_fd == -1) {
+        return false;
+    }
+
+    if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss_, false)) {
+        LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
+                   << vma.end << "]";
+        return false;
+    }
+    return true;
+}
+
 bool ProcMemInfo::ReadVmaStats(int pagemap_fd, Vma& vma, bool get_wss, bool use_pageidle) {
     PageAcct& pinfo = PageAcct::Instance();
     if (get_wss && use_pageidle && !pinfo.InitPageAcct(true)) {
diff --git a/libmeminfo/tools/showmap.cpp b/libmeminfo/tools/showmap.cpp
index 8ea2108..72ab0f3 100644
--- a/libmeminfo/tools/showmap.cpp
+++ b/libmeminfo/tools/showmap.cpp
@@ -18,6 +18,7 @@
 #include <inttypes.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <sys/mman.h>
 #include <sys/signal.h>
 #include <sys/types.h>
 #include <unistd.h>
@@ -139,6 +140,9 @@
     if (!g_verbose && !g_show_addr) {
         printf("   # ");
     }
+    if (g_verbose) {
+        printf(" flags ");
+    }
     printf(" object\n");
 }
 
@@ -150,6 +154,9 @@
     if (!g_verbose && !g_show_addr) {
         printf("---- ");
     }
+    if (g_verbose) {
+        printf("------ ");
+    }
     printf("------------------------------\n");
 }
 
@@ -169,6 +176,18 @@
     if (!g_verbose && !g_show_addr) {
         printf("%4" PRIu32 " ", v.count);
     }
+    if (g_verbose) {
+        if (total) {
+            printf("       ");
+        } else {
+            std::string flags_str("---");
+            if (v.vma.flags & PROT_READ) flags_str[0] = 'r';
+            if (v.vma.flags & PROT_WRITE) flags_str[1] = 'w';
+            if (v.vma.flags & PROT_EXEC) flags_str[2] = 'x';
+
+            printf("%6s ", flags_str.c_str());
+        }
+    }
 }
 
 static int showmap(void) {
diff --git a/libnativebridge/.clang-format b/libnativebridge/.clang-format
deleted file mode 120000
index fd0645f..0000000
--- a/libnativebridge/.clang-format
+++ /dev/null
@@ -1 +0,0 @@
-../.clang-format-2
\ No newline at end of file
diff --git a/libnativebridge/Android.bp b/libnativebridge/Android.bp
deleted file mode 100644
index 10d42e4..0000000
--- a/libnativebridge/Android.bp
+++ /dev/null
@@ -1,61 +0,0 @@
-cc_defaults {
-    name: "libnativebridge-defaults",
-    cflags: [
-        "-Werror",
-        "-Wall",
-    ],
-    cppflags: [
-        "-fvisibility=protected",
-    ],
-    header_libs: ["libnativebridge-headers"],
-    export_header_lib_headers: ["libnativebridge-headers"],
-}
-
-cc_library_headers {
-    name: "libnativebridge-headers",
-
-    host_supported: true,
-    export_include_dirs: ["include"],
-}
-
-cc_library {
-    name: "libnativebridge",
-    defaults: ["libnativebridge-defaults"],
-
-    host_supported: true,
-    srcs: ["native_bridge.cc"],
-    header_libs: [
-        "libbase_headers",
-    ],
-    shared_libs: [
-        "liblog",
-    ],
-    // TODO(jiyong): remove this line after aosp/885921 lands
-    export_include_dirs: ["include"],
-
-    target: {
-        android: {
-            version_script: "libnativebridge.map.txt",
-        },
-        linux: {
-            version_script: "libnativebridge.map.txt",
-        },
-    },
-
-    stubs: {
-        symbol_file: "libnativebridge.map.txt",
-        versions: ["1"],
-    },
-}
-
-// TODO(b/124250621): eliminate the need for this library
-cc_library {
-    name: "libnativebridge_lazy",
-    defaults: ["libnativebridge-defaults"],
-
-    host_supported: false,
-    srcs: ["native_bridge_lazy.cc"],
-    required: ["libnativebridge"],
-}
-
-subdirs = ["tests"]
diff --git a/libnativebridge/CPPLINT.cfg b/libnativebridge/CPPLINT.cfg
deleted file mode 100644
index 578047b..0000000
--- a/libnativebridge/CPPLINT.cfg
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Copyright (C) 2019 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.
-#
-
-filter=-build/header_guard
-filter=-whitespace/comments
-filter=-whitespace/parens
diff --git a/libnativebridge/OWNERS b/libnativebridge/OWNERS
deleted file mode 100644
index daf87f4..0000000
--- a/libnativebridge/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-dimitry@google.com
-eaeltsin@google.com
-ngeoffray@google.com
-oth@google.com
diff --git a/libnativebridge/include/nativebridge/native_bridge.h b/libnativebridge/include/nativebridge/native_bridge.h
deleted file mode 100644
index e9c9500..0000000
--- a/libnativebridge/include/nativebridge/native_bridge.h
+++ /dev/null
@@ -1,418 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVE_BRIDGE_H_
-#define NATIVE_BRIDGE_H_
-
-#include <signal.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include "jni.h"
-
-#ifdef __cplusplus
-namespace android {
-extern "C" {
-#endif  // __cplusplus
-
-struct NativeBridgeRuntimeCallbacks;
-struct NativeBridgeRuntimeValues;
-
-// Function pointer type for sigaction. This is mostly the signature of a signal handler, except
-// for the return type. The runtime needs to know whether the signal was handled or should be given
-// to the chain.
-typedef bool (*NativeBridgeSignalHandlerFn)(int, siginfo_t*, void*);
-
-// Open the native bridge, if any. Should be called by Runtime::Init(). A null library filename
-// signals that we do not want to load a native bridge.
-bool LoadNativeBridge(const char* native_bridge_library_filename,
-                      const struct NativeBridgeRuntimeCallbacks* runtime_callbacks);
-
-// Quick check whether a native bridge will be needed. This is based off of the instruction set
-// of the process.
-bool NeedsNativeBridge(const char* instruction_set);
-
-// Do the early initialization part of the native bridge, if necessary. This should be done under
-// high privileges.
-bool PreInitializeNativeBridge(const char* app_data_dir, const char* instruction_set);
-
-// Initialize the native bridge, if any. Should be called by Runtime::DidForkFromZygote. The JNIEnv*
-// will be used to modify the app environment for the bridge.
-bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set);
-
-// Unload the native bridge, if any. Should be called by Runtime::DidForkFromZygote.
-void UnloadNativeBridge();
-
-// Check whether a native bridge is available (opened or initialized). Requires a prior call to
-// LoadNativeBridge.
-bool NativeBridgeAvailable();
-
-// Check whether a native bridge is available (initialized). Requires a prior call to
-// LoadNativeBridge & InitializeNativeBridge.
-bool NativeBridgeInitialized();
-
-// Load a shared library that is supported by the native bridge.
-//
-// Starting with v3, NativeBridge has two scenarios: with/without namespace.
-// Use NativeBridgeLoadLibraryExt() instead in namespace scenario.
-void* NativeBridgeLoadLibrary(const char* libpath, int flag);
-
-// Get a native bridge trampoline for specified native method.
-void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty, uint32_t len);
-
-// True if native library paths are valid and is for an ABI that is supported by native bridge.
-// The *libpath* must point to a library.
-//
-// Starting with v3, NativeBridge has two scenarios: with/without namespace.
-// Use NativeBridgeIsPathSupported() instead in namespace scenario.
-bool NativeBridgeIsSupported(const char* libpath);
-
-// Returns the version number of the native bridge. This information is available after a
-// successful LoadNativeBridge() and before closing it, that is, as long as NativeBridgeAvailable()
-// returns true. Returns 0 otherwise.
-uint32_t NativeBridgeGetVersion();
-
-// Returns a signal handler that the bridge would like to be managed. Only valid for a native
-// bridge supporting the version 2 interface. Will return null if the bridge does not support
-// version 2, or if it doesn't have a signal handler it wants to be known.
-NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal);
-
-// Returns whether we have seen a native bridge error. This could happen because the library
-// was not found, rejected, could not be initialized and so on.
-//
-// This functionality is mainly for testing.
-bool NativeBridgeError();
-
-// Returns whether a given string is acceptable as a native bridge library filename.
-//
-// This functionality is exposed mainly for testing.
-bool NativeBridgeNameAcceptable(const char* native_bridge_library_filename);
-
-// Decrements the reference count on the dynamic library handler. If the reference count drops
-// to zero then the dynamic library is unloaded. Returns 0 on success and non-zero on error.
-int NativeBridgeUnloadLibrary(void* handle);
-
-// Get last error message of native bridge when fail to load library or search symbol.
-// This is reflection of dlerror() for native bridge.
-const char* NativeBridgeGetError();
-
-struct native_bridge_namespace_t;
-
-// True if native library paths are valid and is for an ABI that is supported by native bridge.
-// Different from NativeBridgeIsSupported(), the *path* here must be a directory containing
-// libraries of an ABI.
-//
-// Starting with v3, NativeBridge has two scenarios: with/without namespace.
-// Use NativeBridgeIsSupported() instead in non-namespace scenario.
-bool NativeBridgeIsPathSupported(const char* path);
-
-// Initializes anonymous namespace.
-// NativeBridge's peer of android_init_anonymous_namespace() of dynamic linker.
-//
-// The anonymous namespace is used in the case when a NativeBridge implementation
-// cannot identify the caller of dlopen/dlsym which happens for the code not loaded
-// by dynamic linker; for example calls from the mono-compiled code.
-//
-// Starting with v3, NativeBridge has two scenarios: with/without namespace.
-// Should not use in non-namespace scenario.
-bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
-                                        const char* anon_ns_library_path);
-
-// Create new namespace in which native libraries will be loaded.
-// NativeBridge's peer of android_create_namespace() of dynamic linker.
-//
-// The libraries in the namespace are searched by folowing order:
-// 1. ld_library_path (Think of this as namespace-local LD_LIBRARY_PATH)
-// 2. In directories specified by DT_RUNPATH of the "needed by" binary.
-// 3. deault_library_path (This of this as namespace-local default library path)
-//
-// Starting with v3, NativeBridge has two scenarios: with/without namespace.
-// Should not use in non-namespace scenario.
-struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
-    const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
-    const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent_ns);
-
-// Creates a link which shares some libraries from one namespace to another.
-// NativeBridge's peer of android_link_namespaces() of dynamic linker.
-//
-// Starting with v3, NativeBridge has two scenarios: with/without namespace.
-// Should not use in non-namespace scenario.
-bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
-                                struct native_bridge_namespace_t* to,
-                                const char* shared_libs_sonames);
-
-// Load a shared library with namespace key that is supported by the native bridge.
-// NativeBridge's peer of android_dlopen_ext() of dynamic linker, only supports namespace
-// extension.
-//
-// Starting with v3, NativeBridge has two scenarios: with/without namespace.
-// Use NativeBridgeLoadLibrary() instead in non-namespace scenario.
-void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
-                                 struct native_bridge_namespace_t* ns);
-
-// Returns exported namespace by the name. This is a reflection of
-// android_get_exported_namespace function. Introduced in v5.
-struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name);
-
-// Native bridge interfaces to runtime.
-struct NativeBridgeCallbacks {
-  // Version number of the interface.
-  uint32_t version;
-
-  // Initialize native bridge. Native bridge's internal implementation must ensure MT safety and
-  // that the native bridge is initialized only once. Thus it is OK to call this interface for an
-  // already initialized native bridge.
-  //
-  // Parameters:
-  //   runtime_cbs [IN] the pointer to NativeBridgeRuntimeCallbacks.
-  // Returns:
-  //   true if initialization was successful.
-  bool (*initialize)(const struct NativeBridgeRuntimeCallbacks* runtime_cbs,
-                     const char* private_dir, const char* instruction_set);
-
-  // Load a shared library that is supported by the native bridge.
-  //
-  // Parameters:
-  //   libpath [IN] path to the shared library
-  //   flag [IN] the stardard RTLD_XXX defined in bionic dlfcn.h
-  // Returns:
-  //   The opaque handle of the shared library if sucessful, otherwise NULL
-  //
-  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
-  // Use loadLibraryExt instead in namespace scenario.
-  void* (*loadLibrary)(const char* libpath, int flag);
-
-  // Get a native bridge trampoline for specified native method. The trampoline has same
-  // sigature as the native method.
-  //
-  // Parameters:
-  //   handle [IN] the handle returned from loadLibrary
-  //   shorty [IN] short descriptor of native method
-  //   len [IN] length of shorty
-  // Returns:
-  //   address of trampoline if successful, otherwise NULL
-  void* (*getTrampoline)(void* handle, const char* name, const char* shorty, uint32_t len);
-
-  // Check whether native library is valid and is for an ABI that is supported by native bridge.
-  //
-  // Parameters:
-  //   libpath [IN] path to the shared library
-  // Returns:
-  //   TRUE if library is supported by native bridge, FALSE otherwise
-  //
-  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
-  // Use isPathSupported instead in namespace scenario.
-  bool (*isSupported)(const char* libpath);
-
-  // Provide environment values required by the app running with native bridge according to the
-  // instruction set.
-  //
-  // Parameters:
-  //   instruction_set [IN] the instruction set of the app
-  // Returns:
-  //   NULL if not supported by native bridge.
-  //   Otherwise, return all environment values to be set after fork.
-  const struct NativeBridgeRuntimeValues* (*getAppEnv)(const char* instruction_set);
-
-  // Added callbacks in version 2.
-
-  // Check whether the bridge is compatible with the given version. A bridge may decide not to be
-  // forwards- or backwards-compatible, and libnativebridge will then stop using it.
-  //
-  // Parameters:
-  //   bridge_version [IN] the version of libnativebridge.
-  // Returns:
-  //   true if the native bridge supports the given version of libnativebridge.
-  bool (*isCompatibleWith)(uint32_t bridge_version);
-
-  // A callback to retrieve a native bridge's signal handler for the specified signal. The runtime
-  // will ensure that the signal handler is being called after the runtime's own handler, but before
-  // all chained handlers. The native bridge should not try to install the handler by itself, as
-  // that will potentially lead to cycles.
-  //
-  // Parameters:
-  //   signal [IN] the signal for which the handler is asked for. Currently, only SIGSEGV is
-  //                 supported by the runtime.
-  // Returns:
-  //   NULL if the native bridge doesn't use a handler or doesn't want it to be managed by the
-  //   runtime.
-  //   Otherwise, a pointer to the signal handler.
-  NativeBridgeSignalHandlerFn (*getSignalHandler)(int signal);
-
-  // Added callbacks in version 3.
-
-  // Decrements the reference count on the dynamic library handler. If the reference count drops
-  // to zero then the dynamic library is unloaded.
-  //
-  // Parameters:
-  //   handle [IN] the handler of a dynamic library.
-  //
-  // Returns:
-  //   0 on success, and nonzero on error.
-  int (*unloadLibrary)(void* handle);
-
-  // Dump the last failure message of native bridge when fail to load library or search symbol.
-  //
-  // Parameters:
-  //
-  // Returns:
-  //   A string describing the most recent error that occurred when load library
-  //   or lookup symbol via native bridge.
-  const char* (*getError)();
-
-  // Check whether library paths are supported by native bridge.
-  //
-  // Parameters:
-  //   library_path [IN] search paths for native libraries (directories separated by ':')
-  // Returns:
-  //   TRUE if libraries within search paths are supported by native bridge, FALSE otherwise
-  //
-  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
-  // Use isSupported instead in non-namespace scenario.
-  bool (*isPathSupported)(const char* library_path);
-
-  // Initializes anonymous namespace at native bridge side.
-  // NativeBridge's peer of android_init_anonymous_namespace() of dynamic linker.
-  //
-  // The anonymous namespace is used in the case when a NativeBridge implementation
-  // cannot identify the caller of dlopen/dlsym which happens for the code not loaded
-  // by dynamic linker; for example calls from the mono-compiled code.
-  //
-  // Parameters:
-  //   public_ns_sonames [IN] the name of "public" libraries.
-  //   anon_ns_library_path [IN] the library search path of (anonymous) namespace.
-  // Returns:
-  //   true if the pass is ok.
-  //   Otherwise, false.
-  //
-  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
-  // Should not use in non-namespace scenario.
-  bool (*initAnonymousNamespace)(const char* public_ns_sonames, const char* anon_ns_library_path);
-
-  // Create new namespace in which native libraries will be loaded.
-  // NativeBridge's peer of android_create_namespace() of dynamic linker.
-  //
-  // Parameters:
-  //   name [IN] the name of the namespace.
-  //   ld_library_path [IN] the first set of library search paths of the namespace.
-  //   default_library_path [IN] the second set of library search path of the namespace.
-  //   type [IN] the attribute of the namespace.
-  //   permitted_when_isolated_path [IN] the permitted path for isolated namespace(if it is).
-  //   parent_ns [IN] the pointer of the parent namespace to be inherited from.
-  // Returns:
-  //   native_bridge_namespace_t* for created namespace or nullptr in the case of error.
-  //
-  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
-  // Should not use in non-namespace scenario.
-  struct native_bridge_namespace_t* (*createNamespace)(const char* name,
-                                                       const char* ld_library_path,
-                                                       const char* default_library_path,
-                                                       uint64_t type,
-                                                       const char* permitted_when_isolated_path,
-                                                       struct native_bridge_namespace_t* parent_ns);
-
-  // Creates a link which shares some libraries from one namespace to another.
-  // NativeBridge's peer of android_link_namespaces() of dynamic linker.
-  //
-  // Parameters:
-  //   from [IN] the namespace where libraries are accessed.
-  //   to [IN] the namespace where libraries are loaded.
-  //   shared_libs_sonames [IN] the libraries to be shared.
-  //
-  // Returns:
-  //   Whether successed or not.
-  //
-  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
-  // Should not use in non-namespace scenario.
-  bool (*linkNamespaces)(struct native_bridge_namespace_t* from,
-                         struct native_bridge_namespace_t* to, const char* shared_libs_sonames);
-
-  // Load a shared library within a namespace.
-  // NativeBridge's peer of android_dlopen_ext() of dynamic linker, only supports namespace
-  // extension.
-  //
-  // Parameters:
-  //   libpath [IN] path to the shared library
-  //   flag [IN] the stardard RTLD_XXX defined in bionic dlfcn.h
-  //   ns [IN] the pointer of the namespace in which the library should be loaded.
-  // Returns:
-  //   The opaque handle of the shared library if sucessful, otherwise NULL
-  //
-  // Starting with v3, NativeBridge has two scenarios: with/without namespace.
-  // Use loadLibrary instead in non-namespace scenario.
-  void* (*loadLibraryExt)(const char* libpath, int flag, struct native_bridge_namespace_t* ns);
-
-  // Get native bridge version of vendor namespace.
-  // The vendor namespace is the namespace used to load vendor public libraries.
-  // With O release this namespace can be different from the default namespace.
-  // For the devices without enable vendor namespaces this function should return null
-  //
-  // Returns:
-  //   vendor namespace or null if it was not set up for the device
-  //
-  // Starting with v5 (Android Q) this function is no longer used.
-  // Use getExportedNamespace() below.
-  struct native_bridge_namespace_t* (*getVendorNamespace)();
-
-  // Get native bridge version of exported namespace. Peer of
-  // android_get_exported_namespace(const char*) function.
-  //
-  // Returns:
-  //   exported namespace or null if it was not set up for the device
-  struct native_bridge_namespace_t* (*getExportedNamespace)(const char* name);
-};
-
-// Runtime interfaces to native bridge.
-struct NativeBridgeRuntimeCallbacks {
-  // Get shorty of a Java method. The shorty is supposed to be persistent in memory.
-  //
-  // Parameters:
-  //   env [IN] pointer to JNIenv.
-  //   mid [IN] Java methodID.
-  // Returns:
-  //   short descriptor for method.
-  const char* (*getMethodShorty)(JNIEnv* env, jmethodID mid);
-
-  // Get number of native methods for specified class.
-  //
-  // Parameters:
-  //   env [IN] pointer to JNIenv.
-  //   clazz [IN] Java class object.
-  // Returns:
-  //   number of native methods.
-  uint32_t (*getNativeMethodCount)(JNIEnv* env, jclass clazz);
-
-  // Get at most 'method_count' native methods for specified class 'clazz'. Results are outputed
-  // via 'methods' [OUT]. The signature pointer in JNINativeMethod is reused as the method shorty.
-  //
-  // Parameters:
-  //   env [IN] pointer to JNIenv.
-  //   clazz [IN] Java class object.
-  //   methods [OUT] array of method with the name, shorty, and fnPtr.
-  //   method_count [IN] max number of elements in methods.
-  // Returns:
-  //   number of method it actually wrote to methods.
-  uint32_t (*getNativeMethods)(JNIEnv* env, jclass clazz, JNINativeMethod* methods,
-                               uint32_t method_count);
-};
-
-#ifdef __cplusplus
-}  // extern "C"
-}  // namespace android
-#endif  // __cplusplus
-
-#endif  // NATIVE_BRIDGE_H_
diff --git a/libnativebridge/libnativebridge.map.txt b/libnativebridge/libnativebridge.map.txt
deleted file mode 100644
index a6841a3..0000000
--- a/libnativebridge/libnativebridge.map.txt
+++ /dev/null
@@ -1,45 +0,0 @@
-#
-# Copyright (C) 2019 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.
-#
-
-# TODO(b/122710865): Most of these uses come from libnativeloader, which should be bundled
-# together with libnativebridge in the APEX. Once this happens, prune this list.
-LIBNATIVEBRIDGE_1 {
-  global:
-    NativeBridgeIsSupported;
-    NativeBridgeLoadLibrary;
-    NativeBridgeUnloadLibrary;
-    NativeBridgeGetError;
-    NativeBridgeIsPathSupported;
-    NativeBridgeCreateNamespace;
-    NativeBridgeGetExportedNamespace;
-    NativeBridgeLinkNamespaces;
-    NativeBridgeLoadLibraryExt;
-    NativeBridgeInitAnonymousNamespace;
-    NativeBridgeInitialized;
-    NativeBridgeGetTrampoline;
-    LoadNativeBridge;
-    PreInitializeNativeBridge;
-    InitializeNativeBridge;
-    NativeBridgeGetVersion;
-    NativeBridgeGetSignalHandler;
-    UnloadNativeBridge;
-    NativeBridgeAvailable;
-    NeedsNativeBridge;
-    NativeBridgeError;
-    NativeBridgeNameAcceptable;
-  local:
-    *;
-};
diff --git a/libnativebridge/native_bridge.cc b/libnativebridge/native_bridge.cc
deleted file mode 100644
index 9adba9a..0000000
--- a/libnativebridge/native_bridge.cc
+++ /dev/null
@@ -1,646 +0,0 @@
-/*
- * Copyright (C) 2014 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.
- */
-
-#define LOG_TAG "nativebridge"
-
-#include "nativebridge/native_bridge.h"
-
-#include <dlfcn.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <sys/mount.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <cstring>
-
-#include <android-base/macros.h>
-#include <log/log.h>
-
-namespace android {
-
-#ifdef __APPLE__
-template <typename T>
-void UNUSED(const T&) {}
-#endif
-
-extern "C" {
-
-// Environment values required by the apps running with native bridge.
-struct NativeBridgeRuntimeValues {
-    const char* os_arch;
-    const char* cpu_abi;
-    const char* cpu_abi2;
-    const char* *supported_abis;
-    int32_t abi_count;
-};
-
-// The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
-static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
-
-enum class NativeBridgeState {
-  kNotSetup,                        // Initial state.
-  kOpened,                          // After successful dlopen.
-  kPreInitialized,                  // After successful pre-initialization.
-  kInitialized,                     // After successful initialization.
-  kClosed                           // Closed or errors.
-};
-
-static constexpr const char* kNotSetupString = "kNotSetup";
-static constexpr const char* kOpenedString = "kOpened";
-static constexpr const char* kPreInitializedString = "kPreInitialized";
-static constexpr const char* kInitializedString = "kInitialized";
-static constexpr const char* kClosedString = "kClosed";
-
-static const char* GetNativeBridgeStateString(NativeBridgeState state) {
-  switch (state) {
-    case NativeBridgeState::kNotSetup:
-      return kNotSetupString;
-
-    case NativeBridgeState::kOpened:
-      return kOpenedString;
-
-    case NativeBridgeState::kPreInitialized:
-      return kPreInitializedString;
-
-    case NativeBridgeState::kInitialized:
-      return kInitializedString;
-
-    case NativeBridgeState::kClosed:
-      return kClosedString;
-  }
-}
-
-// Current state of the native bridge.
-static NativeBridgeState state = NativeBridgeState::kNotSetup;
-
-// The version of NativeBridge implementation.
-// Different Nativebridge interface needs the service of different version of
-// Nativebridge implementation.
-// Used by isCompatibleWith() which is introduced in v2.
-enum NativeBridgeImplementationVersion {
-  // first version, not used.
-  DEFAULT_VERSION = 1,
-  // The version which signal semantic is introduced.
-  SIGNAL_VERSION = 2,
-  // The version which namespace semantic is introduced.
-  NAMESPACE_VERSION = 3,
-  // The version with vendor namespaces
-  VENDOR_NAMESPACE_VERSION = 4,
-  // The version with runtime namespaces
-  RUNTIME_NAMESPACE_VERSION = 5,
-};
-
-// Whether we had an error at some point.
-static bool had_error = false;
-
-// Handle of the loaded library.
-static void* native_bridge_handle = nullptr;
-// Pointer to the callbacks. Available as soon as LoadNativeBridge succeeds, but only initialized
-// later.
-static const NativeBridgeCallbacks* callbacks = nullptr;
-// Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
-static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
-
-// The app's code cache directory.
-static char* app_code_cache_dir = nullptr;
-
-// Code cache directory (relative to the application private directory)
-// Ideally we'd like to call into framework to retrieve this name. However that's considered an
-// implementation detail and will require either hacks or consistent refactorings. We compromise
-// and hard code the directory name again here.
-static constexpr const char* kCodeCacheDir = "code_cache";
-
-// Characters allowed in a native bridge filename. The first character must
-// be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
-static bool CharacterAllowed(char c, bool first) {
-  if (first) {
-    return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
-  } else {
-    return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
-           (c == '.') || (c == '_') || (c == '-');
-  }
-}
-
-static void ReleaseAppCodeCacheDir() {
-  if (app_code_cache_dir != nullptr) {
-    delete[] app_code_cache_dir;
-    app_code_cache_dir = nullptr;
-  }
-}
-
-// We only allow simple names for the library. It is supposed to be a file in
-// /system/lib or /vendor/lib. Only allow a small range of characters, that is
-// names consisting of [a-zA-Z0-9._-] and starting with [a-zA-Z].
-bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
-  const char* ptr = nb_library_filename;
-  if (*ptr == 0) {
-    // Emptry string. Allowed, means no native bridge.
-    return true;
-  } else {
-    // First character must be [a-zA-Z].
-    if (!CharacterAllowed(*ptr, true))  {
-      // Found an invalid fist character, don't accept.
-      ALOGE("Native bridge library %s has been rejected for first character %c",
-            nb_library_filename,
-            *ptr);
-      return false;
-    } else {
-      // For the rest, be more liberal.
-      ptr++;
-      while (*ptr != 0) {
-        if (!CharacterAllowed(*ptr, false)) {
-          // Found an invalid character, don't accept.
-          ALOGE("Native bridge library %s has been rejected for %c", nb_library_filename, *ptr);
-          return false;
-        }
-        ptr++;
-      }
-    }
-    return true;
-  }
-}
-
-// The policy of invoking Nativebridge changed in v3 with/without namespace.
-// Suggest Nativebridge implementation not maintain backward-compatible.
-static bool isCompatibleWith(const uint32_t version) {
-  // Libnativebridge is now designed to be forward-compatible. So only "0" is an unsupported
-  // version.
-  if (callbacks == nullptr || callbacks->version == 0 || version == 0) {
-    return false;
-  }
-
-  // If this is a v2+ bridge, it may not be forwards- or backwards-compatible. Check.
-  if (callbacks->version >= SIGNAL_VERSION) {
-    return callbacks->isCompatibleWith(version);
-  }
-
-  return true;
-}
-
-static void CloseNativeBridge(bool with_error) {
-  state = NativeBridgeState::kClosed;
-  had_error |= with_error;
-  ReleaseAppCodeCacheDir();
-}
-
-bool LoadNativeBridge(const char* nb_library_filename,
-                      const NativeBridgeRuntimeCallbacks* runtime_cbs) {
-  // We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
-  // multi-threaded, so we do not need locking here.
-
-  if (state != NativeBridgeState::kNotSetup) {
-    // Setup has been called before. Ignore this call.
-    if (nb_library_filename != nullptr) {  // Avoids some log-spam for dalvikvm.
-      ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
-            GetNativeBridgeStateString(state));
-    }
-    // Note: counts as an error, even though the bridge may be functional.
-    had_error = true;
-    return false;
-  }
-
-  if (nb_library_filename == nullptr || *nb_library_filename == 0) {
-    CloseNativeBridge(false);
-    return false;
-  } else {
-    if (!NativeBridgeNameAcceptable(nb_library_filename)) {
-      CloseNativeBridge(true);
-    } else {
-      // Try to open the library.
-      void* handle = dlopen(nb_library_filename, RTLD_LAZY);
-      if (handle != nullptr) {
-        callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
-                                                                   kNativeBridgeInterfaceSymbol));
-        if (callbacks != nullptr) {
-          if (isCompatibleWith(NAMESPACE_VERSION)) {
-            // Store the handle for later.
-            native_bridge_handle = handle;
-          } else {
-            callbacks = nullptr;
-            dlclose(handle);
-            ALOGW("Unsupported native bridge interface.");
-          }
-        } else {
-          dlclose(handle);
-        }
-      }
-
-      // Two failure conditions: could not find library (dlopen failed), or could not find native
-      // bridge interface (dlsym failed). Both are an error and close the native bridge.
-      if (callbacks == nullptr) {
-        CloseNativeBridge(true);
-      } else {
-        runtime_callbacks = runtime_cbs;
-        state = NativeBridgeState::kOpened;
-      }
-    }
-    return state == NativeBridgeState::kOpened;
-  }
-}
-
-bool NeedsNativeBridge(const char* instruction_set) {
-  if (instruction_set == nullptr) {
-    ALOGE("Null instruction set in NeedsNativeBridge.");
-    return false;
-  }
-  return strncmp(instruction_set, ABI_STRING, strlen(ABI_STRING) + 1) != 0;
-}
-
-bool PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
-  if (state != NativeBridgeState::kOpened) {
-    ALOGE("Invalid state: native bridge is expected to be opened.");
-    CloseNativeBridge(true);
-    return false;
-  }
-
-  if (app_data_dir_in == nullptr) {
-    ALOGE("Application private directory cannot be null.");
-    CloseNativeBridge(true);
-    return false;
-  }
-
-  // Create the path to the application code cache directory.
-  // The memory will be release after Initialization or when the native bridge is closed.
-  const size_t len = strlen(app_data_dir_in) + strlen(kCodeCacheDir) + 2; // '\0' + '/'
-  app_code_cache_dir = new char[len];
-  snprintf(app_code_cache_dir, len, "%s/%s", app_data_dir_in, kCodeCacheDir);
-
-  // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo.
-  // Failure is not fatal and will keep the native bridge in kPreInitialized.
-  state = NativeBridgeState::kPreInitialized;
-
-#ifndef __APPLE__
-  if (instruction_set == nullptr) {
-    return true;
-  }
-  size_t isa_len = strlen(instruction_set);
-  if (isa_len > 10) {
-    // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
-    // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
-    // be another instruction set in the future.
-    ALOGW("Instruction set %s is malformed, must be less than or equal to 10 characters.",
-          instruction_set);
-    return true;
-  }
-
-  // If the file does not exist, the mount command will fail,
-  // so we save the extra file existence check.
-  char cpuinfo_path[1024];
-
-#if defined(__ANDROID__)
-  snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib"
-#ifdef __LP64__
-      "64"
-#endif  // __LP64__
-      "/%s/cpuinfo", instruction_set);
-#else   // !__ANDROID__
-  // To be able to test on the host, we hardwire a relative path.
-  snprintf(cpuinfo_path, sizeof(cpuinfo_path), "./cpuinfo");
-#endif
-
-  // Bind-mount.
-  if (TEMP_FAILURE_RETRY(mount(cpuinfo_path,        // Source.
-                               "/proc/cpuinfo",     // Target.
-                               nullptr,             // FS type.
-                               MS_BIND,             // Mount flags: bind mount.
-                               nullptr)) == -1) {   // "Data."
-    ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %s", cpuinfo_path, strerror(errno));
-  }
-#else  // __APPLE__
-  UNUSED(instruction_set);
-  ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
-#endif
-
-  return true;
-}
-
-static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
-  if (value != nullptr) {
-    jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
-    if (field_id == nullptr) {
-      env->ExceptionClear();
-      ALOGW("Could not find %s field.", field);
-      return;
-    }
-
-    jstring str = env->NewStringUTF(value);
-    if (str == nullptr) {
-      env->ExceptionClear();
-      ALOGW("Could not create string %s.", value);
-      return;
-    }
-
-    env->SetStaticObjectField(build_class, field_id, str);
-  }
-}
-
-// Set up the environment for the bridged app.
-static void SetupEnvironment(const NativeBridgeCallbacks* callbacks, JNIEnv* env, const char* isa) {
-  // Need a JNIEnv* to do anything.
-  if (env == nullptr) {
-    ALOGW("No JNIEnv* to set up app environment.");
-    return;
-  }
-
-  // Query the bridge for environment values.
-  const struct NativeBridgeRuntimeValues* env_values = callbacks->getAppEnv(isa);
-  if (env_values == nullptr) {
-    return;
-  }
-
-  // Keep the JNIEnv clean.
-  jint success = env->PushLocalFrame(16);  // That should be small and large enough.
-  if (success < 0) {
-    // Out of memory, really borked.
-    ALOGW("Out of memory while setting up app environment.");
-    env->ExceptionClear();
-    return;
-  }
-
-  // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
-  if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
-      env_values->abi_count >= 0) {
-    jclass bclass_id = env->FindClass("android/os/Build");
-    if (bclass_id != nullptr) {
-      SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
-      SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
-    } else {
-      // For example in a host test environment.
-      env->ExceptionClear();
-      ALOGW("Could not find Build class.");
-    }
-  }
-
-  if (env_values->os_arch != nullptr) {
-    jclass sclass_id = env->FindClass("java/lang/System");
-    if (sclass_id != nullptr) {
-      jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setUnchangeableSystemProperty",
-          "(Ljava/lang/String;Ljava/lang/String;)V");
-      if (set_prop_id != nullptr) {
-        // Init os.arch to the value reqired by the apps running with native bridge.
-        env->CallStaticVoidMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
-            env->NewStringUTF(env_values->os_arch));
-      } else {
-        env->ExceptionClear();
-        ALOGW("Could not find System#setUnchangeableSystemProperty.");
-      }
-    } else {
-      env->ExceptionClear();
-      ALOGW("Could not find System class.");
-    }
-  }
-
-  // Make it pristine again.
-  env->PopLocalFrame(nullptr);
-}
-
-bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
-  // We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
-  // point we are not multi-threaded, so we do not need locking here.
-
-  if (state == NativeBridgeState::kPreInitialized) {
-    // Check for code cache: if it doesn't exist try to create it.
-    struct stat st;
-    if (stat(app_code_cache_dir, &st) == -1) {
-      if (errno == ENOENT) {
-        if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
-          ALOGW("Cannot create code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
-          ReleaseAppCodeCacheDir();
-        }
-      } else {
-        ALOGW("Cannot stat code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
-        ReleaseAppCodeCacheDir();
-      }
-    } else if (!S_ISDIR(st.st_mode)) {
-      ALOGW("Code cache is not a directory %s.", app_code_cache_dir);
-      ReleaseAppCodeCacheDir();
-    }
-
-    // If we're still PreInitialized (dind't fail the code cache checks) try to initialize.
-    if (state == NativeBridgeState::kPreInitialized) {
-      if (callbacks->initialize(runtime_callbacks, app_code_cache_dir, instruction_set)) {
-        SetupEnvironment(callbacks, env, instruction_set);
-        state = NativeBridgeState::kInitialized;
-        // We no longer need the code cache path, release the memory.
-        ReleaseAppCodeCacheDir();
-      } else {
-        // Unload the library.
-        dlclose(native_bridge_handle);
-        CloseNativeBridge(true);
-      }
-    }
-  } else {
-    CloseNativeBridge(true);
-  }
-
-  return state == NativeBridgeState::kInitialized;
-}
-
-void UnloadNativeBridge() {
-  // We expect only one place that calls UnloadNativeBridge: Runtime::DidForkFromZygote. At that
-  // point we are not multi-threaded, so we do not need locking here.
-
-  switch(state) {
-    case NativeBridgeState::kOpened:
-    case NativeBridgeState::kPreInitialized:
-    case NativeBridgeState::kInitialized:
-      // Unload.
-      dlclose(native_bridge_handle);
-      CloseNativeBridge(false);
-      break;
-
-    case NativeBridgeState::kNotSetup:
-      // Not even set up. Error.
-      CloseNativeBridge(true);
-      break;
-
-    case NativeBridgeState::kClosed:
-      // Ignore.
-      break;
-  }
-}
-
-bool NativeBridgeError() {
-  return had_error;
-}
-
-bool NativeBridgeAvailable() {
-  return state == NativeBridgeState::kOpened
-      || state == NativeBridgeState::kPreInitialized
-      || state == NativeBridgeState::kInitialized;
-}
-
-bool NativeBridgeInitialized() {
-  // Calls of this are supposed to happen in a state where the native bridge is stable, i.e., after
-  // Runtime::DidForkFromZygote. In that case we do not need a lock.
-  return state == NativeBridgeState::kInitialized;
-}
-
-void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
-  if (NativeBridgeInitialized()) {
-    return callbacks->loadLibrary(libpath, flag);
-  }
-  return nullptr;
-}
-
-void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty,
-                                uint32_t len) {
-  if (NativeBridgeInitialized()) {
-    return callbacks->getTrampoline(handle, name, shorty, len);
-  }
-  return nullptr;
-}
-
-bool NativeBridgeIsSupported(const char* libpath) {
-  if (NativeBridgeInitialized()) {
-    return callbacks->isSupported(libpath);
-  }
-  return false;
-}
-
-uint32_t NativeBridgeGetVersion() {
-  if (NativeBridgeAvailable()) {
-    return callbacks->version;
-  }
-  return 0;
-}
-
-NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
-  if (NativeBridgeInitialized()) {
-    if (isCompatibleWith(SIGNAL_VERSION)) {
-      return callbacks->getSignalHandler(signal);
-    } else {
-      ALOGE("not compatible with version %d, cannot get signal handler", SIGNAL_VERSION);
-    }
-  }
-  return nullptr;
-}
-
-int NativeBridgeUnloadLibrary(void* handle) {
-  if (NativeBridgeInitialized()) {
-    if (isCompatibleWith(NAMESPACE_VERSION)) {
-      return callbacks->unloadLibrary(handle);
-    } else {
-      ALOGE("not compatible with version %d, cannot unload library", NAMESPACE_VERSION);
-    }
-  }
-  return -1;
-}
-
-const char* NativeBridgeGetError() {
-  if (NativeBridgeInitialized()) {
-    if (isCompatibleWith(NAMESPACE_VERSION)) {
-      return callbacks->getError();
-    } else {
-      return "native bridge implementation is not compatible with version 3, cannot get message";
-    }
-  }
-  return "native bridge is not initialized";
-}
-
-bool NativeBridgeIsPathSupported(const char* path) {
-  if (NativeBridgeInitialized()) {
-    if (isCompatibleWith(NAMESPACE_VERSION)) {
-      return callbacks->isPathSupported(path);
-    } else {
-      ALOGE("not compatible with version %d, cannot check via library path", NAMESPACE_VERSION);
-    }
-  }
-  return false;
-}
-
-bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
-                                        const char* anon_ns_library_path) {
-  if (NativeBridgeInitialized()) {
-    if (isCompatibleWith(NAMESPACE_VERSION)) {
-      return callbacks->initAnonymousNamespace(public_ns_sonames, anon_ns_library_path);
-    } else {
-      ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
-    }
-  }
-
-  return false;
-}
-
-native_bridge_namespace_t* NativeBridgeCreateNamespace(const char* name,
-                                                       const char* ld_library_path,
-                                                       const char* default_library_path,
-                                                       uint64_t type,
-                                                       const char* permitted_when_isolated_path,
-                                                       native_bridge_namespace_t* parent_ns) {
-  if (NativeBridgeInitialized()) {
-    if (isCompatibleWith(NAMESPACE_VERSION)) {
-      return callbacks->createNamespace(name,
-                                        ld_library_path,
-                                        default_library_path,
-                                        type,
-                                        permitted_when_isolated_path,
-                                        parent_ns);
-    } else {
-      ALOGE("not compatible with version %d, cannot create namespace %s", NAMESPACE_VERSION, name);
-    }
-  }
-
-  return nullptr;
-}
-
-bool NativeBridgeLinkNamespaces(native_bridge_namespace_t* from, native_bridge_namespace_t* to,
-                                const char* shared_libs_sonames) {
-  if (NativeBridgeInitialized()) {
-    if (isCompatibleWith(NAMESPACE_VERSION)) {
-      return callbacks->linkNamespaces(from, to, shared_libs_sonames);
-    } else {
-      ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
-    }
-  }
-
-  return false;
-}
-
-native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
-  if (!NativeBridgeInitialized()) {
-    return nullptr;
-  }
-
-  if (isCompatibleWith(RUNTIME_NAMESPACE_VERSION)) {
-    return callbacks->getExportedNamespace(name);
-  }
-
-  // sphal is vendor namespace name -> use v4 callback in the case NB callbacks
-  // are not compatible with v5
-  if (isCompatibleWith(VENDOR_NAMESPACE_VERSION) && name != nullptr && strcmp("sphal", name) == 0) {
-    return callbacks->getVendorNamespace();
-  }
-
-  return nullptr;
-}
-
-void* NativeBridgeLoadLibraryExt(const char* libpath, int flag, native_bridge_namespace_t* ns) {
-  if (NativeBridgeInitialized()) {
-    if (isCompatibleWith(NAMESPACE_VERSION)) {
-      return callbacks->loadLibraryExt(libpath, flag, ns);
-    } else {
-      ALOGE("not compatible with version %d, cannot load library in namespace", NAMESPACE_VERSION);
-    }
-  }
-  return nullptr;
-}
-
-}  // extern "C"
-
-}  // namespace android
diff --git a/libnativebridge/native_bridge_lazy.cc b/libnativebridge/native_bridge_lazy.cc
deleted file mode 100644
index 94c8084..0000000
--- a/libnativebridge/native_bridge_lazy.cc
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (C) 2019 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 "nativebridge/native_bridge.h"
-#define LOG_TAG "nativebridge"
-
-#include <dlfcn.h>
-#include <errno.h>
-#include <string.h>
-
-#include <log/log.h>
-
-namespace android {
-
-namespace {
-
-void* GetLibHandle() {
-  static void* handle = dlopen("libnativebridge.so", RTLD_NOW);
-  LOG_FATAL_IF(handle == nullptr, "Failed to load libnativebridge.so: %s", dlerror());
-  return handle;
-}
-
-template <typename FuncPtr>
-FuncPtr GetFuncPtr(const char* function_name) {
-  auto f = reinterpret_cast<FuncPtr>(dlsym(GetLibHandle(), function_name));
-  LOG_FATAL_IF(f == nullptr, "Failed to get address of %s: %s", function_name, dlerror());
-  return f;
-}
-
-#define GET_FUNC_PTR(name) GetFuncPtr<decltype(&name)>(#name)
-
-}  // namespace
-
-bool LoadNativeBridge(const char* native_bridge_library_filename,
-                      const struct NativeBridgeRuntimeCallbacks* runtime_callbacks) {
-  static auto f = GET_FUNC_PTR(LoadNativeBridge);
-  return f(native_bridge_library_filename, runtime_callbacks);
-}
-
-bool NeedsNativeBridge(const char* instruction_set) {
-  static auto f = GET_FUNC_PTR(NeedsNativeBridge);
-  return f(instruction_set);
-}
-
-bool PreInitializeNativeBridge(const char* app_data_dir, const char* instruction_set) {
-  static auto f = GET_FUNC_PTR(PreInitializeNativeBridge);
-  return f(app_data_dir, instruction_set);
-}
-
-bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
-  static auto f = GET_FUNC_PTR(InitializeNativeBridge);
-  return f(env, instruction_set);
-}
-
-void UnloadNativeBridge() {
-  static auto f = GET_FUNC_PTR(UnloadNativeBridge);
-  return f();
-}
-
-bool NativeBridgeAvailable() {
-  static auto f = GET_FUNC_PTR(NativeBridgeAvailable);
-  return f();
-}
-
-bool NativeBridgeInitialized() {
-  static auto f = GET_FUNC_PTR(NativeBridgeInitialized);
-  return f();
-}
-
-void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
-  static auto f = GET_FUNC_PTR(NativeBridgeLoadLibrary);
-  return f(libpath, flag);
-}
-
-void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty, uint32_t len) {
-  static auto f = GET_FUNC_PTR(NativeBridgeGetTrampoline);
-  return f(handle, name, shorty, len);
-}
-
-bool NativeBridgeIsSupported(const char* libpath) {
-  static auto f = GET_FUNC_PTR(NativeBridgeIsSupported);
-  return f(libpath);
-}
-
-uint32_t NativeBridgeGetVersion() {
-  static auto f = GET_FUNC_PTR(NativeBridgeGetVersion);
-  return f();
-}
-
-NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
-  static auto f = GET_FUNC_PTR(NativeBridgeGetSignalHandler);
-  return f(signal);
-}
-
-bool NativeBridgeError() {
-  static auto f = GET_FUNC_PTR(NativeBridgeError);
-  return f();
-}
-
-bool NativeBridgeNameAcceptable(const char* native_bridge_library_filename) {
-  static auto f = GET_FUNC_PTR(NativeBridgeNameAcceptable);
-  return f(native_bridge_library_filename);
-}
-
-int NativeBridgeUnloadLibrary(void* handle) {
-  static auto f = GET_FUNC_PTR(NativeBridgeUnloadLibrary);
-  return f(handle);
-}
-
-const char* NativeBridgeGetError() {
-  static auto f = GET_FUNC_PTR(NativeBridgeGetError);
-  return f();
-}
-
-bool NativeBridgeIsPathSupported(const char* path) {
-  static auto f = GET_FUNC_PTR(NativeBridgeIsPathSupported);
-  return f(path);
-}
-
-bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
-                                        const char* anon_ns_library_path) {
-  static auto f = GET_FUNC_PTR(NativeBridgeInitAnonymousNamespace);
-  return f(public_ns_sonames, anon_ns_library_path);
-}
-
-struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
-    const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
-    const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent_ns) {
-  static auto f = GET_FUNC_PTR(NativeBridgeCreateNamespace);
-  return f(name, ld_library_path, default_library_path, type, permitted_when_isolated_path,
-           parent_ns);
-}
-
-bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
-                                struct native_bridge_namespace_t* to,
-                                const char* shared_libs_sonames) {
-  static auto f = GET_FUNC_PTR(NativeBridgeLinkNamespaces);
-  return f(from, to, shared_libs_sonames);
-}
-
-void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
-                                 struct native_bridge_namespace_t* ns) {
-  static auto f = GET_FUNC_PTR(NativeBridgeLoadLibraryExt);
-  return f(libpath, flag, ns);
-}
-
-struct native_bridge_namespace_t* NativeBridgeGetVendorNamespace() {
-  static auto f = GET_FUNC_PTR(NativeBridgeGetVendorNamespace);
-  return f();
-}
-
-#undef GET_FUNC_PTR
-
-}  // namespace android
diff --git a/libnativebridge/tests/Android.bp b/libnativebridge/tests/Android.bp
deleted file mode 100644
index 2bb8467..0000000
--- a/libnativebridge/tests/Android.bp
+++ /dev/null
@@ -1,110 +0,0 @@
-//
-// Copyright (C) 2017 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-cc_defaults {
-    name: "libnativebridge-dummy-defaults",
-
-    host_supported: true,
-    cflags: [
-        "-Wall",
-        "-Wextra",
-        "-Werror",
-    ],
-    header_libs: ["libnativebridge-headers"],
-    cppflags: ["-fvisibility=protected"],
-}
-
-cc_library_shared {
-    name: "libnativebridge-dummy",
-    srcs: ["DummyNativeBridge.cpp"],
-    defaults: ["libnativebridge-dummy-defaults"],
-}
-
-cc_library_shared {
-    name: "libnativebridge2-dummy",
-    srcs: ["DummyNativeBridge2.cpp"],
-    defaults: ["libnativebridge-dummy-defaults"],
-}
-
-cc_library_shared {
-    name: "libnativebridge3-dummy",
-    srcs: ["DummyNativeBridge3.cpp"],
-    defaults: ["libnativebridge-dummy-defaults"],
-}
-
-// Build the unit tests.
-cc_defaults {
-    name: "libnativebridge-tests-defaults",
-    test_per_src: true,
-
-    cflags: [
-        "-Wall",
-        "-Werror",
-    ],
-
-    srcs: [
-        "CodeCacheCreate_test.cpp",
-        "CodeCacheExists_test.cpp",
-        "CodeCacheStatFail_test.cpp",
-        "CompleteFlow_test.cpp",
-        "InvalidCharsNativeBridge_test.cpp",
-        "NativeBridge2Signal_test.cpp",
-        "NativeBridgeVersion_test.cpp",
-        "NeedsNativeBridge_test.cpp",
-        "PreInitializeNativeBridge_test.cpp",
-        "PreInitializeNativeBridgeFail1_test.cpp",
-        "PreInitializeNativeBridgeFail2_test.cpp",
-        "ReSetupNativeBridge_test.cpp",
-        "UnavailableNativeBridge_test.cpp",
-        "ValidNameNativeBridge_test.cpp",
-        "NativeBridge3UnloadLibrary_test.cpp",
-        "NativeBridge3GetError_test.cpp",
-        "NativeBridge3IsPathSupported_test.cpp",
-        "NativeBridge3InitAnonymousNamespace_test.cpp",
-        "NativeBridge3CreateNamespace_test.cpp",
-        "NativeBridge3LoadLibraryExt_test.cpp",
-    ],
-
-    shared_libs: [
-        "liblog",
-        "libnativebridge-dummy",
-    ],
-    header_libs: ["libbase_headers"],
-}
-
-cc_test {
-    name: "libnativebridge-tests",
-    defaults: ["libnativebridge-tests-defaults"],
-    host_supported: true,
-    shared_libs: ["libnativebridge"],
-}
-
-cc_test {
-    name: "libnativebridge-lazy-tests",
-    defaults: ["libnativebridge-tests-defaults"],
-    shared_libs: ["libnativebridge_lazy"],
-}
-
-// Build the test for the C API.
-cc_test {
-    name: "libnativebridge-api-tests",
-    host_supported: true,
-    test_per_src: true,
-    srcs: [
-        "NativeBridgeApi.c",
-    ],
-    header_libs: ["libnativebridge-headers"],
-}
diff --git a/libnativebridge/tests/CodeCacheCreate_test.cpp b/libnativebridge/tests/CodeCacheCreate_test.cpp
deleted file mode 100644
index 58270c4..0000000
--- a/libnativebridge/tests/CodeCacheCreate_test.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2014 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 "NativeBridgeTest.h"
-
-#include <errno.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-namespace android {
-
-// Tests that the bridge initialization creates the code_cache if it doesn't
-// exists.
-TEST_F(NativeBridgeTest, CodeCacheCreate) {
-    // Make sure that code_cache does not exists
-    struct stat st;
-    ASSERT_EQ(-1, stat(kCodeCache, &st));
-    ASSERT_EQ(ENOENT, errno);
-
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary, nullptr));
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_FALSE(NativeBridgeError());
-
-    // Check that code_cache was created
-    ASSERT_EQ(0, stat(kCodeCache, &st));
-    ASSERT_TRUE(S_ISDIR(st.st_mode));
-
-    // Clean up
-    UnloadNativeBridge();
-    ASSERT_EQ(0, rmdir(kCodeCache));
-
-    ASSERT_FALSE(NativeBridgeError());
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/CodeCacheExists_test.cpp b/libnativebridge/tests/CodeCacheExists_test.cpp
deleted file mode 100644
index 8ba0158..0000000
--- a/libnativebridge/tests/CodeCacheExists_test.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2014 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 "NativeBridgeTest.h"
-
-#include <errno.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-namespace android {
-
-// Tests that the bridge is initialized without errors if the code_cache already
-// exists.
-TEST_F(NativeBridgeTest, CodeCacheExists) {
-    // Make sure that code_cache does not exists
-    struct stat st;
-    ASSERT_EQ(-1, stat(kCodeCache, &st));
-    ASSERT_EQ(ENOENT, errno);
-
-    // Create the code_cache
-    ASSERT_EQ(0, mkdir(kCodeCache, S_IRWXU | S_IRWXG | S_IXOTH));
-
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary, nullptr));
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_FALSE(NativeBridgeError());
-
-    // Check that the code cache is still there
-    ASSERT_EQ(0, stat(kCodeCache, &st));
-    ASSERT_TRUE(S_ISDIR(st.st_mode));
-
-    // Clean up
-    UnloadNativeBridge();
-    ASSERT_EQ(0, rmdir(kCodeCache));
-
-    ASSERT_FALSE(NativeBridgeError());
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/CodeCacheStatFail_test.cpp b/libnativebridge/tests/CodeCacheStatFail_test.cpp
deleted file mode 100644
index 4ea519e..0000000
--- a/libnativebridge/tests/CodeCacheStatFail_test.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2014 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 "NativeBridgeTest.h"
-
-#include <errno.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <fcntl.h>
-
-namespace android {
-
-// Tests that the bridge is initialized without errors if the code_cache is
-// existed as a file.
-TEST_F(NativeBridgeTest, CodeCacheStatFail) {
-    int fd = creat(kCodeCache, O_RDWR);
-    ASSERT_NE(-1, fd);
-    close(fd);
-
-    struct stat st;
-    ASSERT_EQ(-1, stat(kCodeCacheStatFail, &st));
-    ASSERT_EQ(ENOTDIR, errno);
-
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary, nullptr));
-    ASSERT_TRUE(PreInitializeNativeBridge(kCodeCacheStatFail, "isa"));
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_FALSE(NativeBridgeError());
-
-    // Clean up
-    UnloadNativeBridge();
-
-    ASSERT_FALSE(NativeBridgeError());
-    unlink(kCodeCache);
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/CompleteFlow_test.cpp b/libnativebridge/tests/CompleteFlow_test.cpp
deleted file mode 100644
index b033792..0000000
--- a/libnativebridge/tests/CompleteFlow_test.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2014 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 "NativeBridgeTest.h"
-
-#include <unistd.h>
-
-namespace android {
-
-TEST_F(NativeBridgeTest, CompleteFlow) {
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-
-    // Basic calls to check that nothing crashes
-    ASSERT_FALSE(NativeBridgeIsSupported(nullptr));
-    ASSERT_EQ(nullptr, NativeBridgeLoadLibrary(nullptr, 0));
-    ASSERT_EQ(nullptr, NativeBridgeGetTrampoline(nullptr, nullptr, nullptr, 0));
-
-    // Unload
-    UnloadNativeBridge();
-
-    ASSERT_FALSE(NativeBridgeAvailable());
-    ASSERT_FALSE(NativeBridgeError());
-
-    // Clean-up code_cache
-    ASSERT_EQ(0, rmdir(kCodeCache));
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/DummyNativeBridge.cpp b/libnativebridge/tests/DummyNativeBridge.cpp
deleted file mode 100644
index b9894f6..0000000
--- a/libnativebridge/tests/DummyNativeBridge.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2014 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.
- */
-
-// A dummy implementation of the native-bridge interface.
-
-#include "nativebridge/native_bridge.h"
-
-// NativeBridgeCallbacks implementations
-extern "C" bool native_bridge_initialize(const android::NativeBridgeRuntimeCallbacks* /* art_cbs */,
-                                         const char* /* app_code_cache_dir */,
-                                         const char* /* isa */) {
-  return true;
-}
-
-extern "C" void* native_bridge_loadLibrary(const char* /* libpath */, int /* flag */) {
-  return nullptr;
-}
-
-extern "C" void* native_bridge_getTrampoline(void* /* handle */, const char* /* name */,
-                                             const char* /* shorty */, uint32_t /* len */) {
-  return nullptr;
-}
-
-extern "C" bool native_bridge_isSupported(const char* /* libpath */) {
-  return false;
-}
-
-extern "C" const struct android::NativeBridgeRuntimeValues* native_bridge_getAppEnv(
-    const char* /* abi */) {
-  return nullptr;
-}
-
-android::NativeBridgeCallbacks NativeBridgeItf {
-  .version = 1,
-  .initialize = &native_bridge_initialize,
-  .loadLibrary = &native_bridge_loadLibrary,
-  .getTrampoline = &native_bridge_getTrampoline,
-  .isSupported = &native_bridge_isSupported,
-  .getAppEnv = &native_bridge_getAppEnv
-};
diff --git a/libnativebridge/tests/DummyNativeBridge2.cpp b/libnativebridge/tests/DummyNativeBridge2.cpp
deleted file mode 100644
index 6920c74..0000000
--- a/libnativebridge/tests/DummyNativeBridge2.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2014 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.
- */
-
-// A dummy implementation of the native-bridge interface.
-
-#include "nativebridge/native_bridge.h"
-
-#include <signal.h>
-
-// NativeBridgeCallbacks implementations
-extern "C" bool native_bridge2_initialize(const android::NativeBridgeRuntimeCallbacks* /* art_cbs */,
-                                         const char* /* app_code_cache_dir */,
-                                         const char* /* isa */) {
-  return true;
-}
-
-extern "C" void* native_bridge2_loadLibrary(const char* /* libpath */, int /* flag */) {
-  return nullptr;
-}
-
-extern "C" void* native_bridge2_getTrampoline(void* /* handle */, const char* /* name */,
-                                             const char* /* shorty */, uint32_t /* len */) {
-  return nullptr;
-}
-
-extern "C" bool native_bridge2_isSupported(const char* /* libpath */) {
-  return false;
-}
-
-extern "C" const struct android::NativeBridgeRuntimeValues* native_bridge2_getAppEnv(
-    const char* /* abi */) {
-  return nullptr;
-}
-
-extern "C" bool native_bridge2_is_compatible_compatible_with(uint32_t version) {
-  // For testing, allow 1 and 2, but disallow 3+.
-  return version <= 2;
-}
-
-static bool native_bridge2_dummy_signal_handler(int, siginfo_t*, void*) {
-  // TODO: Implement something here. We'd either have to have a death test with a log here, or
-  //       we'd have to be able to resume after the faulting instruction...
-  return true;
-}
-
-extern "C" android::NativeBridgeSignalHandlerFn native_bridge2_get_signal_handler(int signal) {
-  if (signal == SIGSEGV) {
-    return &native_bridge2_dummy_signal_handler;
-  }
-  return nullptr;
-}
-
-android::NativeBridgeCallbacks NativeBridgeItf {
-  .version = 2,
-  .initialize = &native_bridge2_initialize,
-  .loadLibrary = &native_bridge2_loadLibrary,
-  .getTrampoline = &native_bridge2_getTrampoline,
-  .isSupported = &native_bridge2_isSupported,
-  .getAppEnv = &native_bridge2_getAppEnv,
-  .isCompatibleWith = &native_bridge2_is_compatible_compatible_with,
-  .getSignalHandler = &native_bridge2_get_signal_handler
-};
-
diff --git a/libnativebridge/tests/DummyNativeBridge3.cpp b/libnativebridge/tests/DummyNativeBridge3.cpp
deleted file mode 100644
index 4ef1c82..0000000
--- a/libnativebridge/tests/DummyNativeBridge3.cpp
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// A dummy implementation of the native-bridge interface.
-
-#include "nativebridge/native_bridge.h"
-
-#include <signal.h>
-
-// NativeBridgeCallbacks implementations
-extern "C" bool native_bridge3_initialize(
-                      const android::NativeBridgeRuntimeCallbacks* /* art_cbs */,
-                      const char* /* app_code_cache_dir */,
-                      const char* /* isa */) {
-  return true;
-}
-
-extern "C" void* native_bridge3_loadLibrary(const char* /* libpath */, int /* flag */) {
-  return nullptr;
-}
-
-extern "C" void* native_bridge3_getTrampoline(void* /* handle */, const char* /* name */,
-                                             const char* /* shorty */, uint32_t /* len */) {
-  return nullptr;
-}
-
-extern "C" bool native_bridge3_isSupported(const char* /* libpath */) {
-  return false;
-}
-
-extern "C" const struct android::NativeBridgeRuntimeValues* native_bridge3_getAppEnv(
-    const char* /* abi */) {
-  return nullptr;
-}
-
-extern "C" bool native_bridge3_isCompatibleWith(uint32_t version) {
-  // For testing, allow 1-3, but disallow 4+.
-  return version <= 3;
-}
-
-static bool native_bridge3_dummy_signal_handler(int, siginfo_t*, void*) {
-  // TODO: Implement something here. We'd either have to have a death test with a log here, or
-  //       we'd have to be able to resume after the faulting instruction...
-  return true;
-}
-
-extern "C" android::NativeBridgeSignalHandlerFn native_bridge3_getSignalHandler(int signal) {
-  if (signal == SIGSEGV) {
-    return &native_bridge3_dummy_signal_handler;
-  }
-  return nullptr;
-}
-
-extern "C" int native_bridge3_unloadLibrary(void* /* handle */) {
-  return 0;
-}
-
-extern "C" const char* native_bridge3_getError() {
-  return nullptr;
-}
-
-extern "C" bool native_bridge3_isPathSupported(const char* /* path */) {
-  return true;
-}
-
-extern "C" bool native_bridge3_initAnonymousNamespace(const char* /* public_ns_sonames */,
-                                                      const char* /* anon_ns_library_path */) {
-  return true;
-}
-
-extern "C" android::native_bridge_namespace_t*
-native_bridge3_createNamespace(const char* /* name */,
-                               const char* /* ld_library_path */,
-                               const char* /* default_library_path */,
-                               uint64_t /* type */,
-                               const char* /* permitted_when_isolated_path */,
-                               android::native_bridge_namespace_t* /* parent_ns */) {
-  return nullptr;
-}
-
-extern "C" bool native_bridge3_linkNamespaces(android::native_bridge_namespace_t* /* from */,
-                                              android::native_bridge_namespace_t* /* to */,
-                                              const char* /* shared_libs_soname */) {
-  return true;
-}
-
-extern "C" void* native_bridge3_loadLibraryExt(const char* /* libpath */,
-                                               int /* flag */,
-                                               android::native_bridge_namespace_t* /* ns */) {
-  return nullptr;
-}
-
-android::NativeBridgeCallbacks NativeBridgeItf{
-    // v1
-    .version = 3,
-    .initialize = &native_bridge3_initialize,
-    .loadLibrary = &native_bridge3_loadLibrary,
-    .getTrampoline = &native_bridge3_getTrampoline,
-    .isSupported = &native_bridge3_isSupported,
-    .getAppEnv = &native_bridge3_getAppEnv,
-    // v2
-    .isCompatibleWith = &native_bridge3_isCompatibleWith,
-    .getSignalHandler = &native_bridge3_getSignalHandler,
-    // v3
-    .unloadLibrary = &native_bridge3_unloadLibrary,
-    .getError = &native_bridge3_getError,
-    .isPathSupported = &native_bridge3_isPathSupported,
-    .initAnonymousNamespace = &native_bridge3_initAnonymousNamespace,
-    .createNamespace = &native_bridge3_createNamespace,
-    .linkNamespaces = &native_bridge3_linkNamespaces,
-    .loadLibraryExt = &native_bridge3_loadLibraryExt};
diff --git a/libnativebridge/tests/InvalidCharsNativeBridge_test.cpp b/libnativebridge/tests/InvalidCharsNativeBridge_test.cpp
deleted file mode 100644
index 8f7973d..0000000
--- a/libnativebridge/tests/InvalidCharsNativeBridge_test.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2014 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 "NativeBridgeTest.h"
-
-namespace android {
-
-static const char* kTestName = "../librandom$@-bridge_not.existing.so";
-
-TEST_F(NativeBridgeTest, InvalidChars) {
-    // Do one test actually calling setup.
-    EXPECT_EQ(false, NativeBridgeError());
-    LoadNativeBridge(kTestName, nullptr);
-    // This should lead to an error for invalid characters.
-    EXPECT_EQ(true, NativeBridgeError());
-
-    // Further tests need to use NativeBridgeNameAcceptable, as the error
-    // state can't be changed back.
-    EXPECT_EQ(false, NativeBridgeNameAcceptable("."));
-    EXPECT_EQ(false, NativeBridgeNameAcceptable(".."));
-    EXPECT_EQ(false, NativeBridgeNameAcceptable("_"));
-    EXPECT_EQ(false, NativeBridgeNameAcceptable("-"));
-    EXPECT_EQ(false, NativeBridgeNameAcceptable("lib@.so"));
-    EXPECT_EQ(false, NativeBridgeNameAcceptable("lib$.so"));
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge2Signal_test.cpp b/libnativebridge/tests/NativeBridge2Signal_test.cpp
deleted file mode 100644
index 44e45e3..0000000
--- a/libnativebridge/tests/NativeBridge2Signal_test.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2014 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 "NativeBridgeTest.h"
-
-#include <signal.h>
-#include <unistd.h>
-
-namespace android {
-
-constexpr const char* kNativeBridgeLibrary2 = "libnativebridge2-dummy.so";
-
-TEST_F(NativeBridgeTest, V2_Signal) {
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary2, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-
-    ASSERT_EQ(2U, NativeBridgeGetVersion());
-    ASSERT_NE(nullptr, NativeBridgeGetSignalHandler(SIGSEGV));
-
-    // Clean-up code_cache
-    ASSERT_EQ(0, rmdir(kCodeCache));
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3CreateNamespace_test.cpp b/libnativebridge/tests/NativeBridge3CreateNamespace_test.cpp
deleted file mode 100644
index 668d942..0000000
--- a/libnativebridge/tests/NativeBridge3CreateNamespace_test.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "NativeBridgeTest.h"
-
-namespace android {
-
-constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
-
-TEST_F(NativeBridgeTest, V3_CreateNamespace) {
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary3, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-
-    ASSERT_EQ(3U, NativeBridgeGetVersion());
-    ASSERT_EQ(nullptr, NativeBridgeCreateNamespace(nullptr, nullptr, nullptr,
-                                                   0, nullptr, nullptr));
-
-    // Clean-up code_cache
-    ASSERT_EQ(0, rmdir(kCodeCache));
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3GetError_test.cpp b/libnativebridge/tests/NativeBridge3GetError_test.cpp
deleted file mode 100644
index 0b9f582..0000000
--- a/libnativebridge/tests/NativeBridge3GetError_test.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "NativeBridgeTest.h"
-
-namespace android {
-
-constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
-
-TEST_F(NativeBridgeTest, V3_GetError) {
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary3, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-
-    ASSERT_EQ(3U, NativeBridgeGetVersion());
-    ASSERT_EQ(nullptr, NativeBridgeGetError());
-
-    // Clean-up code_cache
-    ASSERT_EQ(0, rmdir(kCodeCache));
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3InitAnonymousNamespace_test.cpp b/libnativebridge/tests/NativeBridge3InitAnonymousNamespace_test.cpp
deleted file mode 100644
index b0d6b09..0000000
--- a/libnativebridge/tests/NativeBridge3InitAnonymousNamespace_test.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "NativeBridgeTest.h"
-
-namespace android {
-
-constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
-
-TEST_F(NativeBridgeTest, V3_InitAnonymousNamespace) {
-  // Init
-  ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary3, nullptr));
-  ASSERT_TRUE(NativeBridgeAvailable());
-  ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-  ASSERT_TRUE(NativeBridgeAvailable());
-  ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-  ASSERT_TRUE(NativeBridgeAvailable());
-
-  ASSERT_EQ(3U, NativeBridgeGetVersion());
-  ASSERT_EQ(true, NativeBridgeInitAnonymousNamespace(nullptr, nullptr));
-
-  // Clean-up code_cache
-  ASSERT_EQ(0, rmdir(kCodeCache));
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3IsPathSupported_test.cpp b/libnativebridge/tests/NativeBridge3IsPathSupported_test.cpp
deleted file mode 100644
index 325e40b..0000000
--- a/libnativebridge/tests/NativeBridge3IsPathSupported_test.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "NativeBridgeTest.h"
-
-namespace android {
-
-constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
-
-TEST_F(NativeBridgeTest, V3_IsPathSupported) {
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary3, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-
-    ASSERT_EQ(3U, NativeBridgeGetVersion());
-    ASSERT_EQ(true, NativeBridgeIsPathSupported(nullptr));
-
-    // Clean-up code_cache
-    ASSERT_EQ(0, rmdir(kCodeCache));
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3LoadLibraryExt_test.cpp b/libnativebridge/tests/NativeBridge3LoadLibraryExt_test.cpp
deleted file mode 100644
index 4caeb44..0000000
--- a/libnativebridge/tests/NativeBridge3LoadLibraryExt_test.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "NativeBridgeTest.h"
-
-namespace android {
-
-constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
-
-TEST_F(NativeBridgeTest, V3_LoadLibraryExt) {
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary3, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-
-    ASSERT_EQ(3U, NativeBridgeGetVersion());
-    ASSERT_EQ(nullptr, NativeBridgeLoadLibraryExt(nullptr, 0, nullptr));
-
-    // Clean-up code_cache
-    ASSERT_EQ(0, rmdir(kCodeCache));
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/NativeBridge3UnloadLibrary_test.cpp b/libnativebridge/tests/NativeBridge3UnloadLibrary_test.cpp
deleted file mode 100644
index 93a979c..0000000
--- a/libnativebridge/tests/NativeBridge3UnloadLibrary_test.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "NativeBridgeTest.h"
-
-namespace android {
-
-constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
-
-TEST_F(NativeBridgeTest, V3_UnloadLibrary) {
-    // Init
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary3, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(PreInitializeNativeBridge(".", "isa"));
-    ASSERT_TRUE(NativeBridgeAvailable());
-    ASSERT_TRUE(InitializeNativeBridge(nullptr, nullptr));
-    ASSERT_TRUE(NativeBridgeAvailable());
-
-    ASSERT_EQ(3U, NativeBridgeGetVersion());
-    ASSERT_EQ(0, NativeBridgeUnloadLibrary(nullptr));
-
-    // Clean-up code_cache
-    ASSERT_EQ(0, rmdir(kCodeCache));
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/NativeBridgeApi.c b/libnativebridge/tests/NativeBridgeApi.c
deleted file mode 100644
index 7ab71fe..0000000
--- a/libnativebridge/tests/NativeBridgeApi.c
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2019 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.
- */
-
-/* The main purpose of this test is to ensure this C header compiles in C, so
- * that no C++ features inadvertently leak into the C ABI. */
-#include "nativebridge/native_bridge.h"
-
-int main(int argc, char** argv) {
-  (void)argc;
-  (void)argv;
-  return 0;
-}
diff --git a/libnativebridge/tests/NativeBridgeTest.h b/libnativebridge/tests/NativeBridgeTest.h
deleted file mode 100644
index 0f99816..0000000
--- a/libnativebridge/tests/NativeBridgeTest.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVE_BRIDGE_TEST_H_
-#define NATIVE_BRIDGE_TEST_H_
-
-#define LOG_TAG "NativeBridge_test"
-
-#include <nativebridge/native_bridge.h>
-#include <gtest/gtest.h>
-
-constexpr const char* kNativeBridgeLibrary = "libnativebridge-dummy.so";
-constexpr const char* kCodeCache = "./code_cache";
-constexpr const char* kCodeCacheStatFail = "./code_cache/temp";
-constexpr const char* kNativeBridgeLibrary2 = "libnativebridge2-dummy.so";
-constexpr const char* kNativeBridgeLibrary3 = "libnativebridge3-dummy.so";
-
-namespace android {
-
-class NativeBridgeTest : public testing::Test {
-};
-
-};  // namespace android
-
-#endif  // NATIVE_BRIDGE_H_
-
diff --git a/libnativebridge/tests/NativeBridgeVersion_test.cpp b/libnativebridge/tests/NativeBridgeVersion_test.cpp
deleted file mode 100644
index d3f9a80..0000000
--- a/libnativebridge/tests/NativeBridgeVersion_test.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2015 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 "NativeBridgeTest.h"
-
-#include <unistd.h>
-
-namespace android {
-
-TEST_F(NativeBridgeTest, Version) {
-    // When a bridge isn't loaded, we expect 0.
-    EXPECT_EQ(NativeBridgeGetVersion(), 0U);
-
-    // After our dummy bridge has been loaded, we expect 1.
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary, nullptr));
-    EXPECT_EQ(NativeBridgeGetVersion(), 1U);
-
-    // Unload
-    UnloadNativeBridge();
-
-    // Version information is gone.
-    EXPECT_EQ(NativeBridgeGetVersion(), 0U);
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/NeedsNativeBridge_test.cpp b/libnativebridge/tests/NeedsNativeBridge_test.cpp
deleted file mode 100644
index c8ff743..0000000
--- a/libnativebridge/tests/NeedsNativeBridge_test.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2014 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 "NativeBridgeTest.h"
-
-#include <android-base/macros.h>
-
-namespace android {
-
-static const char* kISAs[] = { "arm", "arm64", "mips", "mips64", "x86", "x86_64", "random", "64arm",
-                               "64_x86", "64_x86_64", "", "reallylongstringabcd", nullptr };
-
-TEST_F(NativeBridgeTest, NeedsNativeBridge) {
-  EXPECT_EQ(false, NeedsNativeBridge(ABI_STRING));
-
-  const size_t kISACount = sizeof(kISAs) / sizeof(kISAs[0]);
-  for (size_t i = 0; i < kISACount; i++) {
-    EXPECT_EQ(kISAs[i] == nullptr ? false : strcmp(kISAs[i], ABI_STRING) != 0,
-              NeedsNativeBridge(kISAs[i]));
-    }
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/PreInitializeNativeBridgeFail1_test.cpp b/libnativebridge/tests/PreInitializeNativeBridgeFail1_test.cpp
deleted file mode 100644
index 5a2b0a1..0000000
--- a/libnativebridge/tests/PreInitializeNativeBridgeFail1_test.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2014 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 "NativeBridgeTest.h"
-
-#include <dlfcn.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <sys/mount.h>
-#include <sys/stat.h>
-
-#include <cstdio>
-#include <cstring>
-
-#include <android/log.h>
-
-namespace android {
-
-TEST_F(NativeBridgeTest, PreInitializeNativeBridgeFail1) {
-  // Needs a valid application directory.
-  ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary, nullptr));
-  ASSERT_FALSE(PreInitializeNativeBridge(nullptr, "isa"));
-  ASSERT_TRUE(NativeBridgeError());
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/PreInitializeNativeBridgeFail2_test.cpp b/libnativebridge/tests/PreInitializeNativeBridgeFail2_test.cpp
deleted file mode 100644
index af976b1..0000000
--- a/libnativebridge/tests/PreInitializeNativeBridgeFail2_test.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2014 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 <dlfcn.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <sys/mount.h>
-#include <sys/stat.h>
-
-#include <cstdio>
-#include <cstring>
-
-#include <android/log.h>
-
-#include "NativeBridgeTest.h"
-
-namespace android {
-
-TEST_F(NativeBridgeTest, PreInitializeNativeBridgeFail2) {
-  // Needs LoadNativeBridge() first
-  ASSERT_FALSE(PreInitializeNativeBridge(nullptr, "isa"));
-  ASSERT_TRUE(NativeBridgeError());
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/PreInitializeNativeBridge_test.cpp b/libnativebridge/tests/PreInitializeNativeBridge_test.cpp
deleted file mode 100644
index cd5a8e2..0000000
--- a/libnativebridge/tests/PreInitializeNativeBridge_test.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2014 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 <dlfcn.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <sys/mount.h>
-#include <sys/stat.h>
-
-#include <cstdio>
-#include <cstring>
-
-#include <android/log.h>
-
-#include "NativeBridgeTest.h"
-
-namespace android {
-
-TEST_F(NativeBridgeTest, PreInitializeNativeBridge) {
-    ASSERT_TRUE(LoadNativeBridge(kNativeBridgeLibrary, nullptr));
-#if !defined(__APPLE__)         // Mac OS does not support bind-mount.
-#if !defined(__ANDROID__)       // Cannot write into the hard-wired location.
-    static constexpr const char* kTestData = "PreInitializeNativeBridge test.";
-
-    // Try to create our mount namespace.
-    if (unshare(CLONE_NEWNS) != -1) {
-        // Create a dummy file.
-        FILE* cpuinfo = fopen("./cpuinfo", "w");
-        ASSERT_NE(nullptr, cpuinfo) << strerror(errno);
-        fprintf(cpuinfo, kTestData);
-        fclose(cpuinfo);
-
-        ASSERT_TRUE(PreInitializeNativeBridge("does not matter 1", "short 2"));
-
-        // Read /proc/cpuinfo
-        FILE* proc_cpuinfo = fopen("/proc/cpuinfo", "r");
-        ASSERT_NE(nullptr, proc_cpuinfo) << strerror(errno);
-        char buf[1024];
-        EXPECT_NE(nullptr, fgets(buf, sizeof(buf), proc_cpuinfo)) << "Error reading.";
-        fclose(proc_cpuinfo);
-
-        EXPECT_EQ(0, strcmp(buf, kTestData));
-
-        // Delete the file.
-        ASSERT_EQ(0, unlink("./cpuinfo")) << "Error unlinking temporary file.";
-        // Ending the test will tear down the mount namespace.
-    } else {
-        GTEST_LOG_(WARNING) << "Could not create mount namespace. Are you running this as root?";
-    }
-#endif
-#endif
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/ReSetupNativeBridge_test.cpp b/libnativebridge/tests/ReSetupNativeBridge_test.cpp
deleted file mode 100644
index 944e5d7..0000000
--- a/libnativebridge/tests/ReSetupNativeBridge_test.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2014 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 "NativeBridgeTest.h"
-
-namespace android {
-
-TEST_F(NativeBridgeTest, ReSetup) {
-    EXPECT_EQ(false, NativeBridgeError());
-    LoadNativeBridge("", nullptr);
-    EXPECT_EQ(false, NativeBridgeError());
-    LoadNativeBridge("", nullptr);
-    // This should lead to an error for trying to re-setup a native bridge.
-    EXPECT_EQ(true, NativeBridgeError());
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/UnavailableNativeBridge_test.cpp b/libnativebridge/tests/UnavailableNativeBridge_test.cpp
deleted file mode 100644
index ad374a5..0000000
--- a/libnativebridge/tests/UnavailableNativeBridge_test.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2011 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 "NativeBridgeTest.h"
-
-namespace android {
-
-TEST_F(NativeBridgeTest, NoNativeBridge) {
-    EXPECT_EQ(false, NativeBridgeAvailable());
-    // Try to initialize. This should fail as we are not set up.
-    EXPECT_EQ(false, InitializeNativeBridge(nullptr, nullptr));
-    EXPECT_EQ(true, NativeBridgeError());
-    EXPECT_EQ(false, NativeBridgeAvailable());
-}
-
-}  // namespace android
diff --git a/libnativebridge/tests/ValidNameNativeBridge_test.cpp b/libnativebridge/tests/ValidNameNativeBridge_test.cpp
deleted file mode 100644
index 690be4a..0000000
--- a/libnativebridge/tests/ValidNameNativeBridge_test.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2011 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 <NativeBridgeTest.h>
-
-namespace android {
-
-static const char* kTestName = "librandom-bridge_not.existing.so";
-
-TEST_F(NativeBridgeTest, ValidName) {
-    // Check that the name is acceptable.
-    EXPECT_EQ(true, NativeBridgeNameAcceptable(kTestName));
-
-    // Now check what happens on LoadNativeBridge.
-    EXPECT_EQ(false, NativeBridgeError());
-    LoadNativeBridge(kTestName, nullptr);
-    // This will lead to an error as the library doesn't exist.
-    EXPECT_EQ(true, NativeBridgeError());
-    EXPECT_EQ(false, NativeBridgeAvailable());
-}
-
-}  // namespace android
diff --git a/libnativeloader/.clang-format b/libnativeloader/.clang-format
deleted file mode 120000
index fd0645f..0000000
--- a/libnativeloader/.clang-format
+++ /dev/null
@@ -1 +0,0 @@
-../.clang-format-2
\ No newline at end of file
diff --git a/libnativeloader/Android.bp b/libnativeloader/Android.bp
deleted file mode 100644
index 939bdd7..0000000
--- a/libnativeloader/Android.bp
+++ /dev/null
@@ -1,88 +0,0 @@
-// Shared library for target
-// ========================================================
-cc_defaults {
-    name: "libnativeloader-defaults",
-    cflags: [
-        "-Werror",
-        "-Wall",
-    ],
-    cppflags: [
-        "-fvisibility=hidden",
-    ],
-    header_libs: ["libnativeloader-headers"],
-    export_header_lib_headers: ["libnativeloader-headers"],
-}
-
-cc_library {
-    name: "libnativeloader",
-    defaults: ["libnativeloader-defaults"],
-    host_supported: true,
-    srcs: [
-        "native_loader.cpp",
-    ],
-    shared_libs: [
-        "libnativehelper",
-        "liblog",
-        "libnativebridge",
-        "libbase",
-    ],
-    target: {
-        android: {
-            srcs: [
-                "library_namespaces.cpp",
-                "native_loader_namespace.cpp",
-                "public_libraries.cpp",
-            ],
-            shared_libs: [
-                "libdl_android",
-            ],
-        },
-    },
-    required: [
-        "llndk.libraries.txt",
-        "vndksp.libraries.txt",
-    ],
-    stubs: {
-        symbol_file: "libnativeloader.map.txt",
-        versions: ["1"],
-    },
-}
-
-// TODO(b/124250621) eliminate the need for this library
-cc_library {
-    name: "libnativeloader_lazy",
-    defaults: ["libnativeloader-defaults"],
-    host_supported: false,
-    srcs: ["native_loader_lazy.cpp"],
-    required: ["libnativeloader"],
-}
-
-cc_library_headers {
-    name: "libnativeloader-headers",
-    host_supported: true,
-    export_include_dirs: ["include"],
-}
-
-cc_test {
-    name: "libnativeloader_test",
-    srcs: [
-        "native_loader_test.cpp",
-        "native_loader.cpp",
-        "library_namespaces.cpp",
-        "native_loader_namespace.cpp",
-        "public_libraries.cpp",
-    ],
-    cflags: ["-DANDROID"],
-    static_libs: [
-        "libbase",
-        "liblog",
-        "libnativehelper",
-        "libgmock",
-    ],
-    header_libs: [
-        "libnativebridge-headers",
-        "libnativeloader-headers",
-    ],
-    system_shared_libs: ["libc", "libm"],
-    test_suites: ["device-tests"],
-}
diff --git a/libnativeloader/CPPLINT.cfg b/libnativeloader/CPPLINT.cfg
deleted file mode 100644
index db98533..0000000
--- a/libnativeloader/CPPLINT.cfg
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Copyright (C) 2019 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.
-#
-
-filter=-build/header_guard
-filter=-readability/check
-filter=-build/namespaces
diff --git a/libnativeloader/OWNERS b/libnativeloader/OWNERS
deleted file mode 100644
index f735653..0000000
--- a/libnativeloader/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-dimitry@google.com
-jiyong@google.com
-ngeoffray@google.com
-oth@google.com
-mast@google.com
-rpl@google.com
diff --git a/libnativeloader/README.md b/libnativeloader/README.md
deleted file mode 100644
index 57b9001..0000000
--- a/libnativeloader/README.md
+++ /dev/null
@@ -1,84 +0,0 @@
-libnativeloader
-===============================================================================
-
-Overview
--------------------------------------------------------------------------------
-libnativeloader is responsible for loading native shared libraries (`*.so`
-files) inside the Android Runtime (ART). The native shared libraries could be
-app-provided JNI libraries or public native libraries like `libc.so` provided
-by the platform.
-
-The most typical use case of this library is calling `System.loadLibrary(name)`.
-When the method is called, the ART runtime delegates the call to this library
-along with the reference to the classloader where the call was made.  Then this
-library finds the linker namespace (named `classloader-namespace`) that is
-associated with the given classloader, and tries to load the requested library
-from the namespace. The actual searching, loading, and linking of the library
-is performed by the dynamic linker.
-
-The linker namespace is created when an APK is loaded into the process, and is
-associated with the classloader that loaded the APK. The linker namespace is
-configured so that only the JNI libraries embedded in the APK is accessible
-from the namespace, thus preventing an APK from loading JNI libraries of other
-APKs.
-
-The linker namespace is also configured differently depending on other
-characteristics of the APK such as whether or not the APK is bundled with the
-platform. In case of the unbundled, i.e., downloaded or updated APK, only the
-public native libraries that is listed in `/system/etc/public.libraries.txt`
-are available from the platform, whereas in case of the bundled, all libraries
-under `/system/lib` are available (i.e. shared). In case when the unbundled
-app is from `/vendor` or `/product` partition, the app is additionally provided
-with the [VNDK-SP](https://source.android.com/devices/architecture/vndk#sp-hal)
-libraries. As the platform is getting modularized with
-[APEX](https://android.googlesource.com/platform/system/apex/+/refs/heads/master/docs/README.md),
-some libraries are no longer provided from platform, but from the APEXes which
-have their own linker namespaces. For example, ICU libraries `libicuuc.so` and
-`libicui18n.so` are from the runtime APEX.
-
-The list of public native libraries is not static. The default set of libraries
-are defined in AOSP, but partners can extend it to include their own libraries.
-Currently, following extensions are available:
-
-- `/vendor/etc/public.libraries.txt`: libraries in `/vendor/lib` that are
-specific to the underlying SoC, e.g. GPU, DSP, etc.
-- `/{system|product}/etc/public.libraries-<companyname>.txt`: libraries in
-`/{system|product}/lib` that a device manufacturer has newly added. The
-libraries should be named as `lib<name>.<companyname>.so` as in
-`libFoo.acme.so`.
-
-Note that, due to the naming constraint requiring `.<companyname>.so` suffix, it
-is prohibited for a device manufacturer to expose an AOSP-defined private
-library, e.g. libgui.so, libart.so, etc., to APKs.
-
-Lastly, libnativeloader is responsible for abstracting the two types of the
-dynamic linker interface: `libdl.so` and `libnativebridge.so`. The former is
-for non-translated, e.g. ARM-on-ARM, libraries, while the latter is for
-loading libraries in a translated environment such as ARM-on-x86.
-
-Implementation
--------------------------------------------------------------------------------
-Implementation wise, libnativeloader consists of four parts:
-
-- `native_loader.cpp`
-- `library_namespaces.cpp`
-- `native_loader_namespace.cpp`
-- `public_libraries.cpp`
-
-`native_loader.cpp` implements the public interface of this library. It is just
-a thin wrapper around `library_namespaces.cpp` and `native_loader_namespace.cpp`.
-
-`library_namespaces.cpp` implements the singleton class `LibraryNamespaces` which
-is a manager-like entity that is responsible for creating and configuring
-linker namespaces and finding an already created linker namespace for a given
-classloader.
-
-`native_loader_namespace.cpp` implements the class `NativeLoaderNamespace` that
-models a linker namespace. Its main job is to abstract the two types of the
-dynamic linker interface so that other parts of this library do not have to know
-the differences of the interfaces.
-
-`public_libraries.cpp` is responsible for reading `*.txt` files for the public
-native libraries from the various partitions. It can be considered as a part of
-`LibraryNamespaces` but is separated from it to hide the details of the parsing
-routines.
diff --git a/libnativeloader/TEST_MAPPING b/libnativeloader/TEST_MAPPING
deleted file mode 100644
index 7becb77..0000000
--- a/libnativeloader/TEST_MAPPING
+++ /dev/null
@@ -1,12 +0,0 @@
-{
-  "presubmit": [
-    {
-      "name": "libnativeloader_test"
-    }
-  ],
-  "imports": [
-    {
-      "path": "cts/tests/tests/jni"
-    }
-  ]
-}
diff --git a/libnativeloader/include/nativeloader/dlext_namespaces.h b/libnativeloader/include/nativeloader/dlext_namespaces.h
deleted file mode 100644
index 8937636..0000000
--- a/libnativeloader/include/nativeloader/dlext_namespaces.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __ANDROID_DLEXT_NAMESPACES_H__
-#define __ANDROID_DLEXT_NAMESPACES_H__
-
-#include <android/dlext.h>
-#include <stdbool.h>
-
-__BEGIN_DECLS
-
-enum {
-  /* A regular namespace is the namespace with a custom search path that does
-   * not impose any restrictions on the location of native libraries.
-   */
-  ANDROID_NAMESPACE_TYPE_REGULAR = 0,
-
-  /* An isolated namespace requires all the libraries to be on the search path
-   * or under permitted_when_isolated_path. The search path is the union of
-   * ld_library_path and default_library_path.
-   */
-  ANDROID_NAMESPACE_TYPE_ISOLATED = 1,
-
-  /* The shared namespace clones the list of libraries of the caller namespace upon creation
-   * which means that they are shared between namespaces - the caller namespace and the new one
-   * will use the same copy of a library if it was loaded prior to android_create_namespace call.
-   *
-   * Note that libraries loaded after the namespace is created will not be shared.
-   *
-   * Shared namespaces can be isolated or regular. Note that they do not inherit the search path nor
-   * permitted_path from the caller's namespace.
-   */
-  ANDROID_NAMESPACE_TYPE_SHARED = 2,
-
-  /* This flag instructs linker to enable grey-list workaround for the namespace.
-   * See http://b/26394120 for details.
-   */
-  ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED = 0x08000000,
-
-  /* This flag instructs linker to use this namespace as the anonymous
-   * namespace. The anonymous namespace is used in the case when linker cannot
-   * identify the caller of dlopen/dlsym. This happens for the code not loaded
-   * by dynamic linker; for example calls from the mono-compiled code. There can
-   * be only one anonymous namespace in a process. If there already is an
-   * anonymous namespace in the process, using this flag when creating a new
-   * namespace causes an error.
-   */
-  ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS = 0x10000000,
-
-  ANDROID_NAMESPACE_TYPE_SHARED_ISOLATED =
-      ANDROID_NAMESPACE_TYPE_SHARED | ANDROID_NAMESPACE_TYPE_ISOLATED,
-};
-
-/*
- * Creates new linker namespace.
- * ld_library_path and default_library_path represent the search path
- * for the libraries in the namespace.
- *
- * The libraries in the namespace are searched by folowing order:
- * 1. ld_library_path (Think of this as namespace-local LD_LIBRARY_PATH)
- * 2. In directories specified by DT_RUNPATH of the "needed by" binary.
- * 3. deault_library_path (This of this as namespace-local default library path)
- *
- * When type is ANDROID_NAMESPACE_TYPE_ISOLATED the resulting namespace requires all of
- * the libraries to be on the search path or under the permitted_when_isolated_path;
- * the search_path is ld_library_path:default_library_path. Note that the
- * permitted_when_isolated_path path is not part of the search_path and
- * does not affect the search order. It is a way to allow loading libraries from specific
- * locations when using absolute path.
- * If a library or any of its dependencies are outside of the permitted_when_isolated_path
- * and search_path, and it is not part of the public namespace dlopen will fail.
- */
-extern struct android_namespace_t* android_create_namespace(
-    const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
-    const char* permitted_when_isolated_path, struct android_namespace_t* parent);
-
-/*
- * Creates a link between namespaces. Every link has list of sonames of
- * shared libraries. These are the libraries which are accessible from
- * namespace 'from' but loaded within namespace 'to' context.
- * When to namespace is nullptr this function establishes a link between
- * 'from' namespace and the default namespace.
- *
- * The lookup order of the libraries in namespaces with links is following:
- * 1. Look inside current namespace using 'this' namespace search path.
- * 2. Look in linked namespaces
- * 2.1. Perform soname check - if library soname is not in the list of shared
- *      libraries sonames skip this link, otherwise
- * 2.2. Search library using linked namespace search path. Note that this
- *      step will not go deeper into linked namespaces for this library but
- *      will do so for DT_NEEDED libraries.
- */
-extern bool android_link_namespaces(struct android_namespace_t* from,
-                                    struct android_namespace_t* to,
-                                    const char* shared_libs_sonames);
-
-extern struct android_namespace_t* android_get_exported_namespace(const char* name);
-
-__END_DECLS
-
-#endif /* __ANDROID_DLEXT_NAMESPACES_H__ */
diff --git a/libnativeloader/include/nativeloader/native_loader.h b/libnativeloader/include/nativeloader/native_loader.h
deleted file mode 100644
index 51fb875..0000000
--- a/libnativeloader/include/nativeloader/native_loader.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVE_LOADER_H_
-#define NATIVE_LOADER_H_
-
-#include <stdbool.h>
-#include <stdint.h>
-#include "jni.h"
-#if defined(__ANDROID__)
-#include <android/dlext.h>
-#endif
-
-#ifdef __cplusplus
-namespace android {
-extern "C" {
-#endif  // __cplusplus
-
-// README: the char** error message parameter being passed
-// to the methods below need to be freed through calling NativeLoaderFreeErrorMessage.
-// It's the caller's responsibility to call that method.
-
-__attribute__((visibility("default")))
-void InitializeNativeLoader();
-
-__attribute__((visibility("default"))) jstring CreateClassLoaderNamespace(
-    JNIEnv* env, int32_t target_sdk_version, jobject class_loader, bool is_shared, jstring dex_path,
-    jstring library_path, jstring permitted_path);
-
-__attribute__((visibility("default"))) void* OpenNativeLibrary(
-    JNIEnv* env, int32_t target_sdk_version, const char* path, jobject class_loader,
-    const char* caller_location, jstring library_path, bool* needs_native_bridge, char** error_msg);
-
-__attribute__((visibility("default"))) bool CloseNativeLibrary(void* handle,
-                                                               const bool needs_native_bridge,
-                                                               char** error_msg);
-
-__attribute__((visibility("default"))) void NativeLoaderFreeErrorMessage(char* msg);
-
-#if defined(__ANDROID__)
-// Look up linker namespace by class_loader. Returns nullptr if
-// there is no namespace associated with the class_loader.
-// TODO(b/79940628): move users to FindNativeLoaderNamespaceByClassLoader and remove this function.
-__attribute__((visibility("default"))) struct android_namespace_t* FindNamespaceByClassLoader(
-    JNIEnv* env, jobject class_loader);
-// That version works with native bridge namespaces, but requires use of OpenNativeLibrary.
-struct NativeLoaderNamespace;
-__attribute__((visibility("default"))) struct NativeLoaderNamespace*
-FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader);
-// Load library.  Unlinke OpenNativeLibrary above couldn't create namespace on demand, but does
-// not require access to JNIEnv either.
-__attribute__((visibility("default"))) void* OpenNativeLibraryInNamespace(
-    struct NativeLoaderNamespace* ns, const char* path, bool* needs_native_bridge,
-    char** error_msg);
-#endif
-
-__attribute__((visibility("default")))
-void ResetNativeLoader();
-
-#ifdef __cplusplus
-}  // extern "C"
-}  // namespace android
-#endif  // __cplusplus
-
-#endif  // NATIVE_BRIDGE_H_
diff --git a/libnativeloader/libnativeloader.map.txt b/libnativeloader/libnativeloader.map.txt
deleted file mode 100644
index 40c30bd..0000000
--- a/libnativeloader/libnativeloader.map.txt
+++ /dev/null
@@ -1,31 +0,0 @@
-#
-# Copyright (C) 2019 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.
-#
-
-# TODO(b/122710865): Prune these uses once the runtime APEX is complete.
-LIBNATIVELOADER_1 {
-  global:
-    OpenNativeLibrary;
-    InitializeNativeLoader;
-    ResetNativeLoader;
-    CloseNativeLibrary;
-    OpenNativeLibraryInNamespace;
-    FindNamespaceByClassLoader;
-    FindNativeLoaderNamespaceByClassLoader;
-    CreateClassLoaderNamespace;
-    NativeLoaderFreeErrorMessage;
-  local:
-    *;
-};
diff --git a/libnativeloader/library_namespaces.cpp b/libnativeloader/library_namespaces.cpp
deleted file mode 100644
index 9a33b55..0000000
--- a/libnativeloader/library_namespaces.cpp
+++ /dev/null
@@ -1,319 +0,0 @@
-/*
- * Copyright (C) 2019 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 "library_namespaces.h"
-
-#include <dirent.h>
-#include <dlfcn.h>
-
-#include <regex>
-#include <string>
-#include <vector>
-
-#include <android-base/file.h>
-#include <android-base/logging.h>
-#include <android-base/macros.h>
-#include <android-base/properties.h>
-#include <android-base/strings.h>
-#include <nativehelper/ScopedUtfChars.h>
-
-#include "nativeloader/dlext_namespaces.h"
-#include "public_libraries.h"
-#include "utils.h"
-
-using android::base::Error;
-
-namespace android::nativeloader {
-
-namespace {
-// The device may be configured to have the vendor libraries loaded to a separate namespace.
-// For historical reasons this namespace was named sphal but effectively it is intended
-// to use to load vendor libraries to separate namespace with controlled interface between
-// vendor and system namespaces.
-constexpr const char* kVendorNamespaceName = "sphal";
-constexpr const char* kVndkNamespaceName = "vndk";
-constexpr const char* kRuntimeNamespaceName = "runtime";
-constexpr const char* kNeuralNetworksNamespaceName = "neuralnetworks";
-
-// classloader-namespace is a linker namespace that is created for the loaded
-// app. To be specific, it is created for the app classloader. When
-// System.load() is called from a Java class that is loaded from the
-// classloader, the classloader-namespace namespace associated with that
-// classloader is selected for dlopen. The namespace is configured so that its
-// search path is set to the app-local JNI directory and it is linked to the
-// platform namespace with the names of libs listed in the public.libraries.txt.
-// This way an app can only load its own JNI libraries along with the public libs.
-constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
-// Same thing for vendor APKs.
-constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";
-
-// (http://b/27588281) This is a workaround for apps using custom classloaders and calling
-// System.load() with an absolute path which is outside of the classloader library search path.
-// This list includes all directories app is allowed to access this way.
-constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
-
-constexpr const char* kVendorLibPath = "/vendor/" LIB;
-constexpr const char* kProductLibPath = "/product/" LIB ":/system/product/" LIB;
-
-const std::regex kVendorDexPathRegex("(^|:)/vendor/");
-const std::regex kProductDexPathRegex("(^|:)(/system)?/product/");
-
-// Define origin of APK if it is from vendor partition or product partition
-typedef enum {
-  APK_ORIGIN_DEFAULT = 0,
-  APK_ORIGIN_VENDOR = 1,
-  APK_ORIGIN_PRODUCT = 2,
-} ApkOrigin;
-
-jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
-  jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
-  jmethodID get_parent =
-      env->GetMethodID(class_loader_class, "getParent", "()Ljava/lang/ClassLoader;");
-
-  return env->CallObjectMethod(class_loader, get_parent);
-}
-
-ApkOrigin GetApkOriginFromDexPath(JNIEnv* env, jstring dex_path) {
-  ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
-
-  if (dex_path != nullptr) {
-    ScopedUtfChars dex_path_utf_chars(env, dex_path);
-
-    if (std::regex_search(dex_path_utf_chars.c_str(), kVendorDexPathRegex)) {
-      apk_origin = APK_ORIGIN_VENDOR;
-    }
-
-    if (std::regex_search(dex_path_utf_chars.c_str(), kProductDexPathRegex)) {
-      LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
-                          "Dex path contains both vendor and product partition : %s",
-                          dex_path_utf_chars.c_str());
-
-      apk_origin = APK_ORIGIN_PRODUCT;
-    }
-  }
-  return apk_origin;
-}
-
-}  // namespace
-
-void LibraryNamespaces::Initialize() {
-  // Once public namespace is initialized there is no
-  // point in running this code - it will have no effect
-  // on the current list of public libraries.
-  if (initialized_) {
-    return;
-  }
-
-  // android_init_namespaces() expects all the public libraries
-  // to be loaded so that they can be found by soname alone.
-  //
-  // TODO(dimitry): this is a bit misleading since we do not know
-  // if the vendor public library is going to be opened from /vendor/lib
-  // we might as well end up loading them from /system/lib or /product/lib
-  // For now we rely on CTS test to catch things like this but
-  // it should probably be addressed in the future.
-  for (const auto& soname : android::base::Split(preloadable_public_libraries(), ":")) {
-    LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
-                        "Error preloading public library %s: %s", soname.c_str(), dlerror());
-  }
-}
-
-Result<NativeLoaderNamespace*> LibraryNamespaces::Create(JNIEnv* env, uint32_t target_sdk_version,
-                                                         jobject class_loader, bool is_shared,
-                                                         jstring dex_path,
-                                                         jstring java_library_path,
-                                                         jstring java_permitted_path) {
-  std::string library_path;  // empty string by default.
-
-  if (java_library_path != nullptr) {
-    ScopedUtfChars library_path_utf_chars(env, java_library_path);
-    library_path = library_path_utf_chars.c_str();
-  }
-
-  ApkOrigin apk_origin = GetApkOriginFromDexPath(env, dex_path);
-
-  // (http://b/27588281) This is a workaround for apps using custom
-  // classloaders and calling System.load() with an absolute path which
-  // is outside of the classloader library search path.
-  //
-  // This part effectively allows such a classloader to access anything
-  // under /data and /mnt/expand
-  std::string permitted_path = kWhitelistedDirectories;
-
-  if (java_permitted_path != nullptr) {
-    ScopedUtfChars path(env, java_permitted_path);
-    if (path.c_str() != nullptr && path.size() > 0) {
-      permitted_path = permitted_path + ":" + path.c_str();
-    }
-  }
-
-  LOG_ALWAYS_FATAL_IF(FindNamespaceByClassLoader(env, class_loader) != nullptr,
-                      "There is already a namespace associated with this classloader");
-
-  std::string system_exposed_libraries = default_public_libraries();
-  const char* namespace_name = kClassloaderNamespaceName;
-  bool unbundled_vendor_or_product_app = false;
-  if ((apk_origin == APK_ORIGIN_VENDOR ||
-       (apk_origin == APK_ORIGIN_PRODUCT && target_sdk_version > 29)) &&
-      !is_shared) {
-    unbundled_vendor_or_product_app = true;
-    // For vendor / product apks, give access to the vendor / product lib even though
-    // they are treated as unbundled; the libs and apks are still bundled
-    // together in the vendor / product partition.
-    const char* origin_partition;
-    const char* origin_lib_path;
-
-    switch (apk_origin) {
-      case APK_ORIGIN_VENDOR:
-        origin_partition = "vendor";
-        origin_lib_path = kVendorLibPath;
-        break;
-      case APK_ORIGIN_PRODUCT:
-        origin_partition = "product";
-        origin_lib_path = kProductLibPath;
-        break;
-      default:
-        origin_partition = "unknown";
-        origin_lib_path = "";
-    }
-    library_path = library_path + ":" + origin_lib_path;
-    permitted_path = permitted_path + ":" + origin_lib_path;
-
-    // Also give access to LLNDK libraries since they are available to vendors
-    system_exposed_libraries = system_exposed_libraries + ":" + llndk_libraries().c_str();
-
-    // Different name is useful for debugging
-    namespace_name = kVendorClassloaderNamespaceName;
-    ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
-          origin_partition, library_path.c_str());
-  } else {
-    // extended public libraries are NOT available to vendor apks, otherwise it
-    // would be system->vendor violation.
-    if (!extended_public_libraries().empty()) {
-      system_exposed_libraries = system_exposed_libraries + ':' + extended_public_libraries();
-    }
-  }
-
-  // Create the app namespace
-  NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
-  // Heuristic: the first classloader with non-empty library_path is assumed to
-  // be the main classloader for app
-  // TODO(b/139178525) remove this heuristic by determining this in LoadedApk (or its
-  // friends) and then passing it down to here.
-  bool is_main_classloader = app_main_namespace_ == nullptr && !library_path.empty();
-  // Policy: the namespace for the main classloader is also used as the
-  // anonymous namespace.
-  bool also_used_as_anonymous = is_main_classloader;
-  // Note: this function is executed with g_namespaces_mutex held, thus no
-  // racing here.
-  auto app_ns = NativeLoaderNamespace::Create(
-      namespace_name, library_path, permitted_path, parent_ns, is_shared,
-      target_sdk_version < 24 /* is_greylist_enabled */, also_used_as_anonymous);
-  if (!app_ns) {
-    return app_ns.error();
-  }
-  // ... and link to other namespaces to allow access to some public libraries
-  bool is_bridged = app_ns->IsBridged();
-
-  auto platform_ns = NativeLoaderNamespace::GetPlatformNamespace(is_bridged);
-  if (!platform_ns) {
-    return platform_ns.error();
-  }
-
-  auto linked = app_ns->Link(*platform_ns, system_exposed_libraries);
-  if (!linked) {
-    return linked.error();
-  }
-
-  auto runtime_ns = NativeLoaderNamespace::GetExportedNamespace(kRuntimeNamespaceName, is_bridged);
-  // Runtime apex does not exist in host, and under certain build conditions.
-  if (runtime_ns) {
-    linked = app_ns->Link(*runtime_ns, runtime_public_libraries());
-    if (!linked) {
-      return linked.error();
-    }
-  }
-
-  // Give access to NNAPI libraries (apex-updated LLNDK library).
-  auto nnapi_ns =
-      NativeLoaderNamespace::GetExportedNamespace(kNeuralNetworksNamespaceName, is_bridged);
-  if (nnapi_ns) {
-    linked = app_ns->Link(*nnapi_ns, neuralnetworks_public_libraries());
-    if (!linked) {
-      return linked.error();
-    }
-  }
-
-  // Give access to VNDK-SP libraries from the 'vndk' namespace.
-  if (unbundled_vendor_or_product_app && !vndksp_libraries().empty()) {
-    auto vndk_ns = NativeLoaderNamespace::GetExportedNamespace(kVndkNamespaceName, is_bridged);
-    if (vndk_ns) {
-      linked = app_ns->Link(*vndk_ns, vndksp_libraries());
-      if (!linked) {
-        return linked.error();
-      }
-    }
-  }
-
-  if (!vendor_public_libraries().empty()) {
-    auto vendor_ns = NativeLoaderNamespace::GetExportedNamespace(kVendorNamespaceName, is_bridged);
-    // when vendor_ns is not configured, link to the platform namespace
-    auto target_ns = vendor_ns ? vendor_ns : platform_ns;
-    if (target_ns) {
-      linked = app_ns->Link(*target_ns, vendor_public_libraries());
-      if (!linked) {
-        return linked.error();
-      }
-    }
-  }
-
-  namespaces_.push_back(std::make_pair(env->NewWeakGlobalRef(class_loader), *app_ns));
-  if (is_main_classloader) {
-    app_main_namespace_ = &(*app_ns);
-  }
-
-  return &(namespaces_.back().second);
-}
-
-NativeLoaderNamespace* LibraryNamespaces::FindNamespaceByClassLoader(JNIEnv* env,
-                                                                     jobject class_loader) {
-  auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
-                         [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
-                           return env->IsSameObject(value.first, class_loader);
-                         });
-  if (it != namespaces_.end()) {
-    return &it->second;
-  }
-
-  return nullptr;
-}
-
-NativeLoaderNamespace* LibraryNamespaces::FindParentNamespaceByClassLoader(JNIEnv* env,
-                                                                           jobject class_loader) {
-  jobject parent_class_loader = GetParentClassLoader(env, class_loader);
-
-  while (parent_class_loader != nullptr) {
-    NativeLoaderNamespace* ns;
-    if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
-      return ns;
-    }
-
-    parent_class_loader = GetParentClassLoader(env, parent_class_loader);
-  }
-
-  return nullptr;
-}
-
-}  // namespace android::nativeloader
diff --git a/libnativeloader/library_namespaces.h b/libnativeloader/library_namespaces.h
deleted file mode 100644
index 7b3efff..0000000
--- a/libnativeloader/library_namespaces.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2019 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
-#if !defined(__ANDROID__)
-#error "Not available for host"
-#endif
-
-#define LOG_TAG "nativeloader"
-
-#include "native_loader_namespace.h"
-
-#include <list>
-#include <string>
-
-#include <android-base/result.h>
-#include <jni.h>
-
-namespace android::nativeloader {
-
-using android::base::Result;
-
-// LibraryNamespaces is a singleton object that manages NativeLoaderNamespace
-// objects for an app process. Its main job is to create (and configure) a new
-// NativeLoaderNamespace object for a Java ClassLoader, and to find an existing
-// object for a given ClassLoader.
-class LibraryNamespaces {
- public:
-  LibraryNamespaces() : initialized_(false), app_main_namespace_(nullptr) {}
-
-  LibraryNamespaces(LibraryNamespaces&&) = default;
-  LibraryNamespaces(const LibraryNamespaces&) = delete;
-  LibraryNamespaces& operator=(const LibraryNamespaces&) = delete;
-
-  void Initialize();
-  void Reset() {
-    namespaces_.clear();
-    initialized_ = false;
-    app_main_namespace_ = nullptr;
-  }
-  Result<NativeLoaderNamespace*> Create(JNIEnv* env, uint32_t target_sdk_version,
-                                        jobject class_loader, bool is_shared, jstring dex_path,
-                                        jstring java_library_path, jstring java_permitted_path);
-  NativeLoaderNamespace* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader);
-
- private:
-  Result<void> InitPublicNamespace(const char* library_path);
-  NativeLoaderNamespace* FindParentNamespaceByClassLoader(JNIEnv* env, jobject class_loader);
-
-  bool initialized_;
-  NativeLoaderNamespace* app_main_namespace_;
-  std::list<std::pair<jweak, NativeLoaderNamespace>> namespaces_;
-};
-
-}  // namespace android::nativeloader
diff --git a/libnativeloader/native_loader.cpp b/libnativeloader/native_loader.cpp
deleted file mode 100644
index 60d462f..0000000
--- a/libnativeloader/native_loader.cpp
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
- * Copyright (C) 2015 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.
- */
-
-#define LOG_TAG "nativeloader"
-
-#include "nativeloader/native_loader.h"
-
-#include <dlfcn.h>
-#include <sys/types.h>
-
-#include <memory>
-#include <mutex>
-#include <string>
-#include <vector>
-
-#include <android-base/file.h>
-#include <android-base/macros.h>
-#include <android-base/strings.h>
-#include <nativebridge/native_bridge.h>
-#include <nativehelper/ScopedUtfChars.h>
-
-#ifdef __ANDROID__
-#include <log/log.h>
-#include "library_namespaces.h"
-#include "nativeloader/dlext_namespaces.h"
-#endif
-
-namespace android {
-
-namespace {
-#if defined(__ANDROID__)
-using android::nativeloader::LibraryNamespaces;
-
-constexpr const char* kApexPath = "/apex/";
-
-std::mutex g_namespaces_mutex;
-LibraryNamespaces* g_namespaces = new LibraryNamespaces;
-
-android_namespace_t* FindExportedNamespace(const char* caller_location) {
-  std::string location = caller_location;
-  // Lots of implicit assumptions here: we expect `caller_location` to be of the form:
-  // /apex/com.android...modulename/...
-  //
-  // And we extract from it 'modulename', which is the name of the linker namespace.
-  if (android::base::StartsWith(location, kApexPath)) {
-    size_t slash_index = location.find_first_of('/', strlen(kApexPath));
-    LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
-                        "Error finding namespace of apex: no slash in path %s", caller_location);
-    size_t dot_index = location.find_last_of('.', slash_index);
-    LOG_ALWAYS_FATAL_IF((dot_index == std::string::npos),
-                        "Error finding namespace of apex: no dot in apex name %s", caller_location);
-    std::string name = location.substr(dot_index + 1, slash_index - dot_index - 1);
-    // TODO(b/139408016): Rename the runtime namespace to "art".
-    if (name == "art") {
-      name = "runtime";
-    }
-    android_namespace_t* boot_namespace = android_get_exported_namespace(name.c_str());
-    LOG_ALWAYS_FATAL_IF((boot_namespace == nullptr),
-                        "Error finding namespace of apex: no namespace called %s", name.c_str());
-    return boot_namespace;
-  }
-  return nullptr;
-}
-#endif  // #if defined(__ANDROID__)
-}  // namespace
-
-void InitializeNativeLoader() {
-#if defined(__ANDROID__)
-  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  g_namespaces->Initialize();
-#endif
-}
-
-void ResetNativeLoader() {
-#if defined(__ANDROID__)
-  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  g_namespaces->Reset();
-#endif
-}
-
-jstring CreateClassLoaderNamespace(JNIEnv* env, int32_t target_sdk_version, jobject class_loader,
-                                   bool is_shared, jstring dex_path, jstring library_path,
-                                   jstring permitted_path) {
-#if defined(__ANDROID__)
-  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  auto ns = g_namespaces->Create(env, target_sdk_version, class_loader, is_shared, dex_path,
-                                 library_path, permitted_path);
-  if (!ns) {
-    return env->NewStringUTF(ns.error().message().c_str());
-  }
-#else
-  UNUSED(env, target_sdk_version, class_loader, is_shared, dex_path, library_path, permitted_path);
-#endif
-  return nullptr;
-}
-
-void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
-                        jobject class_loader, const char* caller_location, jstring library_path,
-                        bool* needs_native_bridge, char** error_msg) {
-#if defined(__ANDROID__)
-  UNUSED(target_sdk_version);
-  if (class_loader == nullptr) {
-    *needs_native_bridge = false;
-    if (caller_location != nullptr) {
-      android_namespace_t* boot_namespace = FindExportedNamespace(caller_location);
-      if (boot_namespace != nullptr) {
-        const android_dlextinfo dlextinfo = {
-            .flags = ANDROID_DLEXT_USE_NAMESPACE,
-            .library_namespace = boot_namespace,
-        };
-        void* handle = android_dlopen_ext(path, RTLD_NOW, &dlextinfo);
-        if (handle == nullptr) {
-          *error_msg = strdup(dlerror());
-        }
-        return handle;
-      }
-    }
-    void* handle = dlopen(path, RTLD_NOW);
-    if (handle == nullptr) {
-      *error_msg = strdup(dlerror());
-    }
-    return handle;
-  }
-
-  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  NativeLoaderNamespace* ns;
-
-  if ((ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader)) == nullptr) {
-    // This is the case where the classloader was not created by ApplicationLoaders
-    // In this case we create an isolated not-shared namespace for it.
-    Result<NativeLoaderNamespace*> isolated_ns =
-        g_namespaces->Create(env, target_sdk_version, class_loader, false /* is_shared */, nullptr,
-                             library_path, nullptr);
-    if (!isolated_ns) {
-      *error_msg = strdup(isolated_ns.error().message().c_str());
-      return nullptr;
-    } else {
-      ns = *isolated_ns;
-    }
-  }
-
-  return OpenNativeLibraryInNamespace(ns, path, needs_native_bridge, error_msg);
-#else
-  UNUSED(env, target_sdk_version, class_loader, caller_location);
-
-  // Do some best effort to emulate library-path support. It will not
-  // work for dependencies.
-  //
-  // Note: null has a special meaning and must be preserved.
-  std::string c_library_path;  // Empty string by default.
-  if (library_path != nullptr && path != nullptr && path[0] != '/') {
-    ScopedUtfChars library_path_utf_chars(env, library_path);
-    c_library_path = library_path_utf_chars.c_str();
-  }
-
-  std::vector<std::string> library_paths = base::Split(c_library_path, ":");
-
-  for (const std::string& lib_path : library_paths) {
-    *needs_native_bridge = false;
-    const char* path_arg;
-    std::string complete_path;
-    if (path == nullptr) {
-      // Preserve null.
-      path_arg = nullptr;
-    } else {
-      complete_path = lib_path;
-      if (!complete_path.empty()) {
-        complete_path.append("/");
-      }
-      complete_path.append(path);
-      path_arg = complete_path.c_str();
-    }
-    void* handle = dlopen(path_arg, RTLD_NOW);
-    if (handle != nullptr) {
-      return handle;
-    }
-    if (NativeBridgeIsSupported(path_arg)) {
-      *needs_native_bridge = true;
-      handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
-      if (handle != nullptr) {
-        return handle;
-      }
-      *error_msg = strdup(NativeBridgeGetError());
-    } else {
-      *error_msg = strdup(dlerror());
-    }
-  }
-  return nullptr;
-#endif
-}
-
-bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
-  bool success;
-  if (needs_native_bridge) {
-    success = (NativeBridgeUnloadLibrary(handle) == 0);
-    if (!success) {
-      *error_msg = strdup(NativeBridgeGetError());
-    }
-  } else {
-    success = (dlclose(handle) == 0);
-    if (!success) {
-      *error_msg = strdup(dlerror());
-    }
-  }
-
-  return success;
-}
-
-void NativeLoaderFreeErrorMessage(char* msg) {
-  // The error messages get allocated through strdup, so we must call free on them.
-  free(msg);
-}
-
-#if defined(__ANDROID__)
-void* OpenNativeLibraryInNamespace(NativeLoaderNamespace* ns, const char* path,
-                                   bool* needs_native_bridge, char** error_msg) {
-  auto handle = ns->Load(path);
-  if (!handle && error_msg != nullptr) {
-    *error_msg = strdup(handle.error().message().c_str());
-  }
-  if (needs_native_bridge != nullptr) {
-    *needs_native_bridge = ns->IsBridged();
-  }
-  return handle ? *handle : nullptr;
-}
-
-// native_bridge_namespaces are not supported for callers of this function.
-// This function will return nullptr in the case when application is running
-// on native bridge.
-android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
-  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  NativeLoaderNamespace* ns = g_namespaces->FindNamespaceByClassLoader(env, class_loader);
-  if (ns != nullptr && !ns->IsBridged()) {
-    return ns->ToRawAndroidNamespace();
-  }
-  return nullptr;
-}
-
-NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
-  std::lock_guard<std::mutex> guard(g_namespaces_mutex);
-  return g_namespaces->FindNamespaceByClassLoader(env, class_loader);
-}
-#endif
-
-};  // namespace android
diff --git a/libnativeloader/native_loader_lazy.cpp b/libnativeloader/native_loader_lazy.cpp
deleted file mode 100644
index 2eb1203..0000000
--- a/libnativeloader/native_loader_lazy.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2019 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 "nativeloader/native_loader.h"
-#define LOG_TAG "nativeloader"
-
-#include <dlfcn.h>
-#include <errno.h>
-#include <string.h>
-
-#include <log/log.h>
-
-namespace android {
-
-namespace {
-
-void* GetLibHandle() {
-  static void* handle = dlopen("libnativeloader.so", RTLD_NOW);
-  LOG_FATAL_IF(handle == nullptr, "Failed to load libnativeloader.so: %s", dlerror());
-  return handle;
-}
-
-template <typename FuncPtr>
-FuncPtr GetFuncPtr(const char* function_name) {
-  auto f = reinterpret_cast<FuncPtr>(dlsym(GetLibHandle(), function_name));
-  LOG_FATAL_IF(f == nullptr, "Failed to get address of %s: %s", function_name, dlerror());
-  return f;
-}
-
-#define GET_FUNC_PTR(name) GetFuncPtr<decltype(&name)>(#name)
-
-}  // namespace
-
-void InitializeNativeLoader() {
-  static auto f = GET_FUNC_PTR(InitializeNativeLoader);
-  return f();
-}
-
-jstring CreateClassLoaderNamespace(JNIEnv* env, int32_t target_sdk_version, jobject class_loader,
-                                   bool is_shared, jstring dex_path, jstring library_path,
-                                   jstring permitted_path) {
-  static auto f = GET_FUNC_PTR(CreateClassLoaderNamespace);
-  return f(env, target_sdk_version, class_loader, is_shared, dex_path, library_path,
-           permitted_path);
-}
-
-void* OpenNativeLibrary(JNIEnv* env, int32_t target_sdk_version, const char* path,
-                        jobject class_loader, const char* caller_location, jstring library_path,
-                        bool* needs_native_bridge, char** error_msg) {
-  static auto f = GET_FUNC_PTR(OpenNativeLibrary);
-  return f(env, target_sdk_version, path, class_loader, caller_location, library_path,
-           needs_native_bridge, error_msg);
-}
-
-bool CloseNativeLibrary(void* handle, const bool needs_native_bridge, char** error_msg) {
-  static auto f = GET_FUNC_PTR(CloseNativeLibrary);
-  return f(handle, needs_native_bridge, error_msg);
-}
-
-void NativeLoaderFreeErrorMessage(char* msg) {
-  static auto f = GET_FUNC_PTR(NativeLoaderFreeErrorMessage);
-  return f(msg);
-}
-
-struct android_namespace_t* FindNamespaceByClassLoader(JNIEnv* env, jobject class_loader) {
-  static auto f = GET_FUNC_PTR(FindNamespaceByClassLoader);
-  return f(env, class_loader);
-}
-
-struct NativeLoaderNamespace* FindNativeLoaderNamespaceByClassLoader(JNIEnv* env,
-                                                                     jobject class_loader) {
-  static auto f = GET_FUNC_PTR(FindNativeLoaderNamespaceByClassLoader);
-  return f(env, class_loader);
-}
-
-void* OpenNativeLibraryInNamespace(struct NativeLoaderNamespace* ns, const char* path,
-                                   bool* needs_native_bridge, char** error_msg) {
-  static auto f = GET_FUNC_PTR(OpenNativeLibraryInNamespace);
-  return f(ns, path, needs_native_bridge, error_msg);
-}
-
-void ResetNativeLoader() {
-  static auto f = GET_FUNC_PTR(ResetNativeLoader);
-  return f();
-}
-
-#undef GET_FUNC_PTR
-
-}  // namespace android
diff --git a/libnativeloader/native_loader_namespace.cpp b/libnativeloader/native_loader_namespace.cpp
deleted file mode 100644
index a81fddf..0000000
--- a/libnativeloader/native_loader_namespace.cpp
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Copyright (C) 2019 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.
- */
-
-#define LOG_TAG "nativeloader"
-
-#include "native_loader_namespace.h"
-
-#include <dlfcn.h>
-
-#include <functional>
-
-#include <android-base/strings.h>
-#include <log/log.h>
-#include <nativebridge/native_bridge.h>
-
-#include "nativeloader/dlext_namespaces.h"
-
-using android::base::Error;
-using android::base::Errorf;
-
-namespace android {
-
-namespace {
-
-constexpr const char* kDefaultNamespaceName = "default";
-constexpr const char* kPlatformNamespaceName = "platform";
-
-std::string GetLinkerError(bool is_bridged) {
-  const char* msg = is_bridged ? NativeBridgeGetError() : dlerror();
-  if (msg == nullptr) {
-    return "no error";
-  }
-  return std::string(msg);
-}
-
-}  // namespace
-
-Result<NativeLoaderNamespace> NativeLoaderNamespace::GetExportedNamespace(const std::string& name,
-                                                                          bool is_bridged) {
-  if (!is_bridged) {
-    auto raw = android_get_exported_namespace(name.c_str());
-    if (raw != nullptr) {
-      return NativeLoaderNamespace(name, raw);
-    }
-  } else {
-    auto raw = NativeBridgeGetExportedNamespace(name.c_str());
-    if (raw != nullptr) {
-      return NativeLoaderNamespace(name, raw);
-    }
-  }
-  return Errorf("namespace {} does not exist or exported", name);
-}
-
-// The platform namespace is called "default" for binaries in /system and
-// "platform" for those in the Runtime APEX. Try "platform" first since
-// "default" always exists.
-Result<NativeLoaderNamespace> NativeLoaderNamespace::GetPlatformNamespace(bool is_bridged) {
-  auto ns = GetExportedNamespace(kPlatformNamespaceName, is_bridged);
-  if (ns) return ns;
-  ns = GetExportedNamespace(kDefaultNamespaceName, is_bridged);
-  if (ns) return ns;
-
-  // If nothing is found, return NativeLoaderNamespace constructed from nullptr.
-  // nullptr also means default namespace to the linker.
-  if (!is_bridged) {
-    return NativeLoaderNamespace(kDefaultNamespaceName, static_cast<android_namespace_t*>(nullptr));
-  } else {
-    return NativeLoaderNamespace(kDefaultNamespaceName,
-                                 static_cast<native_bridge_namespace_t*>(nullptr));
-  }
-}
-
-Result<NativeLoaderNamespace> NativeLoaderNamespace::Create(
-    const std::string& name, const std::string& search_paths, const std::string& permitted_paths,
-    const NativeLoaderNamespace* parent, bool is_shared, bool is_greylist_enabled,
-    bool also_used_as_anonymous) {
-  bool is_bridged = false;
-  if (parent != nullptr) {
-    is_bridged = parent->IsBridged();
-  } else if (!search_paths.empty()) {
-    is_bridged = NativeBridgeIsPathSupported(search_paths.c_str());
-  }
-
-  // Fall back to the platform namespace if no parent is set.
-  auto platform_ns = GetPlatformNamespace(is_bridged);
-  if (!platform_ns) {
-    return platform_ns.error();
-  }
-  const NativeLoaderNamespace& effective_parent = parent != nullptr ? *parent : *platform_ns;
-
-  // All namespaces for apps are isolated
-  uint64_t type = ANDROID_NAMESPACE_TYPE_ISOLATED;
-
-  // The namespace is also used as the anonymous namespace
-  // which is used when the linker fails to determine the caller address
-  if (also_used_as_anonymous) {
-    type |= ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS;
-  }
-
-  // Bundled apps have access to all system libraries that are currently loaded
-  // in the default namespace
-  if (is_shared) {
-    type |= ANDROID_NAMESPACE_TYPE_SHARED;
-  }
-  if (is_greylist_enabled) {
-    type |= ANDROID_NAMESPACE_TYPE_GREYLIST_ENABLED;
-  }
-
-  if (!is_bridged) {
-    android_namespace_t* raw =
-        android_create_namespace(name.c_str(), nullptr, search_paths.c_str(), type,
-                                 permitted_paths.c_str(), effective_parent.ToRawAndroidNamespace());
-    if (raw != nullptr) {
-      return NativeLoaderNamespace(name, raw);
-    }
-  } else {
-    native_bridge_namespace_t* raw = NativeBridgeCreateNamespace(
-        name.c_str(), nullptr, search_paths.c_str(), type, permitted_paths.c_str(),
-        effective_parent.ToRawNativeBridgeNamespace());
-    if (raw != nullptr) {
-      return NativeLoaderNamespace(name, raw);
-    }
-  }
-  return Errorf("failed to create {} namespace name:{}, search_paths:{}, permitted_paths:{}",
-                is_bridged ? "bridged" : "native", name, search_paths, permitted_paths);
-}
-
-Result<void> NativeLoaderNamespace::Link(const NativeLoaderNamespace& target,
-                                         const std::string& shared_libs) const {
-  LOG_ALWAYS_FATAL_IF(shared_libs.empty(), "empty share lib when linking %s to %s",
-                      this->name().c_str(), target.name().c_str());
-  if (!IsBridged()) {
-    if (android_link_namespaces(this->ToRawAndroidNamespace(), target.ToRawAndroidNamespace(),
-                                shared_libs.c_str())) {
-      return {};
-    }
-  } else {
-    if (NativeBridgeLinkNamespaces(this->ToRawNativeBridgeNamespace(),
-                                   target.ToRawNativeBridgeNamespace(), shared_libs.c_str())) {
-      return {};
-    }
-  }
-  return Error() << GetLinkerError(IsBridged());
-}
-
-Result<void*> NativeLoaderNamespace::Load(const char* lib_name) const {
-  if (!IsBridged()) {
-    android_dlextinfo extinfo;
-    extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
-    extinfo.library_namespace = this->ToRawAndroidNamespace();
-    void* handle = android_dlopen_ext(lib_name, RTLD_NOW, &extinfo);
-    if (handle != nullptr) {
-      return handle;
-    }
-  } else {
-    void* handle =
-        NativeBridgeLoadLibraryExt(lib_name, RTLD_NOW, this->ToRawNativeBridgeNamespace());
-    if (handle != nullptr) {
-      return handle;
-    }
-  }
-  return Error() << GetLinkerError(IsBridged());
-}
-
-}  // namespace android
diff --git a/libnativeloader/native_loader_namespace.h b/libnativeloader/native_loader_namespace.h
deleted file mode 100644
index 7200ee7..0000000
--- a/libnativeloader/native_loader_namespace.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2019 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
-#if defined(__ANDROID__)
-
-#include <string>
-#include <variant>
-#include <vector>
-
-#include <android-base/logging.h>
-#include <android-base/result.h>
-#include <android/dlext.h>
-#include <log/log.h>
-#include <nativebridge/native_bridge.h>
-
-namespace android {
-
-using android::base::Result;
-
-// NativeLoaderNamespace abstracts a linker namespace for the native
-// architecture (ex: arm on arm) or the translated architecture (ex: arm on
-// x86). Instances of this class are managed by LibraryNamespaces object.
-struct NativeLoaderNamespace {
- public:
-  static Result<NativeLoaderNamespace> Create(const std::string& name,
-                                              const std::string& search_paths,
-                                              const std::string& permitted_paths,
-                                              const NativeLoaderNamespace* parent, bool is_shared,
-                                              bool is_greylist_enabled,
-                                              bool also_used_as_anonymous);
-
-  NativeLoaderNamespace(NativeLoaderNamespace&&) = default;
-  NativeLoaderNamespace(const NativeLoaderNamespace&) = default;
-  NativeLoaderNamespace& operator=(const NativeLoaderNamespace&) = default;
-
-  android_namespace_t* ToRawAndroidNamespace() const { return std::get<0>(raw_); }
-  native_bridge_namespace_t* ToRawNativeBridgeNamespace() const { return std::get<1>(raw_); }
-
-  std::string name() const { return name_; }
-  bool IsBridged() const { return raw_.index() == 1; }
-
-  Result<void> Link(const NativeLoaderNamespace& target, const std::string& shared_libs) const;
-  Result<void*> Load(const char* lib_name) const;
-
-  static Result<NativeLoaderNamespace> GetExportedNamespace(const std::string& name,
-                                                            bool is_bridged);
-  static Result<NativeLoaderNamespace> GetPlatformNamespace(bool is_bridged);
-
- private:
-  explicit NativeLoaderNamespace(const std::string& name, android_namespace_t* ns)
-      : name_(name), raw_(ns) {}
-  explicit NativeLoaderNamespace(const std::string& name, native_bridge_namespace_t* ns)
-      : name_(name), raw_(ns) {}
-
-  std::string name_;
-  std::variant<android_namespace_t*, native_bridge_namespace_t*> raw_;
-};
-
-}  // namespace android
-#endif  // #if defined(__ANDROID__)
diff --git a/libnativeloader/native_loader_test.cpp b/libnativeloader/native_loader_test.cpp
deleted file mode 100644
index 75255b6..0000000
--- a/libnativeloader/native_loader_test.cpp
+++ /dev/null
@@ -1,663 +0,0 @@
-/*
- * Copyright (C) 2019 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 <dlfcn.h>
-#include <memory>
-#include <unordered_map>
-
-#include <android-base/strings.h>
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-#include <jni.h>
-
-#include "native_loader_namespace.h"
-#include "nativeloader/dlext_namespaces.h"
-#include "nativeloader/native_loader.h"
-#include "public_libraries.h"
-
-using namespace ::testing;
-using namespace ::android::nativeloader::internal;
-
-namespace android {
-namespace nativeloader {
-
-// gmock interface that represents interested platform APIs on libdl and libnativebridge
-class Platform {
- public:
-  virtual ~Platform() {}
-
-  // libdl APIs
-  virtual void* dlopen(const char* filename, int flags) = 0;
-  virtual int dlclose(void* handle) = 0;
-  virtual char* dlerror(void) = 0;
-
-  // These mock_* are the APIs semantically the same across libdl and libnativebridge.
-  // Instead of having two set of mock APIs for the two, define only one set with an additional
-  // argument 'bool bridged' to identify the context (i.e., called for libdl or libnativebridge).
-  typedef char* mock_namespace_handle;
-  virtual bool mock_init_anonymous_namespace(bool bridged, const char* sonames,
-                                             const char* search_paths) = 0;
-  virtual mock_namespace_handle mock_create_namespace(
-      bool bridged, const char* name, const char* ld_library_path, const char* default_library_path,
-      uint64_t type, const char* permitted_when_isolated_path, mock_namespace_handle parent) = 0;
-  virtual bool mock_link_namespaces(bool bridged, mock_namespace_handle from,
-                                    mock_namespace_handle to, const char* sonames) = 0;
-  virtual mock_namespace_handle mock_get_exported_namespace(bool bridged, const char* name) = 0;
-  virtual void* mock_dlopen_ext(bool bridged, const char* filename, int flags,
-                                mock_namespace_handle ns) = 0;
-
-  // libnativebridge APIs for which libdl has no corresponding APIs
-  virtual bool NativeBridgeInitialized() = 0;
-  virtual const char* NativeBridgeGetError() = 0;
-  virtual bool NativeBridgeIsPathSupported(const char*) = 0;
-  virtual bool NativeBridgeIsSupported(const char*) = 0;
-
-  // To mock "ClassLoader Object.getParent()"
-  virtual const char* JniObject_getParent(const char*) = 0;
-};
-
-// The mock does not actually create a namespace object. But simply casts the pointer to the
-// string for the namespace name as the handle to the namespace object.
-#define TO_ANDROID_NAMESPACE(str) \
-  reinterpret_cast<struct android_namespace_t*>(const_cast<char*>(str))
-
-#define TO_BRIDGED_NAMESPACE(str) \
-  reinterpret_cast<struct native_bridge_namespace_t*>(const_cast<char*>(str))
-
-#define TO_MOCK_NAMESPACE(ns) reinterpret_cast<Platform::mock_namespace_handle>(ns)
-
-// These represents built-in namespaces created by the linker according to ld.config.txt
-static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
-    {"platform", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("platform"))},
-    {"default", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("default"))},
-    {"runtime", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("runtime"))},
-    {"sphal", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("sphal"))},
-    {"vndk", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk"))},
-    {"neuralnetworks", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("neuralnetworks"))},
-};
-
-// The actual gmock object
-class MockPlatform : public Platform {
- public:
-  MockPlatform(bool is_bridged) : is_bridged_(is_bridged) {
-    ON_CALL(*this, NativeBridgeIsSupported(_)).WillByDefault(Return(is_bridged_));
-    ON_CALL(*this, NativeBridgeIsPathSupported(_)).WillByDefault(Return(is_bridged_));
-    ON_CALL(*this, mock_get_exported_namespace(_, _))
-        .WillByDefault(Invoke([](bool, const char* name) -> mock_namespace_handle {
-          if (namespaces.find(name) != namespaces.end()) {
-            return namespaces[name];
-          }
-          return TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("(namespace not found"));
-        }));
-  }
-
-  // Mocking libdl APIs
-  MOCK_METHOD2(dlopen, void*(const char*, int));
-  MOCK_METHOD1(dlclose, int(void*));
-  MOCK_METHOD0(dlerror, char*());
-
-  // Mocking the common APIs
-  MOCK_METHOD3(mock_init_anonymous_namespace, bool(bool, const char*, const char*));
-  MOCK_METHOD7(mock_create_namespace,
-               mock_namespace_handle(bool, const char*, const char*, const char*, uint64_t,
-                                     const char*, mock_namespace_handle));
-  MOCK_METHOD4(mock_link_namespaces,
-               bool(bool, mock_namespace_handle, mock_namespace_handle, const char*));
-  MOCK_METHOD2(mock_get_exported_namespace, mock_namespace_handle(bool, const char*));
-  MOCK_METHOD4(mock_dlopen_ext, void*(bool, const char*, int, mock_namespace_handle));
-
-  // Mocking libnativebridge APIs
-  MOCK_METHOD0(NativeBridgeInitialized, bool());
-  MOCK_METHOD0(NativeBridgeGetError, const char*());
-  MOCK_METHOD1(NativeBridgeIsPathSupported, bool(const char*));
-  MOCK_METHOD1(NativeBridgeIsSupported, bool(const char*));
-
-  // Mocking "ClassLoader Object.getParent()"
-  MOCK_METHOD1(JniObject_getParent, const char*(const char*));
-
- private:
-  bool is_bridged_;
-};
-
-static std::unique_ptr<MockPlatform> mock;
-
-// Provide C wrappers for the mock object.
-extern "C" {
-void* dlopen(const char* file, int flag) {
-  return mock->dlopen(file, flag);
-}
-
-int dlclose(void* handle) {
-  return mock->dlclose(handle);
-}
-
-char* dlerror(void) {
-  return mock->dlerror();
-}
-
-bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
-  return mock->mock_init_anonymous_namespace(false, sonames, search_path);
-}
-
-struct android_namespace_t* android_create_namespace(const char* name, const char* ld_library_path,
-                                                     const char* default_library_path,
-                                                     uint64_t type,
-                                                     const char* permitted_when_isolated_path,
-                                                     struct android_namespace_t* parent) {
-  return TO_ANDROID_NAMESPACE(
-      mock->mock_create_namespace(false, name, ld_library_path, default_library_path, type,
-                                  permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
-}
-
-bool android_link_namespaces(struct android_namespace_t* from, struct android_namespace_t* to,
-                             const char* sonames) {
-  return mock->mock_link_namespaces(false, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
-}
-
-struct android_namespace_t* android_get_exported_namespace(const char* name) {
-  return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
-}
-
-void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* info) {
-  return mock->mock_dlopen_ext(false, filename, flags, TO_MOCK_NAMESPACE(info->library_namespace));
-}
-
-// libnativebridge APIs
-bool NativeBridgeIsSupported(const char* libpath) {
-  return mock->NativeBridgeIsSupported(libpath);
-}
-
-struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
-  return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
-}
-
-struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
-    const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
-    const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent) {
-  return TO_BRIDGED_NAMESPACE(
-      mock->mock_create_namespace(true, name, ld_library_path, default_library_path, type,
-                                  permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
-}
-
-bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
-                                struct native_bridge_namespace_t* to, const char* sonames) {
-  return mock->mock_link_namespaces(true, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
-}
-
-void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
-                                 struct native_bridge_namespace_t* ns) {
-  return mock->mock_dlopen_ext(true, libpath, flag, TO_MOCK_NAMESPACE(ns));
-}
-
-bool NativeBridgeInitialized() {
-  return mock->NativeBridgeInitialized();
-}
-
-bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
-                                        const char* anon_ns_library_path) {
-  return mock->mock_init_anonymous_namespace(true, public_ns_sonames, anon_ns_library_path);
-}
-
-const char* NativeBridgeGetError() {
-  return mock->NativeBridgeGetError();
-}
-
-bool NativeBridgeIsPathSupported(const char* path) {
-  return mock->NativeBridgeIsPathSupported(path);
-}
-
-}  // extern "C"
-
-// A very simple JNI mock.
-// jstring is a pointer to utf8 char array. We don't need utf16 char here.
-// jobject, jclass, and jmethodID are also a pointer to utf8 char array
-// Only a few JNI methods that are actually used in libnativeloader are mocked.
-JNINativeInterface* CreateJNINativeInterface() {
-  JNINativeInterface* inf = new JNINativeInterface();
-  memset(inf, 0, sizeof(JNINativeInterface));
-
-  inf->GetStringUTFChars = [](JNIEnv*, jstring s, jboolean*) -> const char* {
-    return reinterpret_cast<const char*>(s);
-  };
-
-  inf->ReleaseStringUTFChars = [](JNIEnv*, jstring, const char*) -> void { return; };
-
-  inf->NewStringUTF = [](JNIEnv*, const char* bytes) -> jstring {
-    return reinterpret_cast<jstring>(const_cast<char*>(bytes));
-  };
-
-  inf->FindClass = [](JNIEnv*, const char* name) -> jclass {
-    return reinterpret_cast<jclass>(const_cast<char*>(name));
-  };
-
-  inf->CallObjectMethodV = [](JNIEnv*, jobject obj, jmethodID mid, va_list) -> jobject {
-    if (strcmp("getParent", reinterpret_cast<const char*>(mid)) == 0) {
-      // JniObject_getParent can be a valid jobject or nullptr if there is
-      // no parent classloader.
-      const char* ret = mock->JniObject_getParent(reinterpret_cast<const char*>(obj));
-      return reinterpret_cast<jobject>(const_cast<char*>(ret));
-    }
-    return nullptr;
-  };
-
-  inf->GetMethodID = [](JNIEnv*, jclass, const char* name, const char*) -> jmethodID {
-    return reinterpret_cast<jmethodID>(const_cast<char*>(name));
-  };
-
-  inf->NewWeakGlobalRef = [](JNIEnv*, jobject obj) -> jobject { return obj; };
-
-  inf->IsSameObject = [](JNIEnv*, jobject a, jobject b) -> jboolean {
-    return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)) == 0;
-  };
-
-  return inf;
-}
-
-static void* const any_nonnull = reinterpret_cast<void*>(0x12345678);
-
-// Custom matcher for comparing namespace handles
-MATCHER_P(NsEq, other, "") {
-  *result_listener << "comparing " << reinterpret_cast<const char*>(arg) << " and " << other;
-  return strcmp(reinterpret_cast<const char*>(arg), reinterpret_cast<const char*>(other)) == 0;
-}
-
-/////////////////////////////////////////////////////////////////
-
-// Test fixture
-class NativeLoaderTest : public ::testing::TestWithParam<bool> {
- protected:
-  bool IsBridged() { return GetParam(); }
-
-  void SetUp() override {
-    mock = std::make_unique<NiceMock<MockPlatform>>(IsBridged());
-
-    env = std::make_unique<JNIEnv>();
-    env->functions = CreateJNINativeInterface();
-  }
-
-  void SetExpectations() {
-    std::vector<std::string> default_public_libs =
-        android::base::Split(preloadable_public_libraries(), ":");
-    for (auto l : default_public_libs) {
-      EXPECT_CALL(*mock, dlopen(StrEq(l.c_str()), RTLD_NOW | RTLD_NODELETE))
-          .WillOnce(Return(any_nonnull));
-    }
-  }
-
-  void RunTest() { InitializeNativeLoader(); }
-
-  void TearDown() override {
-    ResetNativeLoader();
-    delete env->functions;
-    mock.reset();
-  }
-
-  std::unique_ptr<JNIEnv> env;
-};
-
-/////////////////////////////////////////////////////////////////
-
-TEST_P(NativeLoaderTest, InitializeLoadsDefaultPublicLibraries) {
-  SetExpectations();
-  RunTest();
-}
-
-INSTANTIATE_TEST_SUITE_P(NativeLoaderTests, NativeLoaderTest, testing::Bool());
-
-/////////////////////////////////////////////////////////////////
-
-class NativeLoaderTest_Create : public NativeLoaderTest {
- protected:
-  // Test inputs (initialized to the default values). Overriding these
-  // must be done before calling SetExpectations() and RunTest().
-  uint32_t target_sdk_version = 29;
-  std::string class_loader = "my_classloader";
-  bool is_shared = false;
-  std::string dex_path = "/data/app/foo/classes.dex";
-  std::string library_path = "/data/app/foo/lib/arm";
-  std::string permitted_path = "/data/app/foo/lib";
-
-  // expected output (.. for the default test inputs)
-  std::string expected_namespace_name = "classloader-namespace";
-  uint64_t expected_namespace_flags =
-      ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS;
-  std::string expected_library_path = library_path;
-  std::string expected_permitted_path = std::string("/data:/mnt/expand:") + permitted_path;
-  std::string expected_parent_namespace = "platform";
-  bool expected_link_with_platform_ns = true;
-  bool expected_link_with_runtime_ns = true;
-  bool expected_link_with_sphal_ns = !vendor_public_libraries().empty();
-  bool expected_link_with_vndk_ns = false;
-  bool expected_link_with_default_ns = false;
-  bool expected_link_with_neuralnetworks_ns = true;
-  std::string expected_shared_libs_to_platform_ns = default_public_libraries();
-  std::string expected_shared_libs_to_runtime_ns = runtime_public_libraries();
-  std::string expected_shared_libs_to_sphal_ns = vendor_public_libraries();
-  std::string expected_shared_libs_to_vndk_ns = vndksp_libraries();
-  std::string expected_shared_libs_to_default_ns = default_public_libraries();
-  std::string expected_shared_libs_to_neuralnetworks_ns = neuralnetworks_public_libraries();
-
-  void SetExpectations() {
-    NativeLoaderTest::SetExpectations();
-
-    ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
-
-    EXPECT_CALL(*mock, NativeBridgeIsPathSupported(_)).Times(AnyNumber());
-    EXPECT_CALL(*mock, NativeBridgeInitialized()).Times(AnyNumber());
-
-    EXPECT_CALL(*mock, mock_create_namespace(
-                           Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
-                           StrEq(expected_library_path), expected_namespace_flags,
-                           StrEq(expected_permitted_path), NsEq(expected_parent_namespace.c_str())))
-        .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(dex_path.c_str()))));
-    if (expected_link_with_platform_ns) {
-      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("platform"),
-                                              StrEq(expected_shared_libs_to_platform_ns)))
-          .WillOnce(Return(true));
-    }
-    if (expected_link_with_runtime_ns) {
-      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("runtime"),
-                                              StrEq(expected_shared_libs_to_runtime_ns)))
-          .WillOnce(Return(true));
-    }
-    if (expected_link_with_sphal_ns) {
-      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("sphal"),
-                                              StrEq(expected_shared_libs_to_sphal_ns)))
-          .WillOnce(Return(true));
-    }
-    if (expected_link_with_vndk_ns) {
-      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk"),
-                                              StrEq(expected_shared_libs_to_vndk_ns)))
-          .WillOnce(Return(true));
-    }
-    if (expected_link_with_default_ns) {
-      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("default"),
-                                              StrEq(expected_shared_libs_to_default_ns)))
-          .WillOnce(Return(true));
-    }
-    if (expected_link_with_neuralnetworks_ns) {
-      EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("neuralnetworks"),
-                                              StrEq(expected_shared_libs_to_neuralnetworks_ns)))
-          .WillOnce(Return(true));
-    }
-  }
-
-  void RunTest() {
-    NativeLoaderTest::RunTest();
-
-    jstring err = CreateClassLoaderNamespace(
-        env(), target_sdk_version, env()->NewStringUTF(class_loader.c_str()), is_shared,
-        env()->NewStringUTF(dex_path.c_str()), env()->NewStringUTF(library_path.c_str()),
-        env()->NewStringUTF(permitted_path.c_str()));
-
-    // no error
-    EXPECT_EQ(err, nullptr);
-
-    if (!IsBridged()) {
-      struct android_namespace_t* ns =
-          FindNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
-
-      // The created namespace is for this apk
-      EXPECT_EQ(dex_path.c_str(), reinterpret_cast<const char*>(ns));
-    } else {
-      struct NativeLoaderNamespace* ns =
-          FindNativeLoaderNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
-
-      // The created namespace is for the this apk
-      EXPECT_STREQ(dex_path.c_str(),
-                   reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
-    }
-  }
-
-  JNIEnv* env() { return NativeLoaderTest::env.get(); }
-};
-
-TEST_P(NativeLoaderTest_Create, DownloadedApp) {
-  SetExpectations();
-  RunTest();
-}
-
-TEST_P(NativeLoaderTest_Create, BundledSystemApp) {
-  dex_path = "/system/app/foo/foo.apk";
-  is_shared = true;
-
-  expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
-  SetExpectations();
-  RunTest();
-}
-
-TEST_P(NativeLoaderTest_Create, BundledVendorApp) {
-  dex_path = "/vendor/app/foo/foo.apk";
-  is_shared = true;
-
-  expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
-  SetExpectations();
-  RunTest();
-}
-
-TEST_P(NativeLoaderTest_Create, UnbundledVendorApp) {
-  dex_path = "/vendor/app/foo/foo.apk";
-  is_shared = false;
-
-  expected_namespace_name = "vendor-classloader-namespace";
-  expected_library_path = expected_library_path + ":/vendor/lib";
-  expected_permitted_path = expected_permitted_path + ":/vendor/lib";
-  expected_shared_libs_to_platform_ns =
-      expected_shared_libs_to_platform_ns + ":" + llndk_libraries();
-  expected_link_with_vndk_ns = true;
-  SetExpectations();
-  RunTest();
-}
-
-TEST_P(NativeLoaderTest_Create, BundledProductApp_pre30) {
-  dex_path = "/product/app/foo/foo.apk";
-  is_shared = true;
-
-  expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
-  SetExpectations();
-  RunTest();
-}
-
-TEST_P(NativeLoaderTest_Create, BundledProductApp_post30) {
-  dex_path = "/product/app/foo/foo.apk";
-  is_shared = true;
-  target_sdk_version = 30;
-
-  expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
-  SetExpectations();
-  RunTest();
-}
-
-TEST_P(NativeLoaderTest_Create, UnbundledProductApp_pre30) {
-  dex_path = "/product/app/foo/foo.apk";
-  is_shared = false;
-  SetExpectations();
-  RunTest();
-}
-
-TEST_P(NativeLoaderTest_Create, UnbundledProductApp_post30) {
-  dex_path = "/product/app/foo/foo.apk";
-  is_shared = false;
-  target_sdk_version = 30;
-
-  expected_namespace_name = "vendor-classloader-namespace";
-  expected_library_path = expected_library_path + ":/product/lib:/system/product/lib";
-  expected_permitted_path = expected_permitted_path + ":/product/lib:/system/product/lib";
-  expected_shared_libs_to_platform_ns =
-      expected_shared_libs_to_platform_ns + ":" + llndk_libraries();
-  expected_link_with_vndk_ns = true;
-  SetExpectations();
-  RunTest();
-}
-
-TEST_P(NativeLoaderTest_Create, NamespaceForSharedLibIsNotUsedAsAnonymousNamespace) {
-  if (IsBridged()) {
-    // There is no shared lib in translated arch
-    // TODO(jiyong): revisit this
-    return;
-  }
-  // compared to apks, for java shared libs, library_path is empty; java shared
-  // libs don't have their own native libs. They use platform's.
-  library_path = "";
-  expected_library_path = library_path;
-  // no ALSO_USED_AS_ANONYMOUS
-  expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
-  SetExpectations();
-  RunTest();
-}
-
-TEST_P(NativeLoaderTest_Create, TwoApks) {
-  SetExpectations();
-  const uint32_t second_app_target_sdk_version = 29;
-  const std::string second_app_class_loader = "second_app_classloader";
-  const bool second_app_is_shared = false;
-  const std::string second_app_dex_path = "/data/app/bar/classes.dex";
-  const std::string second_app_library_path = "/data/app/bar/lib/arm";
-  const std::string second_app_permitted_path = "/data/app/bar/lib";
-  const std::string expected_second_app_permitted_path =
-      std::string("/data:/mnt/expand:") + second_app_permitted_path;
-  const std::string expected_second_app_parent_namespace = "classloader-namespace";
-  // no ALSO_USED_AS_ANONYMOUS
-  const uint64_t expected_second_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
-
-  // The scenario is that second app is loaded by the first app.
-  // So the first app's classloader (`classloader`) is parent of the second
-  // app's classloader.
-  ON_CALL(*mock, JniObject_getParent(StrEq(second_app_class_loader)))
-      .WillByDefault(Return(class_loader.c_str()));
-
-  // namespace for the second app is created. Its parent is set to the namespace
-  // of the first app.
-  EXPECT_CALL(*mock, mock_create_namespace(
-                         Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
-                         StrEq(second_app_library_path), expected_second_namespace_flags,
-                         StrEq(expected_second_app_permitted_path), NsEq(dex_path.c_str())))
-      .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(second_app_dex_path.c_str()))));
-  EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), NsEq(second_app_dex_path.c_str()), _, _))
-      .WillRepeatedly(Return(true));
-
-  RunTest();
-  jstring err = CreateClassLoaderNamespace(
-      env(), second_app_target_sdk_version, env()->NewStringUTF(second_app_class_loader.c_str()),
-      second_app_is_shared, env()->NewStringUTF(second_app_dex_path.c_str()),
-      env()->NewStringUTF(second_app_library_path.c_str()),
-      env()->NewStringUTF(second_app_permitted_path.c_str()));
-
-  // success
-  EXPECT_EQ(err, nullptr);
-
-  if (!IsBridged()) {
-    struct android_namespace_t* ns =
-        FindNamespaceByClassLoader(env(), env()->NewStringUTF(second_app_class_loader.c_str()));
-
-    // The created namespace is for the second apk
-    EXPECT_EQ(second_app_dex_path.c_str(), reinterpret_cast<const char*>(ns));
-  } else {
-    struct NativeLoaderNamespace* ns = FindNativeLoaderNamespaceByClassLoader(
-        env(), env()->NewStringUTF(second_app_class_loader.c_str()));
-
-    // The created namespace is for the second apk
-    EXPECT_STREQ(second_app_dex_path.c_str(),
-                 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
-  }
-}
-
-INSTANTIATE_TEST_SUITE_P(NativeLoaderTests_Create, NativeLoaderTest_Create, testing::Bool());
-
-const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
-    [](const struct ConfigEntry&) -> Result<bool> { return true; };
-
-TEST(NativeLoaderConfigParser, NamesAndComments) {
-  const char file_content[] = R"(
-######
-
-libA.so
-#libB.so
-
-
-      libC.so
-libD.so
-    #### libE.so
-)";
-  const std::vector<std::string> expected_result = {"libA.so", "libC.so", "libD.so"};
-  Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
-  ASSERT_TRUE(result) << result.error().message();
-  ASSERT_EQ(expected_result, *result);
-}
-
-TEST(NativeLoaderConfigParser, WithBitness) {
-  const char file_content[] = R"(
-libA.so 32
-libB.so 64
-libC.so
-)";
-#if defined(__LP64__)
-  const std::vector<std::string> expected_result = {"libB.so", "libC.so"};
-#else
-  const std::vector<std::string> expected_result = {"libA.so", "libC.so"};
-#endif
-  Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
-  ASSERT_TRUE(result) << result.error().message();
-  ASSERT_EQ(expected_result, *result);
-}
-
-TEST(NativeLoaderConfigParser, WithNoPreload) {
-  const char file_content[] = R"(
-libA.so nopreload
-libB.so nopreload
-libC.so
-)";
-
-  const std::vector<std::string> expected_result = {"libC.so"};
-  Result<std::vector<std::string>> result =
-      ParseConfig(file_content,
-                  [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
-  ASSERT_TRUE(result) << result.error().message();
-  ASSERT_EQ(expected_result, *result);
-}
-
-TEST(NativeLoaderConfigParser, WithNoPreloadAndBitness) {
-  const char file_content[] = R"(
-libA.so nopreload 32
-libB.so 64 nopreload
-libC.so 32
-libD.so 64
-libE.so nopreload
-)";
-
-#if defined(__LP64__)
-  const std::vector<std::string> expected_result = {"libD.so"};
-#else
-  const std::vector<std::string> expected_result = {"libC.so"};
-#endif
-  Result<std::vector<std::string>> result =
-      ParseConfig(file_content,
-                  [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
-  ASSERT_TRUE(result) << result.error().message();
-  ASSERT_EQ(expected_result, *result);
-}
-
-TEST(NativeLoaderConfigParser, RejectMalformed) {
-  ASSERT_FALSE(ParseConfig("libA.so 32 64", always_true));
-  ASSERT_FALSE(ParseConfig("libA.so 32 32", always_true));
-  ASSERT_FALSE(ParseConfig("libA.so 32 nopreload 64", always_true));
-  ASSERT_FALSE(ParseConfig("32 libA.so nopreload", always_true));
-  ASSERT_FALSE(ParseConfig("nopreload libA.so 32", always_true));
-  ASSERT_FALSE(ParseConfig("libA.so nopreload # comment", always_true));
-}
-
-}  // namespace nativeloader
-}  // namespace android
diff --git a/libnativeloader/public_libraries.cpp b/libnativeloader/public_libraries.cpp
deleted file mode 100644
index 93df1d0..0000000
--- a/libnativeloader/public_libraries.cpp
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * Copyright (C) 2019 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.
- */
-
-#define LOG_TAG "nativeloader"
-
-#include "public_libraries.h"
-
-#include <dirent.h>
-
-#include <algorithm>
-#include <memory>
-
-#include <android-base/file.h>
-#include <android-base/logging.h>
-#include <android-base/properties.h>
-#include <android-base/result.h>
-#include <android-base/strings.h>
-#include <log/log.h>
-
-#include "utils.h"
-
-namespace android::nativeloader {
-
-using namespace internal;
-using namespace ::std::string_literals;
-using android::base::ErrnoError;
-using android::base::Errorf;
-using android::base::Result;
-
-namespace {
-
-constexpr const char* kDefaultPublicLibrariesFile = "/etc/public.libraries.txt";
-constexpr const char* kExtendedPublicLibrariesFilePrefix = "public.libraries-";
-constexpr const char* kExtendedPublicLibrariesFileSuffix = ".txt";
-constexpr const char* kVendorPublicLibrariesFile = "/vendor/etc/public.libraries.txt";
-constexpr const char* kLlndkLibrariesFile = "/system/etc/llndk.libraries.txt";
-constexpr const char* kVndkLibrariesFile = "/system/etc/vndksp.libraries.txt";
-
-const std::vector<const std::string> kArtApexPublicLibraries = {
-    "libicuuc.so",
-    "libicui18n.so",
-};
-
-constexpr const char* kArtApexLibPath = "/apex/com.android.art/" LIB;
-
-constexpr const char* kNeuralNetworksApexPublicLibrary = "libneuralnetworks.so";
-
-// TODO(b/130388701): do we need this?
-std::string root_dir() {
-  static const char* android_root_env = getenv("ANDROID_ROOT");
-  return android_root_env != nullptr ? android_root_env : "/system";
-}
-
-bool debuggable() {
-  static bool debuggable = android::base::GetBoolProperty("ro.debuggable", false);
-  return debuggable;
-}
-
-std::string vndk_version_str() {
-  static std::string version = android::base::GetProperty("ro.vndk.version", "");
-  if (version != "" && version != "current") {
-    return "." + version;
-  }
-  return "";
-}
-
-// For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
-// variable to add libraries to the list. This is intended for platform tests only.
-std::string additional_public_libraries() {
-  if (debuggable()) {
-    const char* val = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
-    return val ? val : "";
-  }
-  return "";
-}
-
-void InsertVndkVersionStr(std::string* file_name) {
-  CHECK(file_name != nullptr);
-  size_t insert_pos = file_name->find_last_of(".");
-  if (insert_pos == std::string::npos) {
-    insert_pos = file_name->length();
-  }
-  file_name->insert(insert_pos, vndk_version_str());
-}
-
-const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
-    [](const struct ConfigEntry&) -> Result<bool> { return true; };
-
-Result<std::vector<std::string>> ReadConfig(
-    const std::string& configFile,
-    const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn) {
-  std::string file_content;
-  if (!base::ReadFileToString(configFile, &file_content)) {
-    return ErrnoError();
-  }
-  Result<std::vector<std::string>> result = ParseConfig(file_content, filter_fn);
-  if (!result) {
-    return Errorf("Cannot parse {}: {}", configFile, result.error().message());
-  }
-  return result;
-}
-
-void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
-  std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
-  if (dir != nullptr) {
-    // Failing to opening the dir is not an error, which can happen in
-    // webview_zygote.
-    while (struct dirent* ent = readdir(dir.get())) {
-      if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
-        continue;
-      }
-      const std::string filename(ent->d_name);
-      std::string_view fn = filename;
-      if (android::base::ConsumePrefix(&fn, kExtendedPublicLibrariesFilePrefix) &&
-          android::base::ConsumeSuffix(&fn, kExtendedPublicLibrariesFileSuffix)) {
-        const std::string company_name(fn);
-        const std::string config_file_path = dirname + "/"s + filename;
-        LOG_ALWAYS_FATAL_IF(
-            company_name.empty(),
-            "Error extracting company name from public native library list file path \"%s\"",
-            config_file_path.c_str());
-
-        auto ret = ReadConfig(
-            config_file_path, [&company_name](const struct ConfigEntry& entry) -> Result<bool> {
-              if (android::base::StartsWith(entry.soname, "lib") &&
-                  android::base::EndsWith(entry.soname, "." + company_name + ".so")) {
-                return true;
-              } else {
-                return Errorf("Library name \"{}\" does not end with the company name {}.",
-                              entry.soname, company_name);
-              }
-            });
-        if (ret) {
-          sonames->insert(sonames->end(), ret->begin(), ret->end());
-        } else {
-          LOG_ALWAYS_FATAL("Error reading public native library list from \"%s\": %s",
-                           config_file_path.c_str(), ret.error().message().c_str());
-        }
-      }
-    }
-  }
-}
-
-static std::string InitDefaultPublicLibraries(bool for_preload) {
-  std::string config_file = root_dir() + kDefaultPublicLibrariesFile;
-  auto sonames =
-      ReadConfig(config_file, [&for_preload](const struct ConfigEntry& entry) -> Result<bool> {
-        if (for_preload) {
-          return !entry.nopreload;
-        } else {
-          return true;
-        }
-      });
-  if (!sonames) {
-    LOG_ALWAYS_FATAL("Error reading public native library list from \"%s\": %s",
-                     config_file.c_str(), sonames.error().message().c_str());
-    return "";
-  }
-
-  std::string additional_libs = additional_public_libraries();
-  if (!additional_libs.empty()) {
-    auto vec = base::Split(additional_libs, ":");
-    std::copy(vec.begin(), vec.end(), std::back_inserter(*sonames));
-  }
-
-  // Remove the public libs in the runtime namespace.
-  // These libs are listed in public.android.txt, but we don't want the rest of android
-  // in default namespace to dlopen the libs.
-  // For example, libicuuc.so is exposed to classloader namespace from runtime namespace.
-  // Unfortunately, it does not have stable C symbols, and default namespace should only use
-  // stable symbols in libandroidicu.so. http://b/120786417
-  for (const std::string& lib_name : kArtApexPublicLibraries) {
-    std::string path(kArtApexLibPath);
-    path.append("/").append(lib_name);
-
-    struct stat s;
-    // Do nothing if the path in /apex does not exist.
-    // Runtime APEX must be mounted since libnativeloader is in the same APEX
-    if (stat(path.c_str(), &s) != 0) {
-      continue;
-    }
-
-    auto it = std::find(sonames->begin(), sonames->end(), lib_name);
-    if (it != sonames->end()) {
-      sonames->erase(it);
-    }
-  }
-
-  // Remove the public libs in the nnapi namespace.
-  auto it = std::find(sonames->begin(), sonames->end(), kNeuralNetworksApexPublicLibrary);
-  if (it != sonames->end()) {
-    sonames->erase(it);
-  }
-  return android::base::Join(*sonames, ':');
-}
-
-static std::string InitArtPublicLibraries() {
-  CHECK(sizeof(kArtApexPublicLibraries) > 0);
-  std::string list = android::base::Join(kArtApexPublicLibraries, ":");
-
-  std::string additional_libs = additional_public_libraries();
-  if (!additional_libs.empty()) {
-    list = list + ':' + additional_libs;
-  }
-  return list;
-}
-
-static std::string InitVendorPublicLibraries() {
-  // This file is optional, quietly ignore if the file does not exist.
-  auto sonames = ReadConfig(kVendorPublicLibrariesFile, always_true);
-  if (!sonames) {
-    return "";
-  }
-  return android::base::Join(*sonames, ':');
-}
-
-// read /system/etc/public.libraries-<companyname>.txt and
-// /product/etc/public.libraries-<companyname>.txt which contain partner defined
-// system libs that are exposed to apps. The libs in the txt files must be
-// named as lib<name>.<companyname>.so.
-static std::string InitExtendedPublicLibraries() {
-  std::vector<std::string> sonames;
-  ReadExtensionLibraries("/system/etc", &sonames);
-  ReadExtensionLibraries("/product/etc", &sonames);
-  return android::base::Join(sonames, ':');
-}
-
-static std::string InitLlndkLibraries() {
-  std::string config_file = kLlndkLibrariesFile;
-  InsertVndkVersionStr(&config_file);
-  auto sonames = ReadConfig(config_file, always_true);
-  if (!sonames) {
-    LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
-    return "";
-  }
-  return android::base::Join(*sonames, ':');
-}
-
-static std::string InitVndkspLibraries() {
-  std::string config_file = kVndkLibrariesFile;
-  InsertVndkVersionStr(&config_file);
-  auto sonames = ReadConfig(config_file, always_true);
-  if (!sonames) {
-    LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
-    return "";
-  }
-  return android::base::Join(*sonames, ':');
-}
-
-static std::string InitNeuralNetworksPublicLibraries() {
-  return kNeuralNetworksApexPublicLibrary;
-}
-
-}  // namespace
-
-const std::string& preloadable_public_libraries() {
-  static std::string list = InitDefaultPublicLibraries(/*for_preload*/ true);
-  return list;
-}
-
-const std::string& default_public_libraries() {
-  static std::string list = InitDefaultPublicLibraries(/*for_preload*/ false);
-  return list;
-}
-
-const std::string& runtime_public_libraries() {
-  static std::string list = InitArtPublicLibraries();
-  return list;
-}
-
-const std::string& vendor_public_libraries() {
-  static std::string list = InitVendorPublicLibraries();
-  return list;
-}
-
-const std::string& extended_public_libraries() {
-  static std::string list = InitExtendedPublicLibraries();
-  return list;
-}
-
-const std::string& neuralnetworks_public_libraries() {
-  static std::string list = InitNeuralNetworksPublicLibraries();
-  return list;
-}
-
-const std::string& llndk_libraries() {
-  static std::string list = InitLlndkLibraries();
-  return list;
-}
-
-const std::string& vndksp_libraries() {
-  static std::string list = InitVndkspLibraries();
-  return list;
-}
-
-namespace internal {
-// Exported for testing
-Result<std::vector<std::string>> ParseConfig(
-    const std::string& file_content,
-    const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn) {
-  std::vector<std::string> lines = base::Split(file_content, "\n");
-
-  std::vector<std::string> sonames;
-  for (auto& line : lines) {
-    auto trimmed_line = base::Trim(line);
-    if (trimmed_line[0] == '#' || trimmed_line.empty()) {
-      continue;
-    }
-
-    std::vector<std::string> tokens = android::base::Split(trimmed_line, " ");
-    if (tokens.size() < 1 || tokens.size() > 3) {
-      return Errorf("Malformed line \"{}\"", line);
-    }
-    struct ConfigEntry entry = {.soname = "", .nopreload = false, .bitness = ALL};
-    size_t i = tokens.size();
-    while (i-- > 0) {
-      if (tokens[i] == "nopreload") {
-        entry.nopreload = true;
-      } else if (tokens[i] == "32" || tokens[i] == "64") {
-        if (entry.bitness != ALL) {
-          return Errorf("Malformed line \"{}\": bitness can be specified only once", line);
-        }
-        entry.bitness = tokens[i] == "32" ? ONLY_32 : ONLY_64;
-      } else {
-        if (i != 0) {
-          return Errorf("Malformed line \"{}\"", line);
-        }
-        entry.soname = tokens[i];
-      }
-    }
-
-    // skip 32-bit lib on 64-bit process and vice versa
-#if defined(__LP64__)
-    if (entry.bitness == ONLY_32) continue;
-#else
-    if (entry.bitness == ONLY_64) continue;
-#endif
-
-    Result<bool> ret = filter_fn(entry);
-    if (!ret) {
-      return ret.error();
-    }
-    if (*ret) {
-      // filter_fn has returned true.
-      sonames.push_back(entry.soname);
-    }
-  }
-  return sonames;
-}
-
-}  // namespace internal
-
-}  // namespace android::nativeloader
diff --git a/libnativeloader/public_libraries.h b/libnativeloader/public_libraries.h
deleted file mode 100644
index 2de4172..0000000
--- a/libnativeloader/public_libraries.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2019 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 <algorithm>
-#include <string>
-
-#include <android-base/result.h>
-
-namespace android::nativeloader {
-
-using android::base::Result;
-
-// These provide the list of libraries that are available to the namespace for apps.
-// Not all of the libraries are available to apps. Depending on the context,
-// e.g., if it is a vendor app or not, different set of libraries are made available.
-const std::string& preloadable_public_libraries();
-const std::string& default_public_libraries();
-const std::string& runtime_public_libraries();
-const std::string& vendor_public_libraries();
-const std::string& extended_public_libraries();
-const std::string& neuralnetworks_public_libraries();
-const std::string& llndk_libraries();
-const std::string& vndksp_libraries();
-
-// These are exported for testing
-namespace internal {
-
-enum Bitness { ALL = 0, ONLY_32, ONLY_64 };
-
-struct ConfigEntry {
-  std::string soname;
-  bool nopreload;
-  Bitness bitness;
-};
-
-Result<std::vector<std::string>> ParseConfig(
-    const std::string& file_content,
-    const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn);
-
-}  // namespace internal
-
-}  // namespace android::nativeloader
diff --git a/libnativeloader/test/Android.bp b/libnativeloader/test/Android.bp
deleted file mode 100644
index 4d5c53d..0000000
--- a/libnativeloader/test/Android.bp
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// Copyright (C) 2017 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-cc_library {
-    name: "libfoo.oem1",
-    srcs: ["test.cpp"],
-    cflags: ["-DLIBNAME=\"libfoo.oem1.so\""],
-    shared_libs: [
-        "libbase",
-    ],
-}
-
-cc_library {
-    name: "libbar.oem1",
-    srcs: ["test.cpp"],
-    cflags: ["-DLIBNAME=\"libbar.oem1.so\""],
-    shared_libs: [
-        "libbase",
-    ],
-}
-
-cc_library {
-    name: "libfoo.oem2",
-    srcs: ["test.cpp"],
-    cflags: ["-DLIBNAME=\"libfoo.oem2.so\""],
-    shared_libs: [
-        "libbase",
-    ],
-}
-
-cc_library {
-    name: "libbar.oem2",
-    srcs: ["test.cpp"],
-    cflags: ["-DLIBNAME=\"libbar.oem2.so\""],
-    shared_libs: [
-        "libbase",
-    ],
-}
-
-cc_library {
-    name: "libfoo.product1",
-    srcs: ["test.cpp"],
-    cflags: ["-DLIBNAME=\"libfoo.product1.so\""],
-    product_specific: true,
-    shared_libs: [
-        "libbase",
-    ],
-}
-
-cc_library {
-    name: "libbar.product1",
-    srcs: ["test.cpp"],
-    cflags: ["-DLIBNAME=\"libbar.product1.so\""],
-    product_specific: true,
-    shared_libs: [
-        "libbase",
-    ],
-}
-
-// Build the test for the C API.
-cc_test {
-    name: "libnativeloader-api-tests",
-    host_supported: true,
-    test_per_src: true,
-    srcs: [
-        "api_test.c",
-    ],
-    header_libs: ["libnativeloader-headers"],
-}
diff --git a/libnativeloader/test/Android.mk b/libnativeloader/test/Android.mk
deleted file mode 100644
index 65e7b09..0000000
--- a/libnativeloader/test/Android.mk
+++ /dev/null
@@ -1,57 +0,0 @@
-#
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := public.libraries-oem1.txt
-LOCAL_SRC_FILES:= $(LOCAL_MODULE)
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
-include $(BUILD_PREBUILT)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := public.libraries-oem2.txt
-LOCAL_SRC_FILES:= $(LOCAL_MODULE)
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
-include $(BUILD_PREBUILT)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := public.libraries-product1.txt
-LOCAL_SRC_FILES:= $(LOCAL_MODULE)
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_PRODUCT_ETC)
-include $(BUILD_PREBUILT)
-
-include $(CLEAR_VARS)
-LOCAL_PACKAGE_NAME := oemlibrarytest-system
-LOCAL_MODULE_TAGS := tests
-LOCAL_MANIFEST_FILE := system/AndroidManifest.xml
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_SDK_VERSION := current
-LOCAL_PROGUARD_ENABLED := disabled
-LOCAL_MODULE_PATH := $(TARGET_OUT_APPS)
-include $(BUILD_PACKAGE)
-
-include $(CLEAR_VARS)
-LOCAL_PACKAGE_NAME := oemlibrarytest-vendor
-LOCAL_MODULE_TAGS := tests
-LOCAL_MANIFEST_FILE := vendor/AndroidManifest.xml
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_SDK_VERSION := current
-LOCAL_PROGUARD_ENABLED := disabled
-LOCAL_MODULE_PATH := $(TARGET_OUT_VENDOR_APPS)
-include $(BUILD_PACKAGE)
diff --git a/libnativeloader/test/api_test.c b/libnativeloader/test/api_test.c
deleted file mode 100644
index e7025fd..0000000
--- a/libnativeloader/test/api_test.c
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2019 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.
- */
-
-/* The main purpose of this test is to ensure this C header compiles in C, so
- * that no C++ features inadvertently leak into the C ABI. */
-#include "nativeloader/native_loader.h"
-
-int main(int argc, char** argv) {
-  (void)argc;
-  (void)argv;
-  return 0;
-}
diff --git a/libnativeloader/test/public.libraries-oem1.txt b/libnativeloader/test/public.libraries-oem1.txt
deleted file mode 100644
index f9433e2..0000000
--- a/libnativeloader/test/public.libraries-oem1.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-libfoo.oem1.so
-libbar.oem1.so
diff --git a/libnativeloader/test/public.libraries-oem2.txt b/libnativeloader/test/public.libraries-oem2.txt
deleted file mode 100644
index de6bdb0..0000000
--- a/libnativeloader/test/public.libraries-oem2.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-libfoo.oem2.so
-libbar.oem2.so
diff --git a/libnativeloader/test/public.libraries-product1.txt b/libnativeloader/test/public.libraries-product1.txt
deleted file mode 100644
index 358154c..0000000
--- a/libnativeloader/test/public.libraries-product1.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-libfoo.product1.so
-libbar.product1.so
diff --git a/libnativeloader/test/runtest.sh b/libnativeloader/test/runtest.sh
deleted file mode 100755
index 40beb5b..0000000
--- a/libnativeloader/test/runtest.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/bin/bash
-adb root
-adb remount
-adb sync
-adb shell stop
-adb shell start
-sleep 5 # wait until device reboots
-adb logcat -c;
-adb shell am start -n android.test.app.system/android.test.app.TestActivity
-adb shell am start -n android.test.app.vendor/android.test.app.TestActivity
-adb logcat | grep android.test.app
diff --git a/libnativeloader/test/src/android/test/app/TestActivity.java b/libnativeloader/test/src/android/test/app/TestActivity.java
deleted file mode 100644
index a7a455d..0000000
--- a/libnativeloader/test/src/android/test/app/TestActivity.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.test.app;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.util.Log;
-
-public class TestActivity extends Activity {
-
-    @Override
-    public void onCreate(Bundle icicle) {
-         super.onCreate(icicle);
-         tryLoadingLib("foo.oem1");
-         tryLoadingLib("bar.oem1");
-         tryLoadingLib("foo.oem2");
-         tryLoadingLib("bar.oem2");
-         tryLoadingLib("foo.product1");
-         tryLoadingLib("bar.product1");
-    }
-
-    private void tryLoadingLib(String name) {
-        try {
-            System.loadLibrary(name);
-            Log.d(getPackageName(), "library " + name + " is successfully loaded");
-        } catch (UnsatisfiedLinkError e) {
-            Log.d(getPackageName(), "failed to load libarary " + name, e);
-        }
-    }
-}
diff --git a/libnativeloader/test/system/AndroidManifest.xml b/libnativeloader/test/system/AndroidManifest.xml
deleted file mode 100644
index c304889..0000000
--- a/libnativeloader/test/system/AndroidManifest.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.test.app.system">
-
-    <application>
-        <activity android:name="android.test.app.TestActivity" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-
-</manifest>
-
diff --git a/libnativeloader/test/test.cpp b/libnativeloader/test/test.cpp
deleted file mode 100644
index b166928..0000000
--- a/libnativeloader/test/test.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#define LOG_TAG "oemlib"
-#include <android-base/logging.h>
-
-static __attribute__((constructor)) void test_lib_init() {
-  LOG(DEBUG) << LIBNAME << " loaded";
-}
diff --git a/libnativeloader/test/vendor/AndroidManifest.xml b/libnativeloader/test/vendor/AndroidManifest.xml
deleted file mode 100644
index c4c1a9c..0000000
--- a/libnativeloader/test/vendor/AndroidManifest.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.test.app.vendor">
-
-    <application>
-        <activity android:name="android.test.app.TestActivity" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-
-</manifest>
-
diff --git a/libstats/statsd_writer.c b/libstats/statsd_writer.c
index b1c05ea..073b67f 100644
--- a/libstats/statsd_writer.c
+++ b/libstats/statsd_writer.c
@@ -36,25 +36,6 @@
 #include <time.h>
 #include <unistd.h>
 
-/* branchless on many architectures. */
-#define min(x, y) ((y) ^ (((x) ^ (y)) & -((x) < (y))))
-
-#ifndef htole32
-#if __BYTE_ORDER == __LITTLE_ENDIAN
-#define htole32(x) (x)
-#else
-#define htole32(x) __bswap_32(x)
-#endif
-#endif
-
-#ifndef htole64
-#if __BYTE_ORDER == __LITTLE_ENDIAN
-#define htole64(x) (x)
-#else
-#define htole64(x) __bswap_64(x)
-#endif
-#endif
-
 static pthread_mutex_t log_init_lock = PTHREAD_MUTEX_INITIALIZER;
 static atomic_int dropped = 0;
 static atomic_int log_error = 0;
@@ -221,14 +202,14 @@
             android_log_event_long_t buffer;
             header.id = LOG_ID_STATS;
             // store the last log error in the tag field. This tag field is not used by statsd.
-            buffer.header.tag = htole32(atomic_load(&log_error));
+            buffer.header.tag = atomic_load(&log_error);
             buffer.payload.type = EVENT_TYPE_LONG;
             // format:
             // |atom_tag|dropped_count|
             int64_t composed_long = atomic_load(&atom_tag);
             // Send 2 int32's via an int64.
             composed_long = ((composed_long << 32) | ((int64_t)snapshot));
-            buffer.payload.data = htole64(composed_long);
+            buffer.payload.data = composed_long;
 
             newVec[headerLength].iov_base = &buffer;
             newVec[headerLength].iov_len = sizeof(buffer);
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index 8d2299f..b0f3786 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -245,6 +245,7 @@
         "tests/files/offline/jit_debug_x86/*",
         "tests/files/offline/jit_map_arm/*",
         "tests/files/offline/gnu_debugdata_arm/*",
+        "tests/files/offline/load_bias_different_section_bias_arm64/*",
         "tests/files/offline/load_bias_ro_rx_x86_64/*",
         "tests/files/offline/offset_arm/*",
         "tests/files/offline/shared_lib_in_apk_arm64/*",
diff --git a/libunwindstack/DexFile.cpp b/libunwindstack/DexFile.cpp
index eaf867f..dff7a8b 100644
--- a/libunwindstack/DexFile.cpp
+++ b/libunwindstack/DexFile.cpp
@@ -22,6 +22,9 @@
 
 #include <memory>
 
+#define LOG_TAG "unwind"
+#include <log/log.h>
+
 #include <android-base/unique_fd.h>
 #include <art_api/dex_file_support.h>
 
@@ -32,6 +35,19 @@
 
 namespace unwindstack {
 
+static bool CheckDexSupport() {
+  if (std::string err_msg; !art_api::dex::TryLoadLibdexfileExternal(&err_msg)) {
+    ALOGW("Failed to initialize DEX file support: %s", err_msg.c_str());
+    return false;
+  }
+  return true;
+}
+
+static bool HasDexSupport() {
+  static bool has_dex_support = CheckDexSupport();
+  return has_dex_support;
+}
+
 std::unique_ptr<DexFile> DexFile::Create(uint64_t dex_file_offset_in_memory, Memory* memory,
                                          MapInfo* info) {
   if (!info->name.empty()) {
@@ -57,6 +73,10 @@
 
 std::unique_ptr<DexFileFromFile> DexFileFromFile::Create(uint64_t dex_file_offset_in_file,
                                                          const std::string& file) {
+  if (UNLIKELY(!HasDexSupport())) {
+    return nullptr;
+  }
+
   android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC)));
   if (fd == -1) {
     return nullptr;
@@ -75,6 +95,10 @@
 std::unique_ptr<DexFileFromMemory> DexFileFromMemory::Create(uint64_t dex_file_offset_in_memory,
                                                              Memory* memory,
                                                              const std::string& name) {
+  if (UNLIKELY(!HasDexSupport())) {
+    return nullptr;
+  }
+
   std::vector<uint8_t> backing_memory;
 
   for (size_t size = 0;;) {
diff --git a/libunwindstack/DwarfEhFrameWithHdr.cpp b/libunwindstack/DwarfEhFrameWithHdr.cpp
index 802beca..24b94f0 100644
--- a/libunwindstack/DwarfEhFrameWithHdr.cpp
+++ b/libunwindstack/DwarfEhFrameWithHdr.cpp
@@ -32,8 +32,8 @@
 }
 
 template <typename AddressType>
-bool DwarfEhFrameWithHdr<AddressType>::Init(uint64_t offset, uint64_t size, uint64_t load_bias) {
-  load_bias_ = load_bias;
+bool DwarfEhFrameWithHdr<AddressType>::Init(uint64_t offset, uint64_t size, int64_t section_bias) {
+  section_bias_ = section_bias;
 
   memory_.clear_func_offset();
   memory_.clear_text_offset();
@@ -138,7 +138,7 @@
 
   // Relative encodings require adding in the load bias.
   if (IsEncodingRelative(table_encoding_)) {
-    value += load_bias_;
+    value += section_bias_;
   }
   info->pc = value;
   return info;
diff --git a/libunwindstack/DwarfEhFrameWithHdr.h b/libunwindstack/DwarfEhFrameWithHdr.h
index 0e5eef7..b8dd3dd 100644
--- a/libunwindstack/DwarfEhFrameWithHdr.h
+++ b/libunwindstack/DwarfEhFrameWithHdr.h
@@ -38,7 +38,7 @@
   using DwarfSectionImpl<AddressType>::entries_offset_;
   using DwarfSectionImpl<AddressType>::entries_end_;
   using DwarfSectionImpl<AddressType>::last_error_;
-  using DwarfSectionImpl<AddressType>::load_bias_;
+  using DwarfSectionImpl<AddressType>::section_bias_;
 
   struct FdeInfo {
     AddressType pc;
@@ -61,7 +61,7 @@
     return pc + this->memory_.cur_offset() - 4;
   }
 
-  bool Init(uint64_t offset, uint64_t size, uint64_t load_bias) override;
+  bool Init(uint64_t offset, uint64_t size, int64_t section_bias) override;
 
   const DwarfFde* GetFdeFromPc(uint64_t pc) override;
 
diff --git a/libunwindstack/DwarfMemory.cpp b/libunwindstack/DwarfMemory.cpp
index b505900..2e388c6 100644
--- a/libunwindstack/DwarfMemory.cpp
+++ b/libunwindstack/DwarfMemory.cpp
@@ -111,7 +111,7 @@
       // Nothing to do.
       break;
     case DW_EH_PE_pcrel:
-      if (pc_offset_ == static_cast<uint64_t>(-1)) {
+      if (pc_offset_ == INT64_MAX) {
         // Unsupported encoding.
         return false;
       }
diff --git a/libunwindstack/DwarfSection.cpp b/libunwindstack/DwarfSection.cpp
index 849a31a..cdb6141 100644
--- a/libunwindstack/DwarfSection.cpp
+++ b/libunwindstack/DwarfSection.cpp
@@ -333,7 +333,7 @@
   memory_.set_cur_offset(cur_offset);
 
   // The load bias only applies to the start.
-  memory_.set_pc_offset(load_bias_);
+  memory_.set_pc_offset(section_bias_);
   bool valid = memory_.ReadEncodedValue<AddressType>(cie->fde_address_encoding, &fde->pc_start);
   fde->pc_start = AdjustPcFromFde(fde->pc_start);
 
@@ -591,8 +591,9 @@
 }
 
 template <typename AddressType>
-bool DwarfSectionImplNoHdr<AddressType>::Init(uint64_t offset, uint64_t size, uint64_t load_bias) {
-  load_bias_ = load_bias;
+bool DwarfSectionImplNoHdr<AddressType>::Init(uint64_t offset, uint64_t size,
+                                              int64_t section_bias) {
+  section_bias_ = section_bias;
   entries_offset_ = offset;
   next_entries_offset_ = offset;
   entries_end_ = offset + size;
diff --git a/libunwindstack/Elf.cpp b/libunwindstack/Elf.cpp
index 3454913..c141b2e 100644
--- a/libunwindstack/Elf.cpp
+++ b/libunwindstack/Elf.cpp
@@ -53,7 +53,7 @@
 
   valid_ = interface_->Init(&load_bias_);
   if (valid_) {
-    interface_->InitHeaders(load_bias_);
+    interface_->InitHeaders();
     InitGnuDebugdata();
   } else {
     interface_.reset(nullptr);
@@ -77,9 +77,9 @@
 
   // Ignore the load_bias from the compressed section, the correct load bias
   // is in the uncompressed data.
-  uint64_t load_bias;
+  int64_t load_bias;
   if (gnu->Init(&load_bias)) {
-    gnu->InitHeaders(load_bias);
+    gnu->InitHeaders();
     interface_->SetGnuDebugdataInterface(gnu);
   } else {
     // Free all of the memory associated with the gnu_debugdata section.
@@ -124,7 +124,7 @@
   }
 
   // Adjust by the load bias.
-  if (*memory_address < load_bias_) {
+  if (load_bias_ > 0 && *memory_address < static_cast<uint64_t>(load_bias_)) {
     return false;
   }
 
@@ -229,7 +229,7 @@
 }
 
 bool Elf::IsValidPc(uint64_t pc) {
-  if (!valid_ || pc < load_bias_) {
+  if (!valid_ || (load_bias_ > 0 && pc < static_cast<uint64_t>(load_bias_))) {
     return false;
   }
 
@@ -299,7 +299,7 @@
   return interface.release();
 }
 
-uint64_t Elf::GetLoadBias(Memory* memory) {
+int64_t Elf::GetLoadBias(Memory* memory) {
   if (!IsValidElf(memory)) {
     return 0;
   }
diff --git a/libunwindstack/ElfInterface.cpp b/libunwindstack/ElfInterface.cpp
index bdfee01..e34273c 100644
--- a/libunwindstack/ElfInterface.cpp
+++ b/libunwindstack/ElfInterface.cpp
@@ -124,10 +124,10 @@
 }
 
 template <typename AddressType>
-void ElfInterface::InitHeadersWithTemplate(uint64_t load_bias) {
+void ElfInterface::InitHeadersWithTemplate() {
   if (eh_frame_hdr_offset_ != 0) {
     eh_frame_.reset(new DwarfEhFrameWithHdr<AddressType>(memory_));
-    if (!eh_frame_->Init(eh_frame_hdr_offset_, eh_frame_hdr_size_, load_bias)) {
+    if (!eh_frame_->Init(eh_frame_hdr_offset_, eh_frame_hdr_size_, eh_frame_hdr_section_bias_)) {
       eh_frame_.reset(nullptr);
     }
   }
@@ -136,21 +136,23 @@
     // If there is an eh_frame section without an eh_frame_hdr section,
     // or using the frame hdr object failed to init.
     eh_frame_.reset(new DwarfEhFrame<AddressType>(memory_));
-    if (!eh_frame_->Init(eh_frame_offset_, eh_frame_size_, load_bias)) {
+    if (!eh_frame_->Init(eh_frame_offset_, eh_frame_size_, eh_frame_section_bias_)) {
       eh_frame_.reset(nullptr);
     }
   }
 
   if (eh_frame_.get() == nullptr) {
     eh_frame_hdr_offset_ = 0;
+    eh_frame_hdr_section_bias_ = 0;
     eh_frame_hdr_size_ = static_cast<uint64_t>(-1);
     eh_frame_offset_ = 0;
+    eh_frame_section_bias_ = 0;
     eh_frame_size_ = static_cast<uint64_t>(-1);
   }
 
   if (debug_frame_offset_ != 0) {
     debug_frame_.reset(new DwarfDebugFrame<AddressType>(memory_));
-    if (!debug_frame_->Init(debug_frame_offset_, debug_frame_size_, load_bias)) {
+    if (!debug_frame_->Init(debug_frame_offset_, debug_frame_size_, debug_frame_section_bias_)) {
       debug_frame_.reset(nullptr);
       debug_frame_offset_ = 0;
       debug_frame_size_ = static_cast<uint64_t>(-1);
@@ -159,7 +161,7 @@
 }
 
 template <typename EhdrType, typename PhdrType, typename ShdrType>
-bool ElfInterface::ReadAllHeaders(uint64_t* load_bias) {
+bool ElfInterface::ReadAllHeaders(int64_t* load_bias) {
   EhdrType ehdr;
   if (!memory_->ReadFully(0, &ehdr, sizeof(ehdr))) {
     last_error_.code = ERROR_MEMORY_INVALID;
@@ -175,7 +177,7 @@
 }
 
 template <typename EhdrType, typename PhdrType>
-uint64_t ElfInterface::GetLoadBias(Memory* memory) {
+int64_t ElfInterface::GetLoadBias(Memory* memory) {
   EhdrType ehdr;
   if (!memory->ReadFully(0, &ehdr, sizeof(ehdr))) {
     return false;
@@ -187,15 +189,17 @@
     if (!memory->ReadFully(offset, &phdr, sizeof(phdr))) {
       return 0;
     }
-    if (phdr.p_type == PT_LOAD && phdr.p_offset == 0) {
-      return phdr.p_vaddr;
+
+    // Find the first executable load when looking for the load bias.
+    if (phdr.p_type == PT_LOAD && (phdr.p_flags & PF_X)) {
+      return static_cast<uint64_t>(phdr.p_vaddr) - phdr.p_offset;
     }
   }
   return 0;
 }
 
 template <typename EhdrType, typename PhdrType>
-void ElfInterface::ReadProgramHeaders(const EhdrType& ehdr, uint64_t* load_bias) {
+void ElfInterface::ReadProgramHeaders(const EhdrType& ehdr, int64_t* load_bias) {
   uint64_t offset = ehdr.e_phoff;
   bool first_exec_load_header = true;
   for (size_t i = 0; i < ehdr.e_phnum; i++, offset += ehdr.e_phentsize) {
@@ -214,8 +218,8 @@
       pt_loads_[phdr.p_offset] = LoadInfo{phdr.p_offset, phdr.p_vaddr,
                                           static_cast<size_t>(phdr.p_memsz)};
       // Only set the load bias from the first executable load header.
-      if (first_exec_load_header && phdr.p_vaddr > phdr.p_offset) {
-        *load_bias = phdr.p_vaddr - phdr.p_offset;
+      if (first_exec_load_header) {
+        *load_bias = static_cast<uint64_t>(phdr.p_vaddr) - phdr.p_offset;
       }
       first_exec_load_header = false;
       break;
@@ -224,6 +228,7 @@
     case PT_GNU_EH_FRAME:
       // This is really the pointer to the .eh_frame_hdr section.
       eh_frame_hdr_offset_ = phdr.p_offset;
+      eh_frame_hdr_section_bias_ = static_cast<uint64_t>(phdr.p_paddr) - phdr.p_offset;
       eh_frame_hdr_size_ = phdr.p_memsz;
       break;
 
@@ -338,24 +343,21 @@
       if (shdr.sh_name < sec_size) {
         std::string name;
         if (memory_->ReadString(sec_offset + shdr.sh_name, &name)) {
-          uint64_t* offset_ptr = nullptr;
-          uint64_t* size_ptr = nullptr;
           if (name == ".debug_frame") {
-            offset_ptr = &debug_frame_offset_;
-            size_ptr = &debug_frame_size_;
+            debug_frame_offset_ = shdr.sh_offset;
+            debug_frame_size_ = shdr.sh_size;
+            debug_frame_section_bias_ = static_cast<uint64_t>(shdr.sh_addr) - shdr.sh_offset;
           } else if (name == ".gnu_debugdata") {
-            offset_ptr = &gnu_debugdata_offset_;
-            size_ptr = &gnu_debugdata_size_;
+            gnu_debugdata_offset_ = shdr.sh_offset;
+            gnu_debugdata_size_ = shdr.sh_size;
           } else if (name == ".eh_frame") {
-            offset_ptr = &eh_frame_offset_;
-            size_ptr = &eh_frame_size_;
+            eh_frame_offset_ = shdr.sh_offset;
+            eh_frame_section_bias_ = static_cast<uint64_t>(shdr.sh_addr) - shdr.sh_offset;
+            eh_frame_size_ = shdr.sh_size;
           } else if (eh_frame_hdr_offset_ == 0 && name == ".eh_frame_hdr") {
-            offset_ptr = &eh_frame_hdr_offset_;
-            size_ptr = &eh_frame_hdr_size_;
-          }
-          if (offset_ptr != nullptr) {
-            *offset_ptr = shdr.sh_offset;
-            *size_ptr = shdr.sh_size;
+            eh_frame_hdr_offset_ = shdr.sh_offset;
+            eh_frame_hdr_section_bias_ = static_cast<uint64_t>(shdr.sh_addr) - shdr.sh_offset;
+            eh_frame_hdr_size_ = shdr.sh_size;
           }
         }
       }
@@ -637,16 +639,14 @@
 }
 
 // Instantiate all of the needed template functions.
-template void ElfInterface::InitHeadersWithTemplate<uint32_t>(uint64_t);
-template void ElfInterface::InitHeadersWithTemplate<uint64_t>(uint64_t);
+template void ElfInterface::InitHeadersWithTemplate<uint32_t>();
+template void ElfInterface::InitHeadersWithTemplate<uint64_t>();
 
-template bool ElfInterface::ReadAllHeaders<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>(uint64_t*);
-template bool ElfInterface::ReadAllHeaders<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr>(uint64_t*);
+template bool ElfInterface::ReadAllHeaders<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>(int64_t*);
+template bool ElfInterface::ReadAllHeaders<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr>(int64_t*);
 
-template void ElfInterface::ReadProgramHeaders<Elf32_Ehdr, Elf32_Phdr>(const Elf32_Ehdr&,
-                                                                       uint64_t*);
-template void ElfInterface::ReadProgramHeaders<Elf64_Ehdr, Elf64_Phdr>(const Elf64_Ehdr&,
-                                                                       uint64_t*);
+template void ElfInterface::ReadProgramHeaders<Elf32_Ehdr, Elf32_Phdr>(const Elf32_Ehdr&, int64_t*);
+template void ElfInterface::ReadProgramHeaders<Elf64_Ehdr, Elf64_Phdr>(const Elf64_Ehdr&, int64_t*);
 
 template void ElfInterface::ReadSectionHeaders<Elf32_Ehdr, Elf32_Shdr>(const Elf32_Ehdr&);
 template void ElfInterface::ReadSectionHeaders<Elf64_Ehdr, Elf64_Shdr>(const Elf64_Ehdr&);
@@ -668,8 +668,8 @@
 template void ElfInterface::GetMaxSizeWithTemplate<Elf32_Ehdr>(Memory*, uint64_t*);
 template void ElfInterface::GetMaxSizeWithTemplate<Elf64_Ehdr>(Memory*, uint64_t*);
 
-template uint64_t ElfInterface::GetLoadBias<Elf32_Ehdr, Elf32_Phdr>(Memory*);
-template uint64_t ElfInterface::GetLoadBias<Elf64_Ehdr, Elf64_Phdr>(Memory*);
+template int64_t ElfInterface::GetLoadBias<Elf32_Ehdr, Elf32_Phdr>(Memory*);
+template int64_t ElfInterface::GetLoadBias<Elf64_Ehdr, Elf64_Phdr>(Memory*);
 
 template std::string ElfInterface::ReadBuildIDFromMemory<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr>(
     Memory*);
diff --git a/libunwindstack/ElfInterfaceArm.cpp b/libunwindstack/ElfInterfaceArm.cpp
index 3dd5d54..76f2dc8 100644
--- a/libunwindstack/ElfInterfaceArm.cpp
+++ b/libunwindstack/ElfInterfaceArm.cpp
@@ -26,7 +26,7 @@
 
 namespace unwindstack {
 
-bool ElfInterfaceArm::Init(uint64_t* load_bias) {
+bool ElfInterfaceArm::Init(int64_t* load_bias) {
   if (!ElfInterface32::Init(load_bias)) {
     return false;
   }
diff --git a/libunwindstack/ElfInterfaceArm.h b/libunwindstack/ElfInterfaceArm.h
index 4c3a0c3..1d71cac 100644
--- a/libunwindstack/ElfInterfaceArm.h
+++ b/libunwindstack/ElfInterfaceArm.h
@@ -64,7 +64,7 @@
   iterator begin() { return iterator(this, 0); }
   iterator end() { return iterator(this, total_entries_); }
 
-  bool Init(uint64_t* load_bias) override;
+  bool Init(int64_t* section_bias) override;
 
   bool GetPrel31Addr(uint32_t offset, uint32_t* addr);
 
diff --git a/libunwindstack/MapInfo.cpp b/libunwindstack/MapInfo.cpp
index 5b30a4d..f2dad84 100644
--- a/libunwindstack/MapInfo.cpp
+++ b/libunwindstack/MapInfo.cpp
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <stdint.h>
 #include <sys/mman.h>
 #include <sys/types.h>
 #include <unistd.h>
@@ -263,8 +264,8 @@
 }
 
 uint64_t MapInfo::GetLoadBias(const std::shared_ptr<Memory>& process_memory) {
-  uint64_t cur_load_bias = load_bias.load();
-  if (cur_load_bias != static_cast<uint64_t>(-1)) {
+  int64_t cur_load_bias = load_bias.load();
+  if (cur_load_bias != INT64_MAX) {
     return cur_load_bias;
   }
 
diff --git a/libunwindstack/include/unwindstack/DwarfMemory.h b/libunwindstack/include/unwindstack/DwarfMemory.h
index 8dd8d2b..c45699a 100644
--- a/libunwindstack/include/unwindstack/DwarfMemory.h
+++ b/libunwindstack/include/unwindstack/DwarfMemory.h
@@ -49,8 +49,8 @@
   uint64_t cur_offset() { return cur_offset_; }
   void set_cur_offset(uint64_t cur_offset) { cur_offset_ = cur_offset; }
 
-  void set_pc_offset(uint64_t offset) { pc_offset_ = offset; }
-  void clear_pc_offset() { pc_offset_ = static_cast<uint64_t>(-1); }
+  void set_pc_offset(int64_t offset) { pc_offset_ = offset; }
+  void clear_pc_offset() { pc_offset_ = INT64_MAX; }
 
   void set_data_offset(uint64_t offset) { data_offset_ = offset; }
   void clear_data_offset() { data_offset_ = static_cast<uint64_t>(-1); }
@@ -65,7 +65,7 @@
   Memory* memory_;
   uint64_t cur_offset_ = 0;
 
-  uint64_t pc_offset_ = static_cast<uint64_t>(-1);
+  int64_t pc_offset_ = INT64_MAX;
   uint64_t data_offset_ = static_cast<uint64_t>(-1);
   uint64_t func_offset_ = static_cast<uint64_t>(-1);
   uint64_t text_offset_ = static_cast<uint64_t>(-1);
diff --git a/libunwindstack/include/unwindstack/DwarfSection.h b/libunwindstack/include/unwindstack/DwarfSection.h
index e9942de..0b3f6d4 100644
--- a/libunwindstack/include/unwindstack/DwarfSection.h
+++ b/libunwindstack/include/unwindstack/DwarfSection.h
@@ -86,7 +86,7 @@
   DwarfErrorCode LastErrorCode() { return last_error_.code; }
   uint64_t LastErrorAddress() { return last_error_.address; }
 
-  virtual bool Init(uint64_t offset, uint64_t size, uint64_t load_bias) = 0;
+  virtual bool Init(uint64_t offset, uint64_t size, int64_t section_bias) = 0;
 
   virtual bool Eval(const DwarfCie*, Memory*, const dwarf_loc_regs_t&, Regs*, bool*) = 0;
 
@@ -150,7 +150,7 @@
   bool EvalExpression(const DwarfLocation& loc, Memory* regular_memory, AddressType* value,
                       RegsInfo<AddressType>* regs_info, bool* is_dex_pc);
 
-  uint64_t load_bias_ = 0;
+  int64_t section_bias_ = 0;
   uint64_t entries_offset_ = 0;
   uint64_t entries_end_ = 0;
   uint64_t pc_offset_ = 0;
@@ -166,7 +166,7 @@
   using DwarfSectionImpl<AddressType>::entries_offset_;
   using DwarfSectionImpl<AddressType>::entries_end_;
   using DwarfSectionImpl<AddressType>::last_error_;
-  using DwarfSectionImpl<AddressType>::load_bias_;
+  using DwarfSectionImpl<AddressType>::section_bias_;
   using DwarfSectionImpl<AddressType>::cie_entries_;
   using DwarfSectionImpl<AddressType>::fde_entries_;
   using DwarfSectionImpl<AddressType>::cie32_value_;
@@ -175,7 +175,7 @@
   DwarfSectionImplNoHdr(Memory* memory) : DwarfSectionImpl<AddressType>(memory) {}
   virtual ~DwarfSectionImplNoHdr() = default;
 
-  bool Init(uint64_t offset, uint64_t size, uint64_t load_bias) override;
+  bool Init(uint64_t offset, uint64_t size, int64_t section_bias) override;
 
   const DwarfFde* GetFdeFromPc(uint64_t pc) override;
 
diff --git a/libunwindstack/include/unwindstack/Elf.h b/libunwindstack/include/unwindstack/Elf.h
index 56bf318..fc3f2a6 100644
--- a/libunwindstack/include/unwindstack/Elf.h
+++ b/libunwindstack/include/unwindstack/Elf.h
@@ -75,7 +75,7 @@
 
   std::string GetBuildID();
 
-  uint64_t GetLoadBias() { return load_bias_; }
+  int64_t GetLoadBias() { return load_bias_; }
 
   bool IsValidPc(uint64_t pc);
 
@@ -101,7 +101,7 @@
 
   static bool GetInfo(Memory* memory, uint64_t* size);
 
-  static uint64_t GetLoadBias(Memory* memory);
+  static int64_t GetLoadBias(Memory* memory);
 
   static std::string GetBuildID(Memory* memory);
 
@@ -116,7 +116,7 @@
 
  protected:
   bool valid_ = false;
-  uint64_t load_bias_ = 0;
+  int64_t load_bias_ = 0;
   std::unique_ptr<ElfInterface> interface_;
   std::unique_ptr<Memory> memory_;
   uint32_t machine_type_;
diff --git a/libunwindstack/include/unwindstack/ElfInterface.h b/libunwindstack/include/unwindstack/ElfInterface.h
index dbd917d..ae9bd9a 100644
--- a/libunwindstack/include/unwindstack/ElfInterface.h
+++ b/libunwindstack/include/unwindstack/ElfInterface.h
@@ -52,9 +52,9 @@
   ElfInterface(Memory* memory) : memory_(memory) {}
   virtual ~ElfInterface();
 
-  virtual bool Init(uint64_t* load_bias) = 0;
+  virtual bool Init(int64_t* load_bias) = 0;
 
-  virtual void InitHeaders(uint64_t load_bias) = 0;
+  virtual void InitHeaders() = 0;
 
   virtual std::string GetSoname() = 0;
 
@@ -80,10 +80,13 @@
   uint64_t dynamic_vaddr() { return dynamic_vaddr_; }
   uint64_t dynamic_size() { return dynamic_size_; }
   uint64_t eh_frame_hdr_offset() { return eh_frame_hdr_offset_; }
+  int64_t eh_frame_hdr_section_bias() { return eh_frame_hdr_section_bias_; }
   uint64_t eh_frame_hdr_size() { return eh_frame_hdr_size_; }
   uint64_t eh_frame_offset() { return eh_frame_offset_; }
+  int64_t eh_frame_section_bias() { return eh_frame_section_bias_; }
   uint64_t eh_frame_size() { return eh_frame_size_; }
   uint64_t debug_frame_offset() { return debug_frame_offset_; }
+  int64_t debug_frame_section_bias() { return debug_frame_section_bias_; }
   uint64_t debug_frame_size() { return debug_frame_size_; }
   uint64_t gnu_debugdata_offset() { return gnu_debugdata_offset_; }
   uint64_t gnu_debugdata_size() { return gnu_debugdata_size_; }
@@ -98,20 +101,20 @@
   uint64_t LastErrorAddress() { return last_error_.address; }
 
   template <typename EhdrType, typename PhdrType>
-  static uint64_t GetLoadBias(Memory* memory);
+  static int64_t GetLoadBias(Memory* memory);
 
   template <typename EhdrType, typename ShdrType, typename NhdrType>
   static std::string ReadBuildIDFromMemory(Memory* memory);
 
  protected:
   template <typename AddressType>
-  void InitHeadersWithTemplate(uint64_t load_bias);
+  void InitHeadersWithTemplate();
 
   template <typename EhdrType, typename PhdrType, typename ShdrType>
-  bool ReadAllHeaders(uint64_t* load_bias);
+  bool ReadAllHeaders(int64_t* load_bias);
 
   template <typename EhdrType, typename PhdrType>
-  void ReadProgramHeaders(const EhdrType& ehdr, uint64_t* load_bias);
+  void ReadProgramHeaders(const EhdrType& ehdr, int64_t* load_bias);
 
   template <typename EhdrType, typename ShdrType>
   void ReadSectionHeaders(const EhdrType& ehdr);
@@ -142,12 +145,15 @@
   uint64_t dynamic_size_ = 0;
 
   uint64_t eh_frame_hdr_offset_ = 0;
+  int64_t eh_frame_hdr_section_bias_ = 0;
   uint64_t eh_frame_hdr_size_ = 0;
 
   uint64_t eh_frame_offset_ = 0;
+  int64_t eh_frame_section_bias_ = 0;
   uint64_t eh_frame_size_ = 0;
 
   uint64_t debug_frame_offset_ = 0;
+  int64_t debug_frame_section_bias_ = 0;
   uint64_t debug_frame_size_ = 0;
 
   uint64_t gnu_debugdata_offset_ = 0;
@@ -175,13 +181,11 @@
   ElfInterface32(Memory* memory) : ElfInterface(memory) {}
   virtual ~ElfInterface32() = default;
 
-  bool Init(uint64_t* load_bias) override {
+  bool Init(int64_t* load_bias) override {
     return ElfInterface::ReadAllHeaders<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>(load_bias);
   }
 
-  void InitHeaders(uint64_t load_bias) override {
-    ElfInterface::InitHeadersWithTemplate<uint32_t>(load_bias);
-  }
+  void InitHeaders() override { ElfInterface::InitHeadersWithTemplate<uint32_t>(); }
 
   std::string GetSoname() override { return ElfInterface::GetSonameWithTemplate<Elf32_Dyn>(); }
 
@@ -205,13 +209,11 @@
   ElfInterface64(Memory* memory) : ElfInterface(memory) {}
   virtual ~ElfInterface64() = default;
 
-  bool Init(uint64_t* load_bias) override {
+  bool Init(int64_t* load_bias) override {
     return ElfInterface::ReadAllHeaders<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr>(load_bias);
   }
 
-  void InitHeaders(uint64_t load_bias) override {
-    ElfInterface::InitHeadersWithTemplate<uint64_t>(load_bias);
-  }
+  void InitHeaders() override { ElfInterface::InitHeadersWithTemplate<uint64_t>(); }
 
   std::string GetSoname() override { return ElfInterface::GetSonameWithTemplate<Elf64_Dyn>(); }
 
diff --git a/libunwindstack/include/unwindstack/MapInfo.h b/libunwindstack/include/unwindstack/MapInfo.h
index 6c5cfc4..8f0c516 100644
--- a/libunwindstack/include/unwindstack/MapInfo.h
+++ b/libunwindstack/include/unwindstack/MapInfo.h
@@ -39,7 +39,7 @@
         flags(flags),
         name(name),
         prev_map(map_info),
-        load_bias(static_cast<uint64_t>(-1)),
+        load_bias(INT64_MAX),
         build_id(0) {}
   MapInfo(MapInfo* map_info, uint64_t start, uint64_t end, uint64_t offset, uint64_t flags,
           const std::string& name)
@@ -49,7 +49,7 @@
         flags(flags),
         name(name),
         prev_map(map_info),
-        load_bias(static_cast<uint64_t>(-1)),
+        load_bias(INT64_MAX),
         build_id(0) {}
   ~MapInfo();
 
@@ -72,7 +72,7 @@
 
   MapInfo* prev_map = nullptr;
 
-  std::atomic_uint64_t load_bias;
+  std::atomic_int64_t load_bias;
 
   // This is a pointer to a new'd std::string.
   // Using an atomic value means that we don't need to lock and will
diff --git a/libunwindstack/tests/DwarfSectionImplTest.cpp b/libunwindstack/tests/DwarfSectionImplTest.cpp
index b386ef4..a9d6dad 100644
--- a/libunwindstack/tests/DwarfSectionImplTest.cpp
+++ b/libunwindstack/tests/DwarfSectionImplTest.cpp
@@ -35,7 +35,7 @@
   TestDwarfSectionImpl(Memory* memory) : DwarfSectionImpl<TypeParam>(memory) {}
   virtual ~TestDwarfSectionImpl() = default;
 
-  bool Init(uint64_t, uint64_t, uint64_t) override { return false; }
+  bool Init(uint64_t, uint64_t, int64_t) override { return false; }
 
   void GetFdes(std::vector<const DwarfFde*>*) override {}
 
diff --git a/libunwindstack/tests/DwarfSectionTest.cpp b/libunwindstack/tests/DwarfSectionTest.cpp
index d754fcc..953dc75 100644
--- a/libunwindstack/tests/DwarfSectionTest.cpp
+++ b/libunwindstack/tests/DwarfSectionTest.cpp
@@ -30,23 +30,24 @@
   MockDwarfSection(Memory* memory) : DwarfSection(memory) {}
   virtual ~MockDwarfSection() = default;
 
-  MOCK_METHOD3(Init, bool(uint64_t, uint64_t, uint64_t));
+  MOCK_METHOD(bool, Init, (uint64_t, uint64_t, int64_t), (override));
 
-  MOCK_METHOD5(Eval, bool(const DwarfCie*, Memory*, const dwarf_loc_regs_t&, Regs*, bool*));
+  MOCK_METHOD(bool, Eval, (const DwarfCie*, Memory*, const dwarf_loc_regs_t&, Regs*, bool*),
+              (override));
 
-  MOCK_METHOD3(Log, bool(uint8_t, uint64_t, const DwarfFde*));
+  MOCK_METHOD(bool, Log, (uint8_t, uint64_t, const DwarfFde*), (override));
 
-  MOCK_METHOD1(GetFdes, void(std::vector<const DwarfFde*>*));
+  MOCK_METHOD(void, GetFdes, (std::vector<const DwarfFde*>*), (override));
 
-  MOCK_METHOD1(GetFdeFromPc, const DwarfFde*(uint64_t));
+  MOCK_METHOD(const DwarfFde*, GetFdeFromPc, (uint64_t), (override));
 
-  MOCK_METHOD3(GetCfaLocationInfo, bool(uint64_t, const DwarfFde*, dwarf_loc_regs_t*));
+  MOCK_METHOD(bool, GetCfaLocationInfo, (uint64_t, const DwarfFde*, dwarf_loc_regs_t*), (override));
 
-  MOCK_METHOD1(GetCieOffsetFromFde32, uint64_t(uint32_t));
+  MOCK_METHOD(uint64_t, GetCieOffsetFromFde32, (uint32_t), (override));
 
-  MOCK_METHOD1(GetCieOffsetFromFde64, uint64_t(uint64_t));
+  MOCK_METHOD(uint64_t, GetCieOffsetFromFde64, (uint64_t), (override));
 
-  MOCK_METHOD1(AdjustPcFromFde, uint64_t(uint64_t));
+  MOCK_METHOD(uint64_t, AdjustPcFromFde, (uint64_t), (override));
 };
 
 class DwarfSectionTest : public ::testing::Test {
diff --git a/libunwindstack/tests/ElfFake.h b/libunwindstack/tests/ElfFake.h
index bd3083c..832e64a 100644
--- a/libunwindstack/tests/ElfFake.h
+++ b/libunwindstack/tests/ElfFake.h
@@ -66,8 +66,8 @@
   ElfInterfaceFake(Memory* memory) : ElfInterface(memory) {}
   virtual ~ElfInterfaceFake() = default;
 
-  bool Init(uint64_t*) override { return false; }
-  void InitHeaders(uint64_t) override {}
+  bool Init(int64_t*) override { return false; }
+  void InitHeaders() override {}
   std::string GetSoname() override { return fake_soname_; }
 
   bool GetFunctionName(uint64_t, std::string*, uint64_t*) override;
diff --git a/libunwindstack/tests/ElfInterfaceTest.cpp b/libunwindstack/tests/ElfInterfaceTest.cpp
index f9ee9eb..b048b17 100644
--- a/libunwindstack/tests/ElfInterfaceTest.cpp
+++ b/libunwindstack/tests/ElfInterfaceTest.cpp
@@ -112,6 +112,21 @@
   template <typename Ehdr, typename Shdr, typename ElfInterfaceType>
   void InitSectionHeadersOffsets();
 
+  template <typename Ehdr, typename Shdr, typename ElfInterfaceType>
+  void InitSectionHeadersOffsetsEhFrameSectionBias(uint64_t addr, uint64_t offset,
+                                                   int64_t expected_bias);
+
+  template <typename Ehdr, typename Shdr, typename ElfInterfaceType>
+  void InitSectionHeadersOffsetsEhFrameHdrSectionBias(uint64_t addr, uint64_t offset,
+                                                      int64_t expected_bias);
+
+  template <typename Ehdr, typename Shdr, typename ElfInterfaceType>
+  void InitSectionHeadersOffsetsDebugFrameSectionBias(uint64_t addr, uint64_t offset,
+                                                      int64_t expected_bias);
+
+  template <typename Ehdr, typename Phdr, typename ElfInterfaceType>
+  void CheckGnuEhFrame(uint64_t addr, uint64_t offset, int64_t expected_bias);
+
   template <typename Sym>
   void InitSym(uint64_t offset, uint32_t value, uint32_t size, uint32_t name_offset,
                uint64_t sym_offset, const char* name);
@@ -131,6 +146,12 @@
   template <typename Ehdr, typename Shdr, typename Nhdr, typename ElfInterfaceType>
   void BuildIDSectionTooSmallForHeader();
 
+  template <typename Ehdr, typename Phdr, typename ElfInterfaceType>
+  void CheckLoadBiasInFirstPhdr(int64_t load_bias);
+
+  template <typename Ehdr, typename Phdr, typename ElfInterfaceType>
+  void CheckLoadBiasInFirstExecPhdr(uint64_t offset, uint64_t vaddr, int64_t load_bias);
+
   MemoryFake memory_;
 };
 
@@ -166,9 +187,9 @@
   phdr.p_align = 0x1000;
   memory_.SetMemory(0x100, &phdr, sizeof(phdr));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0x2000U, load_bias);
+  EXPECT_EQ(0x2000, load_bias);
 
   const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
   ASSERT_EQ(1U, pt_loads.size());
@@ -178,11 +199,11 @@
   ASSERT_EQ(0x10000U, load_data.table_size);
 }
 
-TEST_F(ElfInterfaceTest, elf32_single_pt_load) {
+TEST_F(ElfInterfaceTest, single_pt_load_32) {
   SinglePtLoad<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, elf64_single_pt_load) {
+TEST_F(ElfInterfaceTest, single_pt_load_64) {
   SinglePtLoad<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
 }
 
@@ -222,9 +243,9 @@
   phdr.p_align = 0x1002;
   memory_.SetMemory(0x100 + 2 * sizeof(phdr), &phdr, sizeof(phdr));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0x2000U, load_bias);
+  EXPECT_EQ(0x2000, load_bias);
 
   const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
   ASSERT_EQ(3U, pt_loads.size());
@@ -245,11 +266,11 @@
   ASSERT_EQ(0x10002U, load_data.table_size);
 }
 
-TEST_F(ElfInterfaceTest, elf32_multiple_executable_pt_loads) {
+TEST_F(ElfInterfaceTest, multiple_executable_pt_loads_32) {
   MultipleExecutablePtLoads<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, elf64_multiple_executable_pt_loads) {
+TEST_F(ElfInterfaceTest, multiple_executable_pt_loads_64) {
   MultipleExecutablePtLoads<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
 }
 
@@ -289,9 +310,9 @@
   phdr.p_align = 0x1002;
   memory_.SetMemory(0x100 + 2 * (sizeof(phdr) + 100), &phdr, sizeof(phdr));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0x2000U, load_bias);
+  EXPECT_EQ(0x2000, load_bias);
 
   const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
   ASSERT_EQ(3U, pt_loads.size());
@@ -312,12 +333,12 @@
   ASSERT_EQ(0x10002U, load_data.table_size);
 }
 
-TEST_F(ElfInterfaceTest, elf32_multiple_executable_pt_loads_increments_not_size_of_phdr) {
+TEST_F(ElfInterfaceTest, multiple_executable_pt_loads_increments_not_size_of_phdr_32) {
   MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn,
                                                    ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, elf64_multiple_executable_pt_loads_increments_not_size_of_phdr) {
+TEST_F(ElfInterfaceTest, multiple_executable_pt_loads_increments_not_size_of_phdr_64) {
   MultipleExecutablePtLoadsIncrementsNotSizeOfPhdr<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn,
                                                    ElfInterface64>();
 }
@@ -358,9 +379,9 @@
   phdr.p_align = 0x1002;
   memory_.SetMemory(0x100 + 2 * sizeof(phdr), &phdr, sizeof(phdr));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0x1001U, load_bias);
+  EXPECT_EQ(0x1001, load_bias);
 
   const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
   ASSERT_EQ(1U, pt_loads.size());
@@ -371,11 +392,11 @@
   ASSERT_EQ(0x10001U, load_data.table_size);
 }
 
-TEST_F(ElfInterfaceTest, elf32_non_executable_pt_loads) {
+TEST_F(ElfInterfaceTest, non_executable_pt_loads_32) {
   NonExecutablePtLoads<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, elf64_non_executable_pt_loads) {
+TEST_F(ElfInterfaceTest, non_executable_pt_loads_64) {
   NonExecutablePtLoads<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
 }
 
@@ -428,11 +449,10 @@
   memset(&phdr, 0, sizeof(phdr));
   phdr.p_type = PT_GNU_EH_FRAME;
   memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
-  phdr_offset += sizeof(phdr);
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0x2000U, load_bias);
+  EXPECT_EQ(0x2000, load_bias);
 
   const std::unordered_map<uint64_t, LoadInfo>& pt_loads = elf->pt_loads();
   ASSERT_EQ(1U, pt_loads.size());
@@ -443,15 +463,15 @@
   ASSERT_EQ(0x10000U, load_data.table_size);
 }
 
-TEST_F(ElfInterfaceTest, elf32_many_phdrs) {
+TEST_F(ElfInterfaceTest, many_phdrs_32) {
   ElfInterfaceTest::ManyPhdrs<Elf32_Ehdr, Elf32_Phdr, Elf32_Dyn, ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, elf64_many_phdrs) {
+TEST_F(ElfInterfaceTest, many_phdrs_64) {
   ElfInterfaceTest::ManyPhdrs<Elf64_Ehdr, Elf64_Phdr, Elf64_Dyn, ElfInterface64>();
 }
 
-TEST_F(ElfInterfaceTest, elf32_arm) {
+TEST_F(ElfInterfaceTest, arm32) {
   ElfInterfaceArm elf_arm(&memory_);
 
   Elf32_Ehdr ehdr = {};
@@ -470,9 +490,9 @@
   memory_.SetData32(0x2000, 0x1000);
   memory_.SetData32(0x2008, 0x1000);
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf_arm.Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
 
   std::vector<uint32_t> entries;
   for (auto addr : elf_arm) {
@@ -551,19 +571,19 @@
 void ElfInterfaceTest::Soname() {
   std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
 
   ASSERT_EQ("fake_soname.so", elf->GetSoname());
 }
 
-TEST_F(ElfInterfaceTest, elf32_soname) {
+TEST_F(ElfInterfaceTest, soname_32) {
   SonameInit<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr, Elf32_Dyn>();
   Soname<ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, elf64_soname) {
+TEST_F(ElfInterfaceTest, soname_64) {
   SonameInit<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, Elf64_Dyn>();
   Soname<ElfInterface64>();
 }
@@ -572,19 +592,19 @@
 void ElfInterfaceTest::SonameAfterDtNull() {
   std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
 
   ASSERT_EQ("", elf->GetSoname());
 }
 
-TEST_F(ElfInterfaceTest, elf32_soname_after_dt_null) {
+TEST_F(ElfInterfaceTest, soname_after_dt_null_32) {
   SonameInit<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr, Elf32_Dyn>(SONAME_DTNULL_AFTER);
   SonameAfterDtNull<ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, elf64_soname_after_dt_null) {
+TEST_F(ElfInterfaceTest, soname_after_dt_null_64) {
   SonameInit<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, Elf64_Dyn>(SONAME_DTNULL_AFTER);
   SonameAfterDtNull<ElfInterface64>();
 }
@@ -593,19 +613,19 @@
 void ElfInterfaceTest::SonameSize() {
   std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
 
   ASSERT_EQ("", elf->GetSoname());
 }
 
-TEST_F(ElfInterfaceTest, elf32_soname_size) {
+TEST_F(ElfInterfaceTest, soname_size_32) {
   SonameInit<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr, Elf32_Dyn>(SONAME_DTSIZE_SMALL);
   SonameSize<ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, elf64_soname_size) {
+TEST_F(ElfInterfaceTest, soname_size_64) {
   SonameInit<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, Elf64_Dyn>(SONAME_DTSIZE_SMALL);
   SonameSize<ElfInterface64>();
 }
@@ -616,19 +636,19 @@
 void ElfInterfaceTest::SonameMissingMap() {
   std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
 
   ASSERT_EQ("", elf->GetSoname());
 }
 
-TEST_F(ElfInterfaceTest, elf32_soname_missing_map) {
+TEST_F(ElfInterfaceTest, soname_missing_map_32) {
   SonameInit<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr, Elf32_Dyn>(SONAME_MISSING_MAP);
   SonameMissingMap<ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, elf64_soname_missing_map) {
+TEST_F(ElfInterfaceTest, soname_missing_map_64) {
   SonameInit<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, Elf64_Dyn>(SONAME_MISSING_MAP);
   SonameMissingMap<ElfInterface64>();
 }
@@ -647,17 +667,17 @@
   memory_.SetData32(0x10004, 0x500);
   memory_.SetData32(0x10008, 250);
 
-  elf.InitHeaders(0);
+  elf.InitHeaders();
 
   EXPECT_FALSE(elf.eh_frame() == nullptr);
   EXPECT_TRUE(elf.debug_frame() == nullptr);
 }
 
-TEST_F(ElfInterfaceTest, init_headers_eh_frame32) {
+TEST_F(ElfInterfaceTest, init_headers_eh_frame_32) {
   InitHeadersEhFrameTest<ElfInterface32Fake>();
 }
 
-TEST_F(ElfInterfaceTest, init_headers_eh_frame64) {
+TEST_F(ElfInterfaceTest, init_headers_eh_frame_64) {
   InitHeadersEhFrameTest<ElfInterface64Fake>();
 }
 
@@ -679,17 +699,17 @@
   memory_.SetData32(0x5108, 0x1500);
   memory_.SetData32(0x510c, 0x200);
 
-  elf.InitHeaders(0);
+  elf.InitHeaders();
 
   EXPECT_TRUE(elf.eh_frame() == nullptr);
   EXPECT_FALSE(elf.debug_frame() == nullptr);
 }
 
-TEST_F(ElfInterfaceTest, init_headers_debug_frame32) {
+TEST_F(ElfInterfaceTest, init_headers_debug_frame_32) {
   InitHeadersDebugFrame<ElfInterface32Fake>();
 }
 
-TEST_F(ElfInterfaceTest, init_headers_debug_frame64) {
+TEST_F(ElfInterfaceTest, init_headers_debug_frame_64) {
   InitHeadersDebugFrame<ElfInterface64Fake>();
 }
 
@@ -703,16 +723,16 @@
   ehdr.e_phentsize = sizeof(Phdr);
   memory_.SetMemory(0, &ehdr, sizeof(ehdr));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
 }
 
-TEST_F(ElfInterfaceTest, init_program_headers_malformed32) {
+TEST_F(ElfInterfaceTest, init_program_headers_malformed_32) {
   InitProgramHeadersMalformed<Elf32_Ehdr, Elf32_Phdr, ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, init_program_headers_malformed64) {
+TEST_F(ElfInterfaceTest, init_program_headers_malformed_64) {
   InitProgramHeadersMalformed<Elf64_Ehdr, Elf64_Phdr, ElfInterface64>();
 }
 
@@ -726,16 +746,16 @@
   ehdr.e_shentsize = sizeof(Shdr);
   memory_.SetMemory(0, &ehdr, sizeof(ehdr));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers_malformed32) {
+TEST_F(ElfInterfaceTest, init_section_headers_malformed_32) {
   InitSectionHeadersMalformed<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers_malformed64) {
+TEST_F(ElfInterfaceTest, init_section_headers_malformed_64) {
   InitSectionHeadersMalformed<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>();
 }
 
@@ -790,11 +810,10 @@
   shdr.sh_offset = 0xf000;
   shdr.sh_size = 0x1000;
   memory_.SetMemory(offset, &shdr, sizeof(shdr));
-  offset += ehdr.e_shentsize;
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
   EXPECT_EQ(0U, elf->debug_frame_offset());
   EXPECT_EQ(0U, elf->debug_frame_size());
   EXPECT_EQ(0U, elf->gnu_debugdata_offset());
@@ -805,11 +824,11 @@
   ASSERT_FALSE(elf->GetFunctionName(0x90010, &name, &name_offset));
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers_malformed_symdata32) {
+TEST_F(ElfInterfaceTest, init_section_headers_malformed_symdata_32) {
   InitSectionHeadersMalformedSymData<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers_malformed_symdata64) {
+TEST_F(ElfInterfaceTest, init_section_headers_malformed_symdata_64) {
   InitSectionHeadersMalformedSymData<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>();
 }
 
@@ -860,14 +879,13 @@
   shdr.sh_offset = 0xf000;
   shdr.sh_size = 0x1000;
   memory_.SetMemory(offset, &shdr, sizeof(shdr));
-  offset += ehdr.e_shentsize;
 
   InitSym<Sym>(0x5000, 0x90000, 0x1000, 0x100, 0xf000, "function_one");
   InitSym<Sym>(0x6000, 0xd0000, 0x1000, 0x300, 0xf000, "function_two");
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
   EXPECT_EQ(0U, elf->debug_frame_offset());
   EXPECT_EQ(0U, elf->debug_frame_size());
   EXPECT_EQ(0U, elf->gnu_debugdata_offset());
@@ -884,19 +902,19 @@
   EXPECT_EQ(32U, name_offset);
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers32) {
+TEST_F(ElfInterfaceTest, init_section_headers_32) {
   InitSectionHeaders<Elf32_Ehdr, Elf32_Shdr, Elf32_Sym, ElfInterface32>(sizeof(Elf32_Shdr));
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers64) {
+TEST_F(ElfInterfaceTest, init_section_headers_64) {
   InitSectionHeaders<Elf64_Ehdr, Elf64_Shdr, Elf64_Sym, ElfInterface64>(sizeof(Elf64_Shdr));
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers_non_std_entry_size32) {
+TEST_F(ElfInterfaceTest, init_section_headers_non_std_entry_size_32) {
   InitSectionHeaders<Elf32_Ehdr, Elf32_Shdr, Elf32_Sym, ElfInterface32>(0x100);
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers_non_std_entry_size64) {
+TEST_F(ElfInterfaceTest, init_section_headers_non_std_entry_size_64) {
   InitSectionHeaders<Elf64_Ehdr, Elf64_Shdr, Elf64_Sym, ElfInterface64>(0x100);
 }
 
@@ -961,7 +979,7 @@
   shdr.sh_type = SHT_PROGBITS;
   shdr.sh_link = 2;
   shdr.sh_name = 0x400;
-  shdr.sh_addr = 0x6000;
+  shdr.sh_addr = 0xa000;
   shdr.sh_offset = 0xa000;
   shdr.sh_entsize = 0x100;
   shdr.sh_size = 0xf00;
@@ -971,10 +989,10 @@
   memset(&shdr, 0, sizeof(shdr));
   shdr.sh_type = SHT_NOTE;
   shdr.sh_name = 0x500;
+  shdr.sh_addr = 0xb000;
   shdr.sh_offset = 0xb000;
   shdr.sh_size = 0xf00;
   memory_.SetMemory(offset, &shdr, sizeof(shdr));
-  offset += ehdr.e_shentsize;
 
   memory_.SetMemory(0xf100, ".debug_frame", sizeof(".debug_frame"));
   memory_.SetMemory(0xf200, ".gnu_debugdata", sizeof(".gnu_debugdata"));
@@ -982,29 +1000,352 @@
   memory_.SetMemory(0xf400, ".eh_frame_hdr", sizeof(".eh_frame_hdr"));
   memory_.SetMemory(0xf500, ".note.gnu.build-id", sizeof(".note.gnu.build-id"));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
   EXPECT_EQ(0x6000U, elf->debug_frame_offset());
+  EXPECT_EQ(0, elf->debug_frame_section_bias());
   EXPECT_EQ(0x500U, elf->debug_frame_size());
+
   EXPECT_EQ(0x5000U, elf->gnu_debugdata_offset());
   EXPECT_EQ(0x800U, elf->gnu_debugdata_size());
+
   EXPECT_EQ(0x7000U, elf->eh_frame_offset());
+  EXPECT_EQ(0, elf->eh_frame_section_bias());
   EXPECT_EQ(0x800U, elf->eh_frame_size());
+
   EXPECT_EQ(0xa000U, elf->eh_frame_hdr_offset());
+  EXPECT_EQ(0, elf->eh_frame_hdr_section_bias());
   EXPECT_EQ(0xf00U, elf->eh_frame_hdr_size());
+
   EXPECT_EQ(0xb000U, elf->gnu_build_id_offset());
   EXPECT_EQ(0xf00U, elf->gnu_build_id_size());
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers_offsets32) {
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_32) {
   InitSectionHeadersOffsets<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, init_section_headers_offsets64) {
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_64) {
   InitSectionHeadersOffsets<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>();
 }
 
+template <typename Ehdr, typename Shdr, typename ElfInterfaceType>
+void ElfInterfaceTest::InitSectionHeadersOffsetsEhFrameSectionBias(uint64_t addr, uint64_t offset,
+                                                                   int64_t expected_bias) {
+  std::unique_ptr<ElfInterfaceType> elf(new ElfInterfaceType(&memory_));
+
+  uint64_t elf_offset = 0x2000;
+
+  Ehdr ehdr = {};
+  ehdr.e_shoff = elf_offset;
+  ehdr.e_shnum = 4;
+  ehdr.e_shentsize = sizeof(Shdr);
+  ehdr.e_shstrndx = 2;
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  elf_offset += ehdr.e_shentsize;
+
+  Shdr shdr = {};
+  shdr.sh_type = SHT_PROGBITS;
+  shdr.sh_link = 2;
+  shdr.sh_name = 0x200;
+  shdr.sh_addr = 0x8000;
+  shdr.sh_offset = 0x8000;
+  shdr.sh_entsize = 0x100;
+  shdr.sh_size = 0x800;
+  memory_.SetMemory(elf_offset, &shdr, sizeof(shdr));
+  elf_offset += ehdr.e_shentsize;
+
+  // The string data for section header names.
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_STRTAB;
+  shdr.sh_name = 0x20000;
+  shdr.sh_offset = 0xf000;
+  shdr.sh_size = 0x1000;
+  memory_.SetMemory(elf_offset, &shdr, sizeof(shdr));
+  elf_offset += ehdr.e_shentsize;
+
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_PROGBITS;
+  shdr.sh_link = 2;
+  shdr.sh_name = 0x100;
+  shdr.sh_addr = addr;
+  shdr.sh_offset = offset;
+  shdr.sh_entsize = 0x100;
+  shdr.sh_size = 0x500;
+  memory_.SetMemory(elf_offset, &shdr, sizeof(shdr));
+
+  memory_.SetMemory(0xf100, ".eh_frame", sizeof(".eh_frame"));
+  memory_.SetMemory(0xf200, ".eh_frame_hdr", sizeof(".eh_frame_hdr"));
+
+  int64_t load_bias = 0;
+  ASSERT_TRUE(elf->Init(&load_bias));
+  EXPECT_EQ(0, load_bias);
+  EXPECT_EQ(offset, elf->eh_frame_offset());
+  EXPECT_EQ(expected_bias, elf->eh_frame_section_bias());
+  EXPECT_EQ(0x500U, elf->eh_frame_size());
+
+  EXPECT_EQ(0x8000U, elf->eh_frame_hdr_offset());
+  EXPECT_EQ(0, elf->eh_frame_hdr_section_bias());
+  EXPECT_EQ(0x800U, elf->eh_frame_hdr_size());
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_section_bias_zero_32) {
+  InitSectionHeadersOffsetsEhFrameSectionBias<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>(0x4000,
+                                                                                      0x4000, 0);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_section_bias_zero_64) {
+  InitSectionHeadersOffsetsEhFrameSectionBias<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>(0x6000,
+                                                                                      0x6000, 0);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_section_bias_positive_32) {
+  InitSectionHeadersOffsetsEhFrameSectionBias<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>(
+      0x5000, 0x4000, 0x1000);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_section_bias_positive_64) {
+  InitSectionHeadersOffsetsEhFrameSectionBias<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>(
+      0x6000, 0x4000, 0x2000);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_section_bias_negative_32) {
+  InitSectionHeadersOffsetsEhFrameSectionBias<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>(
+      0x3000, 0x4000, -0x1000);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_section_bias_negative_64) {
+  InitSectionHeadersOffsetsEhFrameSectionBias<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>(
+      0x6000, 0x9000, -0x3000);
+}
+
+template <typename Ehdr, typename Shdr, typename ElfInterfaceType>
+void ElfInterfaceTest::InitSectionHeadersOffsetsEhFrameHdrSectionBias(uint64_t addr,
+                                                                      uint64_t offset,
+                                                                      int64_t expected_bias) {
+  std::unique_ptr<ElfInterfaceType> elf(new ElfInterfaceType(&memory_));
+
+  uint64_t elf_offset = 0x2000;
+
+  Ehdr ehdr = {};
+  ehdr.e_shoff = elf_offset;
+  ehdr.e_shnum = 4;
+  ehdr.e_shentsize = sizeof(Shdr);
+  ehdr.e_shstrndx = 2;
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  elf_offset += ehdr.e_shentsize;
+
+  Shdr shdr = {};
+  shdr.sh_type = SHT_PROGBITS;
+  shdr.sh_link = 2;
+  shdr.sh_name = 0x200;
+  shdr.sh_addr = addr;
+  shdr.sh_offset = offset;
+  shdr.sh_entsize = 0x100;
+  shdr.sh_size = 0x800;
+  memory_.SetMemory(elf_offset, &shdr, sizeof(shdr));
+  elf_offset += ehdr.e_shentsize;
+
+  // The string data for section header names.
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_STRTAB;
+  shdr.sh_name = 0x20000;
+  shdr.sh_offset = 0xf000;
+  shdr.sh_size = 0x1000;
+  memory_.SetMemory(elf_offset, &shdr, sizeof(shdr));
+  elf_offset += ehdr.e_shentsize;
+
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_PROGBITS;
+  shdr.sh_link = 2;
+  shdr.sh_name = 0x100;
+  shdr.sh_addr = 0x5000;
+  shdr.sh_offset = 0x5000;
+  shdr.sh_entsize = 0x100;
+  shdr.sh_size = 0x500;
+  memory_.SetMemory(elf_offset, &shdr, sizeof(shdr));
+
+  memory_.SetMemory(0xf100, ".eh_frame", sizeof(".eh_frame"));
+  memory_.SetMemory(0xf200, ".eh_frame_hdr", sizeof(".eh_frame_hdr"));
+
+  int64_t load_bias = 0;
+  ASSERT_TRUE(elf->Init(&load_bias));
+  EXPECT_EQ(0, load_bias);
+  EXPECT_EQ(0x5000U, elf->eh_frame_offset());
+  EXPECT_EQ(0, elf->eh_frame_section_bias());
+  EXPECT_EQ(0x500U, elf->eh_frame_size());
+  EXPECT_EQ(offset, elf->eh_frame_hdr_offset());
+  EXPECT_EQ(expected_bias, elf->eh_frame_hdr_section_bias());
+  EXPECT_EQ(0x800U, elf->eh_frame_hdr_size());
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_hdr_section_bias_zero_32) {
+  InitSectionHeadersOffsetsEhFrameHdrSectionBias<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>(0x9000,
+                                                                                         0x9000, 0);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_hdr_section_bias_zero_64) {
+  InitSectionHeadersOffsetsEhFrameHdrSectionBias<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>(0xa000,
+                                                                                         0xa000, 0);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_hdr_section_bias_positive_32) {
+  InitSectionHeadersOffsetsEhFrameHdrSectionBias<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>(
+      0x9000, 0x4000, 0x5000);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_hdr_section_bias_positive_64) {
+  InitSectionHeadersOffsetsEhFrameHdrSectionBias<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>(
+      0x6000, 0x1000, 0x5000);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_hdr_section_bias_negative_32) {
+  InitSectionHeadersOffsetsEhFrameHdrSectionBias<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>(
+      0x3000, 0x5000, -0x2000);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_eh_frame_hdr_section_bias_negative_64) {
+  InitSectionHeadersOffsetsEhFrameHdrSectionBias<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>(
+      0x5000, 0x9000, -0x4000);
+}
+
+template <typename Ehdr, typename Shdr, typename ElfInterfaceType>
+void ElfInterfaceTest::InitSectionHeadersOffsetsDebugFrameSectionBias(uint64_t addr,
+                                                                      uint64_t offset,
+                                                                      int64_t expected_bias) {
+  std::unique_ptr<ElfInterfaceType> elf(new ElfInterfaceType(&memory_));
+
+  uint64_t elf_offset = 0x2000;
+
+  Ehdr ehdr = {};
+  ehdr.e_shoff = elf_offset;
+  ehdr.e_shnum = 3;
+  ehdr.e_shentsize = sizeof(Shdr);
+  ehdr.e_shstrndx = 2;
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  elf_offset += ehdr.e_shentsize;
+
+  Shdr shdr = {};
+  shdr.sh_type = SHT_PROGBITS;
+  shdr.sh_link = 2;
+  shdr.sh_name = 0x100;
+  shdr.sh_addr = addr;
+  shdr.sh_offset = offset;
+  shdr.sh_entsize = 0x100;
+  shdr.sh_size = 0x800;
+  memory_.SetMemory(elf_offset, &shdr, sizeof(shdr));
+  elf_offset += ehdr.e_shentsize;
+
+  // The string data for section header names.
+  memset(&shdr, 0, sizeof(shdr));
+  shdr.sh_type = SHT_STRTAB;
+  shdr.sh_name = 0x20000;
+  shdr.sh_offset = 0xf000;
+  shdr.sh_size = 0x1000;
+  memory_.SetMemory(elf_offset, &shdr, sizeof(shdr));
+
+  memory_.SetMemory(0xf100, ".debug_frame", sizeof(".debug_frame"));
+
+  int64_t load_bias = 0;
+  ASSERT_TRUE(elf->Init(&load_bias));
+  EXPECT_EQ(0, load_bias);
+  EXPECT_EQ(offset, elf->debug_frame_offset());
+  EXPECT_EQ(expected_bias, elf->debug_frame_section_bias());
+  EXPECT_EQ(0x800U, elf->debug_frame_size());
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_debug_frame_section_bias_zero_32) {
+  InitSectionHeadersOffsetsDebugFrameSectionBias<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>(0x5000,
+                                                                                         0x5000, 0);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_debug_frame_section_bias_zero_64) {
+  InitSectionHeadersOffsetsDebugFrameSectionBias<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>(0xa000,
+                                                                                         0xa000, 0);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_debug_frame_section_bias_positive_32) {
+  InitSectionHeadersOffsetsDebugFrameSectionBias<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>(
+      0x5000, 0x2000, 0x3000);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_debug_frame_section_bias_positive_64) {
+  InitSectionHeadersOffsetsDebugFrameSectionBias<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>(
+      0x7000, 0x1000, 0x6000);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_debug_frame_section_bias_negative_32) {
+  InitSectionHeadersOffsetsDebugFrameSectionBias<Elf32_Ehdr, Elf32_Shdr, ElfInterface32>(
+      0x6000, 0x7000, -0x1000);
+}
+
+TEST_F(ElfInterfaceTest, init_section_headers_offsets_debug_frame_section_bias_negative_64) {
+  InitSectionHeadersOffsetsDebugFrameSectionBias<Elf64_Ehdr, Elf64_Shdr, ElfInterface64>(
+      0x3000, 0x5000, -0x2000);
+}
+
+template <typename Ehdr, typename Phdr, typename ElfInterfaceType>
+void ElfInterfaceTest::CheckGnuEhFrame(uint64_t addr, uint64_t offset, int64_t expected_bias) {
+  std::unique_ptr<ElfInterface> elf(new ElfInterfaceType(&memory_));
+
+  Ehdr ehdr = {};
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 2;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  uint64_t phdr_offset = 0x100;
+
+  Phdr phdr = {};
+  phdr.p_type = PT_LOAD;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+  phdr_offset += sizeof(phdr);
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_GNU_EH_FRAME;
+  phdr.p_paddr = addr;
+  phdr.p_offset = offset;
+  memory_.SetMemory(phdr_offset, &phdr, sizeof(phdr));
+
+  int64_t load_bias = 0;
+  ASSERT_TRUE(elf->Init(&load_bias));
+  EXPECT_EQ(0, load_bias);
+  EXPECT_EQ(expected_bias, elf->eh_frame_hdr_section_bias());
+}
+
+TEST_F(ElfInterfaceTest, eh_frame_zero_section_bias_32) {
+  ElfInterfaceTest::CheckGnuEhFrame<Elf32_Ehdr, Elf32_Phdr, ElfInterface32>(0x4000, 0x4000, 0);
+}
+
+TEST_F(ElfInterfaceTest, eh_frame_zero_section_bias_64) {
+  ElfInterfaceTest::CheckGnuEhFrame<Elf64_Ehdr, Elf64_Phdr, ElfInterface64>(0x4000, 0x4000, 0);
+}
+
+TEST_F(ElfInterfaceTest, eh_frame_positive_section_bias_32) {
+  ElfInterfaceTest::CheckGnuEhFrame<Elf32_Ehdr, Elf32_Phdr, ElfInterface32>(0x4000, 0x1000, 0x3000);
+}
+
+TEST_F(ElfInterfaceTest, eh_frame_positive_section_bias_64) {
+  ElfInterfaceTest::CheckGnuEhFrame<Elf64_Ehdr, Elf64_Phdr, ElfInterface64>(0x4000, 0x1000, 0x3000);
+}
+
+TEST_F(ElfInterfaceTest, eh_frame_negative_section_bias_32) {
+  ElfInterfaceTest::CheckGnuEhFrame<Elf32_Ehdr, Elf32_Phdr, ElfInterface32>(0x4000, 0x5000,
+                                                                            -0x1000);
+}
+
+TEST_F(ElfInterfaceTest, eh_frame_negative_section_bias_64) {
+  ElfInterfaceTest::CheckGnuEhFrame<Elf64_Ehdr, Elf64_Phdr, ElfInterface64>(0x4000, 0x5000,
+                                                                            -0x1000);
+}
+
 TEST_F(ElfInterfaceTest, is_valid_pc_from_pt_load) {
   std::unique_ptr<ElfInterface> elf(new ElfInterface32(&memory_));
 
@@ -1022,9 +1363,9 @@
   phdr.p_align = 0x1000;
   memory_.SetMemory(0x100, &phdr, sizeof(phdr));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0U, load_bias);
+  EXPECT_EQ(0, load_bias);
   EXPECT_TRUE(elf->IsValidPc(0));
   EXPECT_TRUE(elf->IsValidPc(0x5000));
   EXPECT_TRUE(elf->IsValidPc(0xffff));
@@ -1048,9 +1389,9 @@
   phdr.p_align = 0x1000;
   memory_.SetMemory(0x100, &phdr, sizeof(phdr));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  EXPECT_EQ(0x2000U, load_bias);
+  EXPECT_EQ(0x2000, load_bias);
   EXPECT_FALSE(elf->IsValidPc(0));
   EXPECT_FALSE(elf->IsValidPc(0x1000));
   EXPECT_FALSE(elf->IsValidPc(0x1fff));
@@ -1105,10 +1446,10 @@
   memory_.SetData32(0x708, 0x2100);
   memory_.SetData32(0x70c, 0x200);
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  elf->InitHeaders(0);
-  EXPECT_EQ(0U, load_bias);
+  elf->InitHeaders();
+  EXPECT_EQ(0, load_bias);
   EXPECT_FALSE(elf->IsValidPc(0));
   EXPECT_FALSE(elf->IsValidPc(0x20ff));
   EXPECT_TRUE(elf->IsValidPc(0x2100));
@@ -1162,10 +1503,10 @@
   memory_.SetData32(0x708, 0x20f8);
   memory_.SetData32(0x70c, 0x200);
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
-  elf->InitHeaders(0);
-  EXPECT_EQ(0U, load_bias);
+  elf->InitHeaders();
+  EXPECT_EQ(0, load_bias);
   EXPECT_FALSE(elf->IsValidPc(0));
   EXPECT_FALSE(elf->IsValidPc(0x27ff));
   EXPECT_TRUE(elf->IsValidPc(0x2800));
@@ -1201,7 +1542,6 @@
   note_offset += sizeof("GNU");
   // This part of the note does not contain any trailing '\0'.
   memcpy(&note_section[note_offset], "BUILDID", 7);
-  note_offset += 8;
 
   Shdr shdr = {};
   shdr.sh_type = SHT_NOTE;
@@ -1218,16 +1558,23 @@
   shdr.sh_offset = 0xf000;
   shdr.sh_size = 0x1000;
   memory_.SetMemory(offset, &shdr, sizeof(shdr));
-  offset += ehdr.e_shentsize;
 
   memory_.SetMemory(0xf500, ".note.gnu.build-id", sizeof(".note.gnu.build-id"));
   memory_.SetMemory(0xb000, note_section, sizeof(note_section));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
   ASSERT_EQ("BUILDID", elf->GetBuildID());
 }
 
+TEST_F(ElfInterfaceTest, build_id_32) {
+  BuildID<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, build_id_64) {
+  BuildID<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr, ElfInterface64>();
+}
+
 template <typename Ehdr, typename Shdr, typename Nhdr, typename ElfInterfaceType>
 void ElfInterfaceTest::BuildIDTwoNotes() {
   std::unique_ptr<ElfInterfaceType> elf(new ElfInterfaceType(&memory_));
@@ -1266,7 +1613,6 @@
   note_offset += sizeof("GNU");
   // This part of the note does not contain any trailing '\0'.
   memcpy(&note_section[note_offset], "BUILDID", 7);
-  note_offset += 8;
 
   Shdr shdr = {};
   shdr.sh_type = SHT_NOTE;
@@ -1283,16 +1629,23 @@
   shdr.sh_offset = 0xf000;
   shdr.sh_size = 0x1000;
   memory_.SetMemory(offset, &shdr, sizeof(shdr));
-  offset += ehdr.e_shentsize;
 
   memory_.SetMemory(0xf500, ".note.gnu.build-id", sizeof(".note.gnu.build-id"));
   memory_.SetMemory(0xb000, note_section, sizeof(note_section));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
   ASSERT_EQ("BUILDID", elf->GetBuildID());
 }
 
+TEST_F(ElfInterfaceTest, build_id_two_notes_32) {
+  BuildIDTwoNotes<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, build_id_two_notes_64) {
+  BuildIDTwoNotes<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr, ElfInterface64>();
+}
+
 template <typename Ehdr, typename Shdr, typename Nhdr, typename ElfInterfaceType>
 void ElfInterfaceTest::BuildIDSectionTooSmallForName () {
   std::unique_ptr<ElfInterfaceType> elf(new ElfInterfaceType(&memory_));
@@ -1320,7 +1673,6 @@
   note_offset += sizeof("GNU");
   // This part of the note does not contain any trailing '\0'.
   memcpy(&note_section[note_offset], "BUILDID", 7);
-  note_offset += 8;
 
   Shdr shdr = {};
   shdr.sh_type = SHT_NOTE;
@@ -1337,16 +1689,23 @@
   shdr.sh_offset = 0xf000;
   shdr.sh_size = 0x1000;
   memory_.SetMemory(offset, &shdr, sizeof(shdr));
-  offset += ehdr.e_shentsize;
 
   memory_.SetMemory(0xf500, ".note.gnu.build-id", sizeof(".note.gnu.build-id"));
   memory_.SetMemory(0xb000, note_section, sizeof(note_section));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
   ASSERT_EQ("", elf->GetBuildID());
 }
 
+TEST_F(ElfInterfaceTest, build_id_section_too_small_for_name_32) {
+  BuildIDSectionTooSmallForName<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, build_id_section_too_small_for_name_64) {
+  BuildIDSectionTooSmallForName<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr, ElfInterface64>();
+}
+
 template <typename Ehdr, typename Shdr, typename Nhdr, typename ElfInterfaceType>
 void ElfInterfaceTest::BuildIDSectionTooSmallForDesc () {
   std::unique_ptr<ElfInterfaceType> elf(new ElfInterfaceType(&memory_));
@@ -1374,7 +1733,6 @@
   note_offset += sizeof("GNU");
   // This part of the note does not contain any trailing '\0'.
   memcpy(&note_section[note_offset], "BUILDID", 7);
-  note_offset += 8;
 
   Shdr shdr = {};
   shdr.sh_type = SHT_NOTE;
@@ -1391,16 +1749,23 @@
   shdr.sh_offset = 0xf000;
   shdr.sh_size = 0x1000;
   memory_.SetMemory(offset, &shdr, sizeof(shdr));
-  offset += ehdr.e_shentsize;
 
   memory_.SetMemory(0xf500, ".note.gnu.build-id", sizeof(".note.gnu.build-id"));
   memory_.SetMemory(0xb000, note_section, sizeof(note_section));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
   ASSERT_EQ("", elf->GetBuildID());
 }
 
+TEST_F(ElfInterfaceTest, build_id_section_too_small_for_desc_32) {
+  BuildIDSectionTooSmallForDesc<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr, ElfInterface32>();
+}
+
+TEST_F(ElfInterfaceTest, build_id_section_too_small_for_desc_64) {
+  BuildIDSectionTooSmallForDesc<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr, ElfInterface64>();
+}
+
 template <typename Ehdr, typename Shdr, typename Nhdr, typename ElfInterfaceType>
 void ElfInterfaceTest::BuildIDSectionTooSmallForHeader () {
   std::unique_ptr<ElfInterfaceType> elf(new ElfInterfaceType(&memory_));
@@ -1428,7 +1793,6 @@
   note_offset += sizeof("GNU");
   // This part of the note does not contain any trailing '\0'.
   memcpy(&note_section[note_offset], "BUILDID", 7);
-  note_offset += 8;
 
   Shdr shdr = {};
   shdr.sh_type = SHT_NOTE;
@@ -1445,54 +1809,139 @@
   shdr.sh_offset = 0xf000;
   shdr.sh_size = 0x1000;
   memory_.SetMemory(offset, &shdr, sizeof(shdr));
-  offset += ehdr.e_shentsize;
 
   memory_.SetMemory(0xf500, ".note.gnu.build-id", sizeof(".note.gnu.build-id"));
   memory_.SetMemory(0xb000, note_section, sizeof(note_section));
 
-  uint64_t load_bias = 0;
+  int64_t load_bias = 0;
   ASSERT_TRUE(elf->Init(&load_bias));
   ASSERT_EQ("", elf->GetBuildID());
 }
 
-TEST_F(ElfInterfaceTest, build_id32) {
-  BuildID<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr, ElfInterface32>();
-}
-
-TEST_F(ElfInterfaceTest, build_id64) {
-  BuildID<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr, ElfInterface64>();
-}
-
-TEST_F(ElfInterfaceTest, build_id_two_notes32) {
-  BuildIDTwoNotes<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr, ElfInterface32>();
-}
-
-TEST_F(ElfInterfaceTest, build_id_two_notes64) {
-  BuildIDTwoNotes<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr, ElfInterface64>();
-}
-
-TEST_F(ElfInterfaceTest, build_id_section_too_small_for_name32) {
-  BuildIDSectionTooSmallForName<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr, ElfInterface32>();
-}
-
-TEST_F(ElfInterfaceTest, build_id_section_too_small_for_name64) {
-  BuildIDSectionTooSmallForName<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr, ElfInterface64>();
-}
-
-TEST_F(ElfInterfaceTest, build_id_section_too_small_for_desc32) {
-  BuildIDSectionTooSmallForDesc<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr, ElfInterface32>();
-}
-
-TEST_F(ElfInterfaceTest, build_id_section_too_small_for_desc64) {
-  BuildIDSectionTooSmallForDesc<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr, ElfInterface64>();
-}
-
-TEST_F(ElfInterfaceTest, build_id_section_too_small_for_header32) {
+TEST_F(ElfInterfaceTest, build_id_section_too_small_for_header_32) {
   BuildIDSectionTooSmallForHeader<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr, ElfInterface32>();
 }
 
-TEST_F(ElfInterfaceTest, build_id_section_too_small_for_header64) {
+TEST_F(ElfInterfaceTest, build_id_section_too_small_for_header_64) {
   BuildIDSectionTooSmallForHeader<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr, ElfInterface64>();
 }
 
+template <typename Ehdr, typename Phdr, typename ElfInterfaceType>
+void ElfInterfaceTest::CheckLoadBiasInFirstPhdr(int64_t load_bias) {
+  Ehdr ehdr = {};
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 2;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr = {};
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = 0;
+  phdr.p_vaddr = load_bias;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = 0x1000;
+  phdr.p_memsz = 0x2000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100 + sizeof(phdr), &phdr, sizeof(phdr));
+
+  int64_t static_load_bias = ElfInterface::GetLoadBias<Ehdr, Phdr>(&memory_);
+  ASSERT_EQ(load_bias, static_load_bias);
+
+  std::unique_ptr<ElfInterfaceType> elf(new ElfInterfaceType(&memory_));
+  int64_t init_load_bias = 0;
+  ASSERT_TRUE(elf->Init(&init_load_bias));
+  ASSERT_EQ(init_load_bias, static_load_bias);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_zero_32) {
+  CheckLoadBiasInFirstPhdr<Elf32_Ehdr, Elf32_Phdr, ElfInterface32>(0);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_zero_64) {
+  CheckLoadBiasInFirstPhdr<Elf64_Ehdr, Elf64_Phdr, ElfInterface64>(0);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_non_zero_32) {
+  CheckLoadBiasInFirstPhdr<Elf32_Ehdr, Elf32_Phdr, ElfInterface32>(0x1000);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_non_zero_64) {
+  CheckLoadBiasInFirstPhdr<Elf64_Ehdr, Elf64_Phdr, ElfInterface64>(0x1000);
+}
+
+template <typename Ehdr, typename Phdr, typename ElfInterfaceType>
+void ElfInterfaceTest::CheckLoadBiasInFirstExecPhdr(uint64_t offset, uint64_t vaddr,
+                                                    int64_t load_bias) {
+  Ehdr ehdr = {};
+  ehdr.e_phoff = 0x100;
+  ehdr.e_phnum = 3;
+  ehdr.e_phentsize = sizeof(Phdr);
+  memory_.SetMemory(0, &ehdr, sizeof(ehdr));
+
+  Phdr phdr = {};
+  phdr.p_type = PT_LOAD;
+  phdr.p_memsz = 0x10000;
+  phdr.p_flags = PF_R;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100, &phdr, sizeof(phdr));
+
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = offset;
+  phdr.p_vaddr = vaddr;
+  phdr.p_memsz = 0x2000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x100 + sizeof(phdr), &phdr, sizeof(phdr));
+
+  // Second executable load should be ignored for load bias computation.
+  memset(&phdr, 0, sizeof(phdr));
+  phdr.p_type = PT_LOAD;
+  phdr.p_offset = 0x1234;
+  phdr.p_vaddr = 0x2000;
+  phdr.p_memsz = 0x2000;
+  phdr.p_flags = PF_R | PF_X;
+  phdr.p_align = 0x1000;
+  memory_.SetMemory(0x200 + sizeof(phdr), &phdr, sizeof(phdr));
+
+  int64_t static_load_bias = ElfInterface::GetLoadBias<Ehdr, Phdr>(&memory_);
+  ASSERT_EQ(load_bias, static_load_bias);
+
+  std::unique_ptr<ElfInterfaceType> elf(new ElfInterfaceType(&memory_));
+  int64_t init_load_bias = 0;
+  ASSERT_TRUE(elf->Init(&init_load_bias));
+  ASSERT_EQ(init_load_bias, static_load_bias);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_exec_zero_32) {
+  CheckLoadBiasInFirstExecPhdr<Elf32_Ehdr, Elf32_Phdr, ElfInterface32>(0x1000, 0x1000, 0);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_exec_zero_64) {
+  CheckLoadBiasInFirstExecPhdr<Elf64_Ehdr, Elf64_Phdr, ElfInterface64>(0x1000, 0x1000, 0);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_exec_positive_32) {
+  CheckLoadBiasInFirstExecPhdr<Elf32_Ehdr, Elf32_Phdr, ElfInterface32>(0x1000, 0x4000, 0x3000);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_exec_positive_64) {
+  CheckLoadBiasInFirstExecPhdr<Elf64_Ehdr, Elf64_Phdr, ElfInterface64>(0x1000, 0x4000, 0x3000);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_exec_negative_32) {
+  CheckLoadBiasInFirstExecPhdr<Elf32_Ehdr, Elf32_Phdr, ElfInterface32>(0x5000, 0x1000, -0x4000);
+}
+
+TEST_F(ElfInterfaceTest, get_load_bias_exec_negative_64) {
+  CheckLoadBiasInFirstExecPhdr<Elf64_Ehdr, Elf64_Phdr, ElfInterface64>(0x5000, 0x1000, -0x4000);
+}
+
 }  // namespace unwindstack
diff --git a/libunwindstack/tests/ElfTest.cpp b/libunwindstack/tests/ElfTest.cpp
index c432d6d..e6728a0 100644
--- a/libunwindstack/tests/ElfTest.cpp
+++ b/libunwindstack/tests/ElfTest.cpp
@@ -310,15 +310,15 @@
   ElfInterfaceMock(Memory* memory) : ElfInterface(memory) {}
   virtual ~ElfInterfaceMock() = default;
 
-  bool Init(uint64_t*) override { return false; }
-  void InitHeaders(uint64_t) override {}
+  bool Init(int64_t*) override { return false; }
+  void InitHeaders() override {}
   std::string GetSoname() override { return ""; }
   bool GetFunctionName(uint64_t, std::string*, uint64_t*) override { return false; }
   std::string GetBuildID() override { return ""; }
 
-  MOCK_METHOD4(Step, bool(uint64_t, Regs*, Memory*, bool*));
-  MOCK_METHOD2(GetGlobalVariable, bool(const std::string&, uint64_t*));
-  MOCK_METHOD1(IsValidPc, bool(uint64_t));
+  MOCK_METHOD(bool, Step, (uint64_t, Regs*, Memory*, bool*), (override));
+  MOCK_METHOD(bool, GetGlobalVariable, (const std::string&, uint64_t*), (override));
+  MOCK_METHOD(bool, IsValidPc, (uint64_t), (override));
 
   void MockSetDynamicOffset(uint64_t offset) { dynamic_offset_ = offset; }
   void MockSetDynamicVaddr(uint64_t vaddr) { dynamic_vaddr_ = vaddr; }
diff --git a/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp b/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp
index f5ac6cb..da3dbf2 100644
--- a/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp
+++ b/libunwindstack/tests/MapInfoGetLoadBiasTest.cpp
@@ -84,7 +84,7 @@
   elf_->FakeSetLoadBias(0);
   EXPECT_EQ(0U, map_info_->GetLoadBias(process_memory_));
 
-  map_info_->load_bias = static_cast<uint64_t>(-1);
+  map_info_->load_bias = INT64_MAX;
   elf_->FakeSetLoadBias(0x1000);
   EXPECT_EQ(0x1000U, map_info_->GetLoadBias(process_memory_));
 }
@@ -141,6 +141,7 @@
   phdr.p_type = PT_NULL;
   memory->SetMemory(offset + 0x5000, &phdr, sizeof(phdr));
   phdr.p_type = PT_LOAD;
+  phdr.p_flags = PF_X;
   phdr.p_offset = 0;
   phdr.p_vaddr = 0xe000;
   memory->SetMemory(offset + 0x5000 + sizeof(phdr), &phdr, sizeof(phdr));
diff --git a/libunwindstack/tests/MapInfoTest.cpp b/libunwindstack/tests/MapInfoTest.cpp
index e2cbb98..ef76b1b 100644
--- a/libunwindstack/tests/MapInfoTest.cpp
+++ b/libunwindstack/tests/MapInfoTest.cpp
@@ -35,7 +35,7 @@
   EXPECT_EQ(3UL, map_info.offset);
   EXPECT_EQ(4UL, map_info.flags);
   EXPECT_EQ("map", map_info.name);
-  EXPECT_EQ(static_cast<uint64_t>(-1), map_info.load_bias);
+  EXPECT_EQ(INT64_MAX, map_info.load_bias);
   EXPECT_EQ(0UL, map_info.elf_offset);
   EXPECT_TRUE(map_info.elf.get() == nullptr);
 }
@@ -51,7 +51,7 @@
   EXPECT_EQ(3UL, map_info.offset);
   EXPECT_EQ(4UL, map_info.flags);
   EXPECT_EQ("string_map", map_info.name);
-  EXPECT_EQ(static_cast<uint64_t>(-1), map_info.load_bias);
+  EXPECT_EQ(INT64_MAX, map_info.load_bias);
   EXPECT_EQ(0UL, map_info.elf_offset);
   EXPECT_TRUE(map_info.elf.get() == nullptr);
 }
diff --git a/libunwindstack/tests/UnwindOfflineTest.cpp b/libunwindstack/tests/UnwindOfflineTest.cpp
index bded57a..72eef3e 100644
--- a/libunwindstack/tests/UnwindOfflineTest.cpp
+++ b/libunwindstack/tests/UnwindOfflineTest.cpp
@@ -1534,4 +1534,53 @@
   EXPECT_EQ(0x7ffd22415e90ULL, unwinder.frames()[16].sp);
 }
 
+TEST_F(UnwindOfflineTest, load_bias_different_section_bias_arm64) {
+  ASSERT_NO_FATAL_FAILURE(Init("load_bias_different_section_bias_arm64/", ARCH_ARM64));
+
+  Unwinder unwinder(128, maps_.get(), regs_.get(), process_memory_);
+  unwinder.Unwind();
+
+  std::string frame_info(DumpFrames(unwinder));
+  ASSERT_EQ(12U, unwinder.NumFrames()) << "Unwind:\n" << frame_info;
+  EXPECT_EQ(
+      "  #00 pc 00000000000d59bc  linker64 (__dl_syscall+28)\n"
+      "  #01 pc 00000000000554e8  linker64 (__dl__ZL24debuggerd_signal_handleriP7siginfoPv+1148)\n"
+      "  #02 pc 00000000000008c0  vdso (__kernel_rt_sigreturn)\n"
+      "  #03 pc 000000000007f3e8  libc.so (abort+168)\n"
+      "  #04 pc 00000000000459fc  test (std::__ndk1::__throw_bad_cast()+4)\n"
+      "  #05 pc 0000000000056d80  test (testing::Test::Run()+88)\n"
+      "  #06 pc 000000000005724c  test (testing::TestInfo::Run()+112)\n"
+      "  #07 pc 0000000000057558  test (testing::TestSuite::Run()+116)\n"
+      "  #08 pc 000000000005bffc  test (testing::internal::UnitTestImpl::RunAllTests()+464)\n"
+      "  #09 pc 000000000005bd9c  test (testing::UnitTest::Run()+116)\n"
+      "  #10 pc 00000000000464e4  test (main+144)\n"
+      "  #11 pc 000000000007aa34  libc.so (__libc_init+108)\n",
+      frame_info);
+
+  EXPECT_EQ(0x7112cb99bcULL, unwinder.frames()[0].pc);
+  EXPECT_EQ(0x7112bdbbf0ULL, unwinder.frames()[0].sp);
+  EXPECT_EQ(0x7112c394e8ULL, unwinder.frames()[1].pc);
+  EXPECT_EQ(0x7112bdbbf0ULL, unwinder.frames()[1].sp);
+  EXPECT_EQ(0x7112be28c0ULL, unwinder.frames()[2].pc);
+  EXPECT_EQ(0x7112bdbda0ULL, unwinder.frames()[2].sp);
+  EXPECT_EQ(0x71115ab3e8ULL, unwinder.frames()[3].pc);
+  EXPECT_EQ(0x7fdd4a3f00ULL, unwinder.frames()[3].sp);
+  EXPECT_EQ(0x5f739dc9fcULL, unwinder.frames()[4].pc);
+  EXPECT_EQ(0x7fdd4a3fe0ULL, unwinder.frames()[4].sp);
+  EXPECT_EQ(0x5f739edd80ULL, unwinder.frames()[5].pc);
+  EXPECT_EQ(0x7fdd4a3ff0ULL, unwinder.frames()[5].sp);
+  EXPECT_EQ(0x5f739ee24cULL, unwinder.frames()[6].pc);
+  EXPECT_EQ(0x7fdd4a4010ULL, unwinder.frames()[6].sp);
+  EXPECT_EQ(0x5f739ee558ULL, unwinder.frames()[7].pc);
+  EXPECT_EQ(0x7fdd4a4040ULL, unwinder.frames()[7].sp);
+  EXPECT_EQ(0x5f739f2ffcULL, unwinder.frames()[8].pc);
+  EXPECT_EQ(0x7fdd4a4070ULL, unwinder.frames()[8].sp);
+  EXPECT_EQ(0x5f739f2d9cULL, unwinder.frames()[9].pc);
+  EXPECT_EQ(0x7fdd4a4100ULL, unwinder.frames()[9].sp);
+  EXPECT_EQ(0x5f739dd4e4ULL, unwinder.frames()[10].pc);
+  EXPECT_EQ(0x7fdd4a4130ULL, unwinder.frames()[10].sp);
+  EXPECT_EQ(0x71115a6a34ULL, unwinder.frames()[11].pc);
+  EXPECT_EQ(0x7fdd4a4170ULL, unwinder.frames()[11].sp);
+}
+
 }  // namespace unwindstack
diff --git a/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/libc.so b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/libc.so
new file mode 100644
index 0000000..7bb7156
--- /dev/null
+++ b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/libc.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/linker64 b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/linker64
new file mode 100644
index 0000000..00a3896
--- /dev/null
+++ b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/linker64
Binary files differ
diff --git a/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/maps.txt b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/maps.txt
new file mode 100644
index 0000000..a2babee
--- /dev/null
+++ b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/maps.txt
@@ -0,0 +1,7 @@
+5f73997000-5f739dc000 r--p 0 00:00 0   test
+5f739dc000-5f73a43000 r-xp 44000 00:00 0   test
+711152c000-711156e000 r--p 0 00:00 0   libc.so
+711156e000-7111611000 --xp 42000 00:00 0   libc.so
+7112be2000-7112be4000 r-xp 0 00:00 0   vdso
+7112be4000-7112c1c000 r--p 0 00:00 0   linker64
+7112c1c000-7112ce1000 r-xp 38000 00:00 0   linker64
diff --git a/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/regs.txt b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/regs.txt
new file mode 100644
index 0000000..3c601e1
--- /dev/null
+++ b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/regs.txt
@@ -0,0 +1,33 @@
+x0: 7112bdbc24
+x1: 0
+x2: ffffffff
+x3: 0
+x4: 0
+x5: 0
+x6: 0
+x7: 7f7f7f7f7f7f7f7f
+x8: 62
+x9: a78826643b37f4a1
+x10: 7112bdbc20
+x11: 4100
+x12: 7112bdbb70
+x13: 18
+x14: 1d6518077
+x15: 2a43148faf732a
+x16: 16fc0
+x17: 71115f61a0
+x18: 7111d6a000
+x19: 7112cef1b0
+x20: 7112bdbda0
+x21: 59616d61
+x22: 1
+x23: 7112bdbc24
+x24: 4b0e
+x25: 62
+x26: 2
+x27: 0
+x28: 7111934020
+x29: 7112bdbd90
+sp: 7112bdbbf0
+lr: 7112c394ec
+pc: 7112cb99bc
diff --git a/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/stack0.data b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/stack0.data
new file mode 100644
index 0000000..1674733
--- /dev/null
+++ b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/stack0.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/stack1.data b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/stack1.data
new file mode 100644
index 0000000..6d7b48a
--- /dev/null
+++ b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/stack1.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/test b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/test
new file mode 100644
index 0000000..3a75b8f
--- /dev/null
+++ b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/test
Binary files differ
diff --git a/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/vdso b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/vdso
new file mode 100644
index 0000000..4940916
--- /dev/null
+++ b/libunwindstack/tests/files/offline/load_bias_different_section_bias_arm64/vdso
Binary files differ
diff --git a/libutils/include/utils/Flattenable.h b/libutils/include/utils/Flattenable.h
index 9d00602..953b859 100644
--- a/libutils/include/utils/Flattenable.h
+++ b/libutils/include/utils/Flattenable.h
@@ -17,6 +17,9 @@
 #ifndef ANDROID_UTILS_FLATTENABLE_H
 #define ANDROID_UTILS_FLATTENABLE_H
 
+// DO NOT USE: please use parcelable instead
+// This code is deprecated and will not be supported via AIDL code gen. For data
+// to be sent over binder, please use parcelables.
 
 #include <stdint.h>
 #include <string.h>
@@ -28,7 +31,9 @@
 
 namespace android {
 
-
+// DO NOT USE: please use parcelable instead
+// This code is deprecated and will not be supported via AIDL code gen. For data
+// to be sent over binder, please use parcelables.
 class FlattenableUtils {
 public:
     template<size_t N>
@@ -79,7 +84,9 @@
     }
 };
 
-
+// DO NOT USE: please use parcelable instead
+// This code is deprecated and will not be supported via AIDL code gen. For data
+// to be sent over binder, please use parcelables.
 /*
  * The Flattenable protocol allows an object to serialize itself out
  * to a byte-buffer and an array of file descriptors.
@@ -131,6 +138,9 @@
     return static_cast<T*>(this)->T::unflatten(buffer, size, fds, count);
 }
 
+// DO NOT USE: please use parcelable instead
+// This code is deprecated and will not be supported via AIDL code gen. For data
+// to be sent over binder, please use parcelables.
 /*
  * LightFlattenable is a protocol allowing object to serialize themselves out
  * to a byte-buffer. Because it doesn't handle file-descriptors,
@@ -171,6 +181,9 @@
     return static_cast<T*>(this)->T::unflatten(buffer, size);
 }
 
+// DO NOT USE: please use parcelable instead
+// This code is deprecated and will not be supported via AIDL code gen. For data
+// to be sent over binder, please use parcelables.
 /*
  * LightFlattenablePod is an implementation of the LightFlattenable protocol
  * for POD (plain-old-data) objects.
diff --git a/lmkd/lmkd.c b/lmkd/lmkd.c
index e3f2bc2..9de7ff7 100644
--- a/lmkd/lmkd.c
+++ b/lmkd/lmkd.c
@@ -31,6 +31,7 @@
 #include <sys/mman.h>
 #include <sys/resource.h>
 #include <sys/socket.h>
+#include <sys/syscall.h>
 #include <sys/sysinfo.h>
 #include <sys/time.h>
 #include <sys/types.h>
@@ -139,6 +140,15 @@
 /* ro.lmk.psi_complete_stall_ms property defaults */
 #define DEF_COMPLETE_STALL 700
 
+static inline int sys_pidfd_open(pid_t pid, unsigned int flags) {
+    return syscall(__NR_pidfd_open, pid, flags);
+}
+
+static inline int sys_pidfd_send_signal(int pidfd, int sig, siginfo_t *info,
+                                        unsigned int flags) {
+    return syscall(__NR_pidfd_send_signal, pidfd, sig, info, flags);
+}
+
 /* default to old in-kernel interface if no memory pressure events */
 static bool use_inkernel_interface = true;
 static bool has_inkernel_module;
@@ -169,6 +179,11 @@
 
 static int level_oomadj[VMPRESS_LEVEL_COUNT];
 static int mpevfd[VMPRESS_LEVEL_COUNT] = { -1, -1, -1 };
+static bool pidfd_supported;
+static int last_kill_pid_or_fd = -1;
+static struct timespec last_kill_tm;
+
+/* lmkd configurable parameters */
 static bool debug_process_killing;
 static bool enable_pressure_upgrade;
 static int64_t upgrade_pressure;
@@ -197,6 +212,8 @@
     POLLING_DO_NOT_CHANGE,
     POLLING_START,
     POLLING_STOP,
+    POLLING_PAUSE,
+    POLLING_RESUME,
 };
 
 /*
@@ -207,6 +224,7 @@
  */
 struct polling_params {
     struct event_handler_info* poll_handler;
+    struct event_handler_info* paused_handler;
     struct timespec poll_start_tm;
     struct timespec last_poll_tm;
     int polling_interval_ms;
@@ -235,8 +253,11 @@
 /* vmpressure event handler data */
 static struct event_handler_info vmpressure_hinfo[VMPRESS_LEVEL_COUNT];
 
-/* 3 memory pressure levels, 1 ctrl listen socket, 2 ctrl data socket, 1 lmk events */
-#define MAX_EPOLL_EVENTS (2 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT)
+/*
+ * 1 ctrl listen socket, 2 ctrl data socket, 3 memory pressure levels,
+ * 1 lmk events + 1 fd to wait for process death
+ */
+#define MAX_EPOLL_EVENTS (1 + MAX_DATA_CONN + VMPRESS_LEVEL_COUNT + 1 + 1)
 static int epollfd;
 static int maxevents;
 
@@ -466,6 +487,7 @@
 struct proc {
     struct adjslot_list asl;
     int pid;
+    int pidfd;
     uid_t uid;
     int oomadj;
     struct proc *pidhash_next;
@@ -682,6 +704,13 @@
         prevp->pidhash_next = procp->pidhash_next;
 
     proc_unslot(procp);
+    /*
+     * Close pidfd here if we are not waiting for corresponding process to die,
+     * in which case stop_wait_for_proc_kill() will close the pidfd later
+     */
+    if (procp->pidfd >= 0 && procp->pidfd != last_kill_pid_or_fd) {
+        close(procp->pidfd);
+    }
     free(procp);
     return 0;
 }
@@ -782,15 +811,15 @@
         close(fd);
         return -1;
     }
+    line[ret] = '\0';
 
     sscanf(line, "%d %d ", &total, &rss);
     close(fd);
     return rss;
 }
 
-static char *proc_get_name(int pid) {
+static char *proc_get_name(int pid, char *buf, size_t buf_size) {
     char path[PATH_MAX];
-    static char line[LINE_MAX];
     int fd;
     char *cp;
     ssize_t ret;
@@ -801,25 +830,24 @@
     if (fd == -1) {
         return NULL;
     }
-    ret = read_all(fd, line, sizeof(line) - 1);
+    ret = read_all(fd, buf, buf_size - 1);
     close(fd);
     if (ret < 0) {
         return NULL;
     }
+    buf[ret] = '\0';
 
-    cp = strchr(line, ' ');
+    cp = strchr(buf, ' ');
     if (cp) {
         *cp = '\0';
-    } else {
-        line[ret] = '\0';
     }
 
-    return line;
+    return buf;
 }
 
 static void cmd_procprio(LMKD_CTRL_PACKET packet) {
     struct proc *procp;
-    char path[80];
+    char path[LINE_MAX];
     char val[20];
     int soft_limit_mult;
     struct lmk_procprio params;
@@ -856,7 +884,8 @@
     }
 
     if (use_inkernel_interface) {
-        stats_store_taskname(params.pid, proc_get_name(params.pid), kpoll_info.poll_fd);
+        stats_store_taskname(params.pid, proc_get_name(params.pid, path, sizeof(path)),
+                             kpoll_info.poll_fd);
         return;
     }
 
@@ -906,16 +935,27 @@
 
     procp = pid_lookup(params.pid);
     if (!procp) {
-            procp = malloc(sizeof(struct proc));
-            if (!procp) {
-                // Oh, the irony.  May need to rebuild our state.
+        int pidfd = -1;
+
+        if (pidfd_supported) {
+            pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(params.pid, 0));
+            if (pidfd < 0) {
+                ALOGE("pidfd_open for pid %d failed; errno=%d", params.pid, errno);
                 return;
             }
+        }
 
-            procp->pid = params.pid;
-            procp->uid = params.uid;
-            procp->oomadj = params.oomadj;
-            proc_insert(procp);
+        procp = calloc(1, sizeof(struct proc));
+        if (!procp) {
+            // Oh, the irony.  May need to rebuild our state.
+            return;
+        }
+
+        procp->pid = params.pid;
+        procp->pidfd = pidfd;
+        procp->uid = params.uid;
+        procp->oomadj = params.oomadj;
+        proc_insert(procp);
     } else {
         proc_unslot(procp);
         procp->oomadj = params.oomadj;
@@ -926,12 +966,12 @@
 static void cmd_procremove(LMKD_CTRL_PACKET packet) {
     struct lmk_procremove params;
 
+    lmkd_pack_get_procremove(packet, &params);
     if (use_inkernel_interface) {
         stats_remove_taskname(params.pid, kpoll_info.poll_fd);
         return;
     }
 
-    lmkd_pack_get_procremove(packet, &params);
     /*
      * WARNING: After pid_remove() procp is freed and can't be used!
      * Therefore placed at the end of the function.
@@ -1647,12 +1687,109 @@
     closedir(d);
 }
 
-static int last_killed_pid = -1;
+static bool is_kill_pending(void) {
+    char buf[24];
+
+    if (last_kill_pid_or_fd < 0) {
+        return false;
+    }
+
+    if (pidfd_supported) {
+        return true;
+    }
+
+    /* when pidfd is not supported base the decision on /proc/<pid> existence */
+    snprintf(buf, sizeof(buf), "/proc/%d/", last_kill_pid_or_fd);
+    if (access(buf, F_OK) == 0) {
+        return true;
+    }
+
+    return false;
+}
+
+static bool is_waiting_for_kill(void) {
+    return pidfd_supported && last_kill_pid_or_fd >= 0;
+}
+
+static void stop_wait_for_proc_kill(bool finished) {
+    struct epoll_event epev;
+
+    if (last_kill_pid_or_fd < 0) {
+        return;
+    }
+
+    if (debug_process_killing) {
+        struct timespec curr_tm;
+
+        if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
+            /*
+             * curr_tm is used here merely to report kill duration, so this failure is not fatal.
+             * Log an error and continue.
+             */
+            ALOGE("Failed to get current time");
+        }
+
+        if (finished) {
+            ALOGI("Process got killed in %ldms",
+                get_time_diff_ms(&last_kill_tm, &curr_tm));
+        } else {
+            ALOGI("Stop waiting for process kill after %ldms",
+                get_time_diff_ms(&last_kill_tm, &curr_tm));
+        }
+    }
+
+    if (pidfd_supported) {
+        /* unregister fd */
+        if (epoll_ctl(epollfd, EPOLL_CTL_DEL, last_kill_pid_or_fd, &epev) != 0) {
+            ALOGE("epoll_ctl for last killed process failed; errno=%d", errno);
+            return;
+        }
+        maxevents--;
+        close(last_kill_pid_or_fd);
+    }
+
+    last_kill_pid_or_fd = -1;
+}
+
+static void kill_done_handler(int data __unused, uint32_t events __unused,
+                              struct polling_params *poll_params) {
+    stop_wait_for_proc_kill(true);
+    poll_params->update = POLLING_RESUME;
+}
+
+static void start_wait_for_proc_kill(int pid_or_fd) {
+    static struct event_handler_info kill_done_hinfo = { 0, kill_done_handler };
+    struct epoll_event epev;
+
+    if (last_kill_pid_or_fd >= 0) {
+        /* Should not happen but if it does we should stop previous wait */
+        ALOGE("Attempt to wait for a kill while another wait is in progress");
+        stop_wait_for_proc_kill(false);
+    }
+
+    last_kill_pid_or_fd = pid_or_fd;
+
+    if (!pidfd_supported) {
+        /* If pidfd is not supported just store PID and exit */
+        return;
+    }
+
+    epev.events = EPOLLIN;
+    epev.data.ptr = (void *)&kill_done_hinfo;
+    if (epoll_ctl(epollfd, EPOLL_CTL_ADD, last_kill_pid_or_fd, &epev) != 0) {
+        ALOGE("epoll_ctl for last kill failed; errno=%d", errno);
+        close(last_kill_pid_or_fd);
+        last_kill_pid_or_fd = -1;
+        return;
+    }
+    maxevents++;
+}
 
 /* Kill one process specified by procp.  Returns the size of the process killed */
 static int kill_one_process(struct proc* procp, int min_oom_score, int kill_reason,
-                            const char *kill_desc, union meminfo *mi) {
+                            const char *kill_desc, union meminfo *mi, struct timespec *tm) {
     int pid = procp->pid;
+    int pidfd = procp->pidfd;
     uid_t uid = procp->uid;
     int tgid;
     char *taskname;
@@ -1660,6 +1797,7 @@
     int r;
     int result = -1;
     struct memory_stat *mem_st;
+    char buf[LINE_MAX];
 
     tgid = proc_get_tgid(pid);
     if (tgid >= 0 && tgid != pid) {
@@ -1667,7 +1805,7 @@
         goto out;
     }
 
-    taskname = proc_get_name(pid);
+    taskname = proc_get_name(pid, buf, sizeof(buf));
     if (!taskname) {
         goto out;
     }
@@ -1682,11 +1820,18 @@
     TRACE_KILL_START(pid);
 
     /* CAP_KILL required */
-    r = kill(pid, SIGKILL);
+    if (pidfd < 0) {
+        start_wait_for_proc_kill(pid);
+        r = kill(pid, SIGKILL);
+    } else {
+        start_wait_for_proc_kill(pidfd);
+        r = sys_pidfd_send_signal(pidfd, SIGKILL, NULL, 0);
+    }
 
     TRACE_KILL_END();
 
     if (r) {
+        stop_wait_for_proc_kill(false);
         ALOGE("kill(%d): errno=%d", pid, errno);
         /* Delete process record even when we fail to kill so that we don't get stuck on it */
         goto out;
@@ -1694,6 +1839,8 @@
 
     set_process_group_and_prio(pid, SP_FOREGROUND, ANDROID_PRIORITY_HIGHEST);
 
+    last_kill_tm = *tm;
+
     inc_killcnt(procp->oomadj);
 
     killinfo_log(procp, min_oom_score, tasksize, kill_reason, mi);
@@ -1706,8 +1853,6 @@
               uid, procp->oomadj, tasksize * page_k);
     }
 
-    last_killed_pid = pid;
-
     stats_write_lmk_kill_occurred(LMK_KILL_OCCURRED, uid, taskname,
             procp->oomadj, min_oom_score, tasksize, mem_st);
 
@@ -1727,7 +1872,7 @@
  * Returns size of the killed process.
  */
 static int find_and_kill_process(int min_score_adj, int kill_reason, const char *kill_desc,
-                                 union meminfo *mi) {
+                                 union meminfo *mi, struct timespec *tm) {
     int i;
     int killed_size = 0;
     bool lmk_state_change_start = false;
@@ -1742,7 +1887,7 @@
             if (!procp)
                 break;
 
-            killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc, mi);
+            killed_size = kill_one_process(procp, min_score_adj, kill_reason, kill_desc, mi, tm);
             if (killed_size >= 0) {
                 if (!lmk_state_change_start) {
                     lmk_state_change_start = true;
@@ -1821,23 +1966,6 @@
         level - 1 : level);
 }
 
-static bool is_kill_pending(void) {
-    char buf[24];
-
-    if (last_killed_pid < 0) {
-        return false;
-    }
-
-    snprintf(buf, sizeof(buf), "/proc/%d/", last_killed_pid);
-    if (access(buf, F_OK) == 0) {
-        return true;
-    }
-
-    // reset last killed PID because there's nothing pending
-    last_killed_pid = -1;
-    return false;
-}
-
 enum zone_watermark {
     WMARK_MIN = 0,
     WMARK_LOW,
@@ -1933,9 +2061,13 @@
 
     /* Skip while still killing a process */
     if (is_kill_pending()) {
-        /* TODO: replace this quick polling with pidfd polling if kernel supports */
         goto no_kill;
     }
+    /*
+     * Process is dead, stop waiting. This has no effect if pidfds are supported and
+     * death notification already caused waiting to stop.
+     */
+    stop_wait_for_proc_kill(true);
 
     if (clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm) != 0) {
         ALOGE("Failed to get current time");
@@ -2066,7 +2198,8 @@
 
     /* Kill a process if necessary */
     if (kill_reason != NONE) {
-        int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi);
+        int pages_freed = find_and_kill_process(min_score_adj, kill_reason, kill_desc, &mi,
+                                                &curr_tm);
         if (pages_freed > 0) {
             killing = true;
             if (cut_thrashing_limit) {
@@ -2080,6 +2213,13 @@
     }
 
 no_kill:
+    /* Do not poll if kernel supports pidfd waiting */
+    if (is_waiting_for_kill()) {
+        /* Pause polling if we are waiting for process death notification */
+        poll_params->update = POLLING_PAUSE;
+        return;
+    }
+
     /*
      * Start polling after initial PSI event;
      * extend polling while device is in direct reclaim or process is being killed;
@@ -2109,7 +2249,6 @@
     union meminfo mi;
     struct zoneinfo zi;
     struct timespec curr_tm;
-    static struct timespec last_kill_tm;
     static unsigned long kill_skip_count = 0;
     enum vmpressure_level level = (enum vmpressure_level)data;
     long other_free = 0, other_file = 0;
@@ -2158,15 +2297,26 @@
         return;
     }
 
-    if (kill_timeout_ms) {
-        // If we're within the timeout, see if there's pending reclaim work
-        // from the last killed process. If there is (as evidenced by
-        // /proc/<pid> continuing to exist), skip killing for now.
-        if ((get_time_diff_ms(&last_kill_tm, &curr_tm) < kill_timeout_ms) &&
-            (low_ram_device || is_kill_pending())) {
+    if (kill_timeout_ms && get_time_diff_ms(&last_kill_tm, &curr_tm) < kill_timeout_ms) {
+        /*
+         * If we're within the no-kill timeout, see if there's pending reclaim work
+         * from the last killed process. If so, skip killing for now.
+         */
+        if (is_kill_pending()) {
             kill_skip_count++;
             return;
         }
+        /*
+         * Process is dead, stop waiting. This has no effect if pidfds are supported and
+         * death notification already caused waiting to stop.
+         */
+        stop_wait_for_proc_kill(true);
+    } else {
+        /*
+         * Killing took longer than no-kill timeout. Stop waiting for the last process
+         * to die because we are ready to kill again.
+         */
+        stop_wait_for_proc_kill(false);
     }
 
     if (kill_skip_count > 0) {
@@ -2265,7 +2415,7 @@
 do_kill:
     if (low_ram_device) {
         /* For Go devices kill only one task */
-        if (find_and_kill_process(level_oomadj[level], -1, NULL, &mi) == 0) {
+        if (find_and_kill_process(level_oomadj[level], -1, NULL, &mi, &curr_tm) == 0) {
             if (debug_process_killing) {
                 ALOGI("Nothing to kill");
             }
@@ -2288,7 +2438,7 @@
             min_score_adj = level_oomadj[level];
         }
 
-        pages_freed = find_and_kill_process(min_score_adj, -1, NULL, &mi);
+        pages_freed = find_and_kill_process(min_score_adj, -1, NULL, &mi, &curr_tm);
 
         if (pages_freed == 0) {
             /* Rate limit kill reports when nothing was reclaimed */
@@ -2296,9 +2446,6 @@
                 report_skip_count++;
                 return;
             }
-        } else {
-            /* If we killed anything, update the last killed timestamp. */
-            last_kill_tm = curr_tm;
         }
 
         /* Log whenever we kill or when report rate limit allows */
@@ -2321,6 +2468,10 @@
 
         last_report_tm = curr_tm;
     }
+    if (is_waiting_for_kill()) {
+        /* pause polling if we are waiting for process death notification */
+        poll_params->update = POLLING_PAUSE;
+    }
 }
 
 static bool init_mp_psi(enum vmpressure_level level, bool use_new_strategy) {
@@ -2472,6 +2623,7 @@
         .fd = -1,
     };
     struct epoll_event epev;
+    int pidfd;
     int i;
     int ret;
 
@@ -2562,9 +2714,59 @@
         ALOGE("Failed to read %s: %s", file_data.filename, strerror(errno));
     }
 
+    /* check if kernel supports pidfd_open syscall */
+    pidfd = TEMP_FAILURE_RETRY(sys_pidfd_open(getpid(), 0));
+    if (pidfd < 0) {
+        pidfd_supported = (errno != ENOSYS);
+    } else {
+        pidfd_supported = true;
+        close(pidfd);
+    }
+    ALOGI("Process polling is %s", pidfd_supported ? "supported" : "not supported" );
+
     return 0;
 }
 
+static void call_handler(struct event_handler_info* handler_info,
+                         struct polling_params *poll_params, uint32_t events) {
+    struct timespec curr_tm;
+
+    handler_info->handler(handler_info->data, events, poll_params);
+    clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
+    poll_params->last_poll_tm = curr_tm;
+
+    switch (poll_params->update) {
+    case POLLING_START:
+        /*
+         * Poll for the duration of PSI_WINDOW_SIZE_MS after the
+         * initial PSI event because psi events are rate-limited
+         * at one per sec.
+         */
+        poll_params->poll_start_tm = curr_tm;
+        poll_params->poll_handler = handler_info;
+        break;
+    case POLLING_STOP:
+        poll_params->poll_handler = NULL;
+        break;
+    case POLLING_PAUSE:
+        poll_params->paused_handler = handler_info;
+        poll_params->poll_handler = NULL;
+        break;
+    case POLLING_RESUME:
+        poll_params->poll_start_tm = curr_tm;
+        poll_params->poll_handler = poll_params->paused_handler;
+        break;
+    case POLLING_DO_NOT_CHANGE:
+        if (get_time_diff_ms(&poll_params->poll_start_tm, &curr_tm) > PSI_WINDOW_SIZE_MS) {
+            /* Polled for the duration of PSI window, time to stop */
+            poll_params->poll_handler = NULL;
+        }
+        /* WARNING: skipping the rest of the function */
+        return;
+    }
+    poll_params->update = POLLING_DO_NOT_CHANGE;
+}
+
 static void mainloop(void) {
     struct event_handler_info* handler_info;
     struct polling_params poll_params;
@@ -2581,41 +2783,33 @@
         int i;
 
         if (poll_params.poll_handler) {
-            /* Calculate next timeout */
-            clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
-            delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
-            delay = (delay < poll_params.polling_interval_ms) ?
-                poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
-
-            /* Wait for events until the next polling timeout */
-            nevents = epoll_wait(epollfd, events, maxevents, delay);
+            bool poll_now;
 
             clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
-            if (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
-                poll_params.polling_interval_ms) {
-                /* Set input params for the call */
-                poll_params.poll_handler->handler(poll_params.poll_handler->data, 0, &poll_params);
-                poll_params.last_poll_tm = curr_tm;
+            if (poll_params.poll_handler == poll_params.paused_handler) {
+                /*
+                 * Just transitioned into POLLING_RESUME. Reset paused_handler
+                 * and poll immediately
+                 */
+                poll_params.paused_handler = NULL;
+                poll_now = true;
+                nevents = 0;
+            } else {
+                /* Calculate next timeout */
+                delay = get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm);
+                delay = (delay < poll_params.polling_interval_ms) ?
+                    poll_params.polling_interval_ms - delay : poll_params.polling_interval_ms;
 
-                if (poll_params.update != POLLING_DO_NOT_CHANGE) {
-                    switch (poll_params.update) {
-                    case POLLING_START:
-                        poll_params.poll_start_tm = curr_tm;
-                        break;
-                    case POLLING_STOP:
-                        poll_params.poll_handler = NULL;
-                        break;
-                    default:
-                        break;
-                    }
-                    poll_params.update = POLLING_DO_NOT_CHANGE;
-                } else {
-                    if (get_time_diff_ms(&poll_params.poll_start_tm, &curr_tm) >
-                        PSI_WINDOW_SIZE_MS) {
-                        /* Polled for the duration of PSI window, time to stop */
-                        poll_params.poll_handler = NULL;
-                    }
-                }
+                /* Wait for events until the next polling timeout */
+                nevents = epoll_wait(epollfd, events, maxevents, delay);
+
+                /* Update current time after wait */
+                clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
+                poll_now = (get_time_diff_ms(&poll_params.last_poll_tm, &curr_tm) >=
+                    poll_params.polling_interval_ms);
+            }
+            if (poll_now) {
+                call_handler(poll_params.poll_handler, &poll_params, 0);
             }
         } else {
             /* Wait for events with no timeout */
@@ -2655,29 +2849,7 @@
             }
             if (evt->data.ptr) {
                 handler_info = (struct event_handler_info*)evt->data.ptr;
-                /* Set input params for the call */
-                handler_info->handler(handler_info->data, evt->events, &poll_params);
-
-                if (poll_params.update != POLLING_DO_NOT_CHANGE) {
-                    switch (poll_params.update) {
-                    case POLLING_START:
-                        /*
-                         * Poll for the duration of PSI_WINDOW_SIZE_MS after the
-                         * initial PSI event because psi events are rate-limited
-                         * at one per sec.
-                         */
-                        clock_gettime(CLOCK_MONOTONIC_COARSE, &curr_tm);
-                        poll_params.poll_start_tm = poll_params.last_poll_tm = curr_tm;
-                        poll_params.poll_handler = handler_info;
-                        break;
-                    case POLLING_STOP:
-                        poll_params.poll_handler = NULL;
-                        break;
-                    default:
-                        break;
-                    }
-                    poll_params.update = POLLING_DO_NOT_CHANGE;
-                }
+                call_handler(handler_info, &poll_params, evt->events);
             }
         }
     }
diff --git a/logcat/Android.bp b/logcat/Android.bp
index f1b18b2..e6b0c7d 100644
--- a/logcat/Android.bp
+++ b/logcat/Android.bp
@@ -50,16 +50,13 @@
     ],
 }
 
-cc_prebuilt_binary {
+sh_binary {
     name: "logpersist.start",
-    srcs: ["logpersist"],
+    src: "logpersist",
     init_rc: ["logcatd.rc"],
     required: ["logcatd"],
     symlinks: [
         "logpersist.stop",
         "logpersist.cat",
     ],
-    strip: {
-        none: true,
-    },
 }
diff --git a/logd/LogAudit.cpp b/logd/LogAudit.cpp
index 665bd38..d9cc0db 100644
--- a/logd/LogAudit.cpp
+++ b/logd/LogAudit.cpp
@@ -143,10 +143,6 @@
 
 void LogAudit::auditParse(const std::string& string, uid_t uid,
                           std::string* bug_num) {
-    if (!__android_log_is_debuggable()) {
-        bug_num->assign("");
-        return;
-    }
     static std::map<std::string, std::string> denial_to_bug =
         populateDenialMap();
     std::string scontext = denialParse(string, ':', "scontext=u:object_r:");
diff --git a/rootdir/Android.mk b/rootdir/Android.mk
index c8f0a8b..5241730 100644
--- a/rootdir/Android.mk
+++ b/rootdir/Android.mk
@@ -236,12 +236,10 @@
 ifeq ($(_enforce_vndk_at_runtime),true)
 
 # for VNDK enforced devices
-LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
-include $(BUILD_SYSTEM)/base_rules.mk
-ld_config_template := $(LOCAL_PATH)/etc/ld.config.txt
-check_backward_compatibility := true
-vndk_version := $(PLATFORM_VNDK_VERSION)
-include $(LOCAL_PATH)/update_and_install_ld_config.mk
+# This file will be replaced with dynamically generated one from system/linkerconfig
+LOCAL_MODULE_STEM := $(LOCAL_MODULE)
+LOCAL_SRC_FILES := etc/ld.config.txt
+include $(BUILD_PREBUILT)
 
 else ifeq ($(_enforce_vndk_lite_at_runtime),true)
 
@@ -262,36 +260,6 @@
 
 endif  # ifeq ($(_enforce_vndk_at_runtime),true)
 
-# ld.config.txt for VNDK versions older than PLATFORM_VNDK_VERSION
-# are built with the VNDK libraries lists under /prebuilts/vndk.
-#
-# ld.config.$(VER).txt is built and installed for all VNDK versions
-# listed in PRODUCT_EXTRA_VNDK_VERSIONS.
-#
-# $(1): VNDK version
-define build_versioned_ld_config
-include $(CLEAR_VARS)
-LOCAL_MODULE := ld.config.$(1).txt
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
-LOCAL_MODULE_STEM := $$(LOCAL_MODULE)
-include $(BUILD_SYSTEM)/base_rules.mk
-ld_config_template := $(LOCAL_PATH)/etc/ld.config.txt
-check_backward_compatibility := true
-vndk_version := $(1)
-lib_list_from_prebuilts := true
-include $(LOCAL_PATH)/update_and_install_ld_config.mk
-endef
-
-vndk_snapshots := $(wildcard prebuilts/vndk/*)
-supported_vndk_snapshot_versions := \
-  $(strip $(patsubst prebuilts/vndk/v%,%,$(vndk_snapshots)))
-$(foreach ver,$(supported_vndk_snapshot_versions),\
-  $(eval $(call build_versioned_ld_config,$(ver))))
-
-vndk_snapshots :=
-supported_vndk_snapshot_versions :=
-
 #######################################
 # ld.config.vndk_lite.txt
 #
@@ -358,7 +326,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
 LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_SAMEPROCESS_LIBRARIES := $(call module-installed-files-or-guess,$(VNDK_SAMEPROCESS_LIBRARIES),.vendor)
+$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_SAMEPROCESS_LIBRARIES := $(call module-installed-files-or-guess,$(VNDK_SAMEPROCESS_LIBRARIES),.com.android.vndk.current)
 $(LOCAL_BUILT_MODULE):
 	@echo "Generate: $@"
 	@mkdir -p $(dir $@)
@@ -374,7 +342,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
 LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_CORE_LIBRARIES := $(call module-installed-files-or-guess,$(VNDK_CORE_LIBRARIES),.vendor)
+$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_CORE_LIBRARIES := $(call module-installed-files-or-guess,$(VNDK_CORE_LIBRARIES),.com.android.vndk.current)
 $(LOCAL_BUILT_MODULE):
 	@echo "Generate: $@"
 	@mkdir -p $(dir $@)
@@ -390,7 +358,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
 LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
 include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_PRIVATE_LIBRARIES := $(call module-installed-files-or-guess,$(VNDK_PRIVATE_LIBRARIES),.vendor)
+$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_PRIVATE_LIBRARIES := $(call module-installed-files-or-guess,$(VNDK_PRIVATE_LIBRARIES),.com.android.vndk.current)
 $(LOCAL_BUILT_MODULE):
 	@echo "Generate: $@"
 	@mkdir -p $(dir $@)
diff --git a/rootdir/etc/ld.config.legacy.txt b/rootdir/etc/ld.config.legacy.txt
index bb8d4d0..a99756a 100644
--- a/rootdir/etc/ld.config.legacy.txt
+++ b/rootdir/etc/ld.config.legacy.txt
@@ -42,29 +42,29 @@
 # APEX related namespaces.
 ###############################################################################
 
-additional.namespaces = runtime,conscrypt,media,neuralnetworks,resolv
+additional.namespaces = art,conscrypt,media,neuralnetworks,resolv
 
 # Keep in sync with the "platform" namespace in art/build/apex/ld.config.txt.
 # If a shared library or an executable requests a shared library that
 # cannot be loaded into the default namespace, the dynamic linker tries
-# to load the shared library from the runtime namespace. And then, if the
-# shared library cannot be loaded from the runtime namespace either, the
+# to load the shared library from the art namespace. And then, if the
+# shared library cannot be loaded from the art namespace either, the
 # dynamic linker tries to load the shared library from the resolv namespace.
 # Finally, if all attempts fail, the dynamic linker returns an error.
-namespace.default.links = runtime,resolv,neuralnetworks
-namespace.default.asan.links = runtime,resolv,neuralnetworks
-namespace.default.link.runtime.shared_libs  = libandroidicu.so
-namespace.default.link.runtime.shared_libs += libdexfile_external.so
-namespace.default.link.runtime.shared_libs += libdexfiled_external.so
+namespace.default.links = art,resolv,neuralnetworks
+namespace.default.asan.links = art,resolv,neuralnetworks
+namespace.default.link.art.shared_libs  = libandroidicu.so
+namespace.default.link.art.shared_libs += libdexfile_external.so
+namespace.default.link.art.shared_libs += libdexfiled_external.so
 # TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
-namespace.default.link.runtime.shared_libs += libicui18n.so
-namespace.default.link.runtime.shared_libs += libicuuc.so
-namespace.default.link.runtime.shared_libs += libnativebridge.so
-namespace.default.link.runtime.shared_libs += libnativehelper.so
-namespace.default.link.runtime.shared_libs += libnativeloader.so
+namespace.default.link.art.shared_libs += libicui18n.so
+namespace.default.link.art.shared_libs += libicuuc.so
+namespace.default.link.art.shared_libs += libnativebridge.so
+namespace.default.link.art.shared_libs += libnativehelper.so
+namespace.default.link.art.shared_libs += libnativeloader.so
 
 # TODO(b/122876336): Remove libpac.so once it's migrated to Webview
-namespace.default.link.runtime.shared_libs += libpac.so
+namespace.default.link.art.shared_libs += libpac.so
 
 # When libnetd_resolv.so can't be found in the default namespace, search for it
 # in the resolv namespace. Don't allow any other libraries from the resolv namespace
@@ -75,25 +75,25 @@
 namespace.default.link.neuralnetworks.shared_libs = libneuralnetworks.so
 
 ###############################################################################
-# "runtime" APEX namespace
+# "art" APEX namespace
 #
-# This namespace exposes externally accessible libraries from the Runtime APEX.
-# Keep in sync with the "runtime" namespace in art/build/apex/ld.config.txt.
+# This namespace exposes externally accessible libraries from the ART APEX.
+# Keep in sync with the "art" namespace in art/build/apex/ld.config.txt.
 ###############################################################################
-# TODO(b/139408016): Rename this namespace to "art".
-namespace.runtime.isolated = true
+namespace.art.isolated = true
 # Visible to allow links to be created at runtime, e.g. through
 # android_link_namespaces in libnativeloader.
-namespace.runtime.visible = true
+namespace.art.visible = true
 
-namespace.runtime.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.asan.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.links = default
+namespace.art.search.paths = /apex/com.android.art/${LIB}
+namespace.art.asan.search.paths = /apex/com.android.art/${LIB}
+namespace.art.links = default,neuralnetworks
 # Need allow_all_shared_libs because libart.so can dlopen oat files in
 # /system/framework and /data.
 # TODO(b/130340935): Use a dynamically created linker namespace similar to
 # classloader-namespace for oat files, and tighten this up.
-namespace.runtime.link.default.allow_all_shared_libs = true
+namespace.art.link.default.allow_all_shared_libs = true
+namespace.art.link.neuralnetworks.shared_libs = libneuralnetworks.so
 
 ###############################################################################
 # "media" APEX namespace
@@ -136,8 +136,8 @@
 
 namespace.conscrypt.search.paths = /apex/com.android.conscrypt/${LIB}
 namespace.conscrypt.asan.search.paths = /apex/com.android.conscrypt/${LIB}
-namespace.conscrypt.links = runtime,default
-namespace.conscrypt.link.runtime.shared_libs  = libandroidio.so
+namespace.conscrypt.links = art,default
+namespace.conscrypt.link.art.shared_libs = libandroidio.so
 namespace.conscrypt.link.default.shared_libs  = libc.so
 namespace.conscrypt.link.default.shared_libs += libm.so
 namespace.conscrypt.link.default.shared_libs += libdl.so
diff --git a/rootdir/etc/ld.config.txt b/rootdir/etc/ld.config.txt
index 60035aa..5c87843 100644
--- a/rootdir/etc/ld.config.txt
+++ b/rootdir/etc/ld.config.txt
@@ -1,803 +1,3 @@
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Bionic loader config file.
-#
-
-# Don't change the order here. The first pattern that matches with the
-# absolute path of an executable is selected.
-dir.system = /system/bin/
-dir.system = /system/xbin/
-dir.system = /%SYSTEM_EXT%/bin/
-dir.system = /%PRODUCT%/bin/
-
-dir.vendor = /odm/bin/
-dir.vendor = /vendor/bin/
-dir.vendor = /data/nativetest/odm
-dir.vendor = /data/nativetest64/odm
-dir.vendor = /data/benchmarktest/odm
-dir.vendor = /data/benchmarktest64/odm
-dir.vendor = /data/nativetest/vendor
-dir.vendor = /data/nativetest64/vendor
-dir.vendor = /data/benchmarktest/vendor
-dir.vendor = /data/benchmarktest64/vendor
-
-dir.unrestricted = /data/nativetest/unrestricted
-dir.unrestricted = /data/nativetest64/unrestricted
-
-# TODO(b/123864775): Ensure tests are run from /data/nativetest{,64} or (if
-# necessary) the unrestricted subdirs above. Then clean this up.
-dir.unrestricted = /data/local/tmp
-
-dir.postinstall = /postinstall
-
-# Fallback entry to provide APEX namespace lookups for binaries anywhere else.
-# This must be last.
-dir.system = /data
-
-[system]
-additional.namespaces = runtime,conscrypt,media,neuralnetworks,resolv,sphal,vndk,rs
-
-###############################################################################
-# "default" namespace
-#
-# Framework-side code runs in this namespace. Libs from /vendor partition
-# can't be loaded in this namespace.
-###############################################################################
-namespace.default.isolated = true
-# Visible to allow links to be created at runtime, e.g. through
-# android_link_namespaces in libnativeloader.
-namespace.default.visible = true
-
-namespace.default.search.paths  = /system/${LIB}
-namespace.default.search.paths += /%SYSTEM_EXT%/${LIB}
-namespace.default.search.paths += /%PRODUCT%/${LIB}
-
-# We can't have entire /system/${LIB} as permitted paths because doing so
-# makes it possible to load libs in /system/${LIB}/vndk* directories by
-# their absolute paths (e.g. dlopen("/system/lib/vndk/libbase.so");).
-# VNDK libs are built with previous versions of Android and thus must not be
-# loaded into this namespace where libs built with the current version of
-# Android are loaded. Mixing the two types of libs in the same namespace can
-# cause unexpected problem.
-namespace.default.permitted.paths  = /system/${LIB}/drm
-namespace.default.permitted.paths += /system/${LIB}/extractors
-namespace.default.permitted.paths += /system/${LIB}/hw
-namespace.default.permitted.paths += /%SYSTEM_EXT%/${LIB}
-namespace.default.permitted.paths += /%PRODUCT%/${LIB}
-# These are where odex files are located. libart has to be able to dlopen the files
-namespace.default.permitted.paths += /system/framework
-namespace.default.permitted.paths += /system/app
-namespace.default.permitted.paths += /system/priv-app
-namespace.default.permitted.paths += /%SYSTEM_EXT%/framework
-namespace.default.permitted.paths += /%SYSTEM_EXT%/app
-namespace.default.permitted.paths += /%SYSTEM_EXT%/priv-app
-namespace.default.permitted.paths += /vendor/framework
-namespace.default.permitted.paths += /vendor/app
-namespace.default.permitted.paths += /vendor/priv-app
-namespace.default.permitted.paths += /system/vendor/framework
-namespace.default.permitted.paths += /system/vendor/app
-namespace.default.permitted.paths += /system/vendor/priv-app
-namespace.default.permitted.paths += /odm/framework
-namespace.default.permitted.paths += /odm/app
-namespace.default.permitted.paths += /odm/priv-app
-namespace.default.permitted.paths += /oem/app
-namespace.default.permitted.paths += /%PRODUCT%/framework
-namespace.default.permitted.paths += /%PRODUCT%/app
-namespace.default.permitted.paths += /%PRODUCT%/priv-app
-namespace.default.permitted.paths += /data
-namespace.default.permitted.paths += /mnt/expand
-namespace.default.permitted.paths += /apex/com.android.runtime/${LIB}/bionic
-namespace.default.permitted.paths += /system/${LIB}/bootstrap
-
-namespace.default.asan.search.paths  = /data/asan/system/${LIB}
-namespace.default.asan.search.paths +=           /system/${LIB}
-namespace.default.asan.search.paths += /data/asan/%SYSTEM_EXT%/${LIB}
-namespace.default.asan.search.paths +=           /%SYSTEM_EXT%/${LIB}
-namespace.default.asan.search.paths += /data/asan/%PRODUCT%/${LIB}
-namespace.default.asan.search.paths +=           /%PRODUCT%/${LIB}
-
-namespace.default.asan.permitted.paths  = /data
-namespace.default.asan.permitted.paths += /system/${LIB}/drm
-namespace.default.asan.permitted.paths += /system/${LIB}/extractors
-namespace.default.asan.permitted.paths += /system/${LIB}/hw
-namespace.default.asan.permitted.paths += /system/framework
-namespace.default.asan.permitted.paths += /system/app
-namespace.default.asan.permitted.paths += /system/priv-app
-namespace.default.asan.permitted.paths += /%SYSTEM_EXT%/${LIB}
-namespace.default.asan.permitted.paths += /%SYSTEM_EXT%/framework
-namespace.default.asan.permitted.paths += /%SYSTEM_EXT%/app
-namespace.default.asan.permitted.paths += /%SYSTEM_EXT%/priv-app
-namespace.default.asan.permitted.paths += /vendor/framework
-namespace.default.asan.permitted.paths += /vendor/app
-namespace.default.asan.permitted.paths += /vendor/priv-app
-namespace.default.asan.permitted.paths += /system/vendor/framework
-namespace.default.asan.permitted.paths += /system/vendor/app
-namespace.default.asan.permitted.paths += /system/vendor/priv-app
-namespace.default.asan.permitted.paths += /odm/framework
-namespace.default.asan.permitted.paths += /odm/app
-namespace.default.asan.permitted.paths += /odm/priv-app
-namespace.default.asan.permitted.paths += /oem/app
-namespace.default.asan.permitted.paths += /%PRODUCT%/${LIB}
-namespace.default.asan.permitted.paths += /%PRODUCT%/framework
-namespace.default.asan.permitted.paths += /%PRODUCT%/app
-namespace.default.asan.permitted.paths += /%PRODUCT%/priv-app
-namespace.default.asan.permitted.paths += /mnt/expand
-namespace.default.asan.permitted.paths += /apex/com.android.runtime/${LIB}/bionic
-namespace.default.asan.permitted.paths += /system/${LIB}/bootstrap
-
-# Keep in sync with the "platform" namespace in art/build/apex/ld.config.txt.
-# If a shared library or an executable requests a shared library that
-# cannot be loaded into the default namespace, the dynamic linker tries
-# to load the shared library from the runtime namespace. And then, if the
-# shared library cannot be loaded from the runtime namespace either, the
-# dynamic linker tries to load the shared library from the resolv namespace.
-# Finally, if all attempts fail, the dynamic linker returns an error.
-namespace.default.links = runtime,resolv,neuralnetworks
-namespace.default.link.runtime.shared_libs  = libandroidicu.so
-namespace.default.link.runtime.shared_libs += libdexfile_external.so
-namespace.default.link.runtime.shared_libs += libdexfiled_external.so
-# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
-namespace.default.link.runtime.shared_libs += libicui18n.so
-namespace.default.link.runtime.shared_libs += libicuuc.so
-namespace.default.link.runtime.shared_libs += libnativebridge.so
-namespace.default.link.runtime.shared_libs += libnativehelper.so
-namespace.default.link.runtime.shared_libs += libnativeloader.so
-
-# TODO(b/122876336): Remove libpac.so once it's migrated to Webview
-namespace.default.link.runtime.shared_libs += libpac.so
-namespace.default.link.runtime.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-
-# When libnetd_resolv.so can't be found in the default namespace, search for it
-# in the resolv namespace. Don't allow any other libraries from the resolv namespace
-# to be loaded in the default namespace.
-namespace.default.link.resolv.shared_libs = libnetd_resolv.so
-
-# LLNDK library moved into apex
-namespace.default.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-###############################################################################
-# "runtime" APEX namespace
-#
-# This namespace exposes externally accessible libraries from the Runtime APEX.
-# Keep in sync with the "runtime" namespace in art/build/apex/ld.config.txt.
-###############################################################################
-# TODO(b/139408016): Rename this namespace to "art".
-namespace.runtime.isolated = true
-# Visible to allow links to be created at runtime, e.g. through
-# android_link_namespaces in libnativeloader.
-namespace.runtime.visible = true
-
-namespace.runtime.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.asan.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.links = default
-# Need allow_all_shared_libs because libart.so can dlopen oat files in
-# /system/framework and /data.
-# TODO(b/130340935): Use a dynamically created linker namespace similar to
-# classloader-namespace for oat files, and tighten this up.
-namespace.runtime.link.default.allow_all_shared_libs = true
-
-###############################################################################
-# "media" APEX namespace
-#
-# This namespace is for libraries within the media APEX.
-###############################################################################
-namespace.media.isolated = true
-namespace.media.visible = true
-
-namespace.media.search.paths = /apex/com.android.media/${LIB}
-namespace.media.asan.search.paths = /apex/com.android.media/${LIB}
-
-namespace.media.permitted.paths = /apex/com.android.media/${LIB}/extractors
-namespace.media.asan.permitted.paths = /apex/com.android.media/${LIB}/extractors
-
-namespace.media.links = default,neuralnetworks
-namespace.media.link.default.shared_libs  = %LLNDK_LIBRARIES%
-namespace.media.link.default.shared_libs += libbinder_ndk.so
-namespace.media.link.default.shared_libs += libcgrouprc.so
-namespace.media.link.default.shared_libs += libmediametrics.so
-namespace.media.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-
-# LLNDK library moved into apex
-namespace.media.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-###############################################################################
-# "conscrypt" APEX namespace
-#
-# This namespace is for libraries within the conscrypt APEX.
-# Keep in sync with the "conscrypt" namespace in art/build/apex/ld.config.txt.
-###############################################################################
-namespace.conscrypt.isolated = true
-namespace.conscrypt.visible = true
-
-namespace.conscrypt.search.paths = /apex/com.android.conscrypt/${LIB}
-namespace.conscrypt.asan.search.paths = /apex/com.android.conscrypt/${LIB}
-namespace.conscrypt.links = runtime,default
-namespace.conscrypt.link.runtime.shared_libs  = libandroidio.so
-namespace.conscrypt.link.default.shared_libs  = libc.so
-namespace.conscrypt.link.default.shared_libs += libm.so
-namespace.conscrypt.link.default.shared_libs += libdl.so
-namespace.conscrypt.link.default.shared_libs += liblog.so
-
-###############################################################################
-# "resolv" APEX namespace
-#
-# This namespace is for libraries within the resolv APEX.
-###############################################################################
-namespace.resolv.isolated = true
-namespace.resolv.visible = true
-
-namespace.resolv.search.paths = /apex/com.android.resolv/${LIB}
-namespace.resolv.asan.search.paths = /apex/com.android.resolv/${LIB}
-namespace.resolv.links = default
-namespace.resolv.link.default.shared_libs  = libc.so
-namespace.resolv.link.default.shared_libs += libcgrouprc.so
-namespace.resolv.link.default.shared_libs += libm.so
-namespace.resolv.link.default.shared_libs += libdl.so
-namespace.resolv.link.default.shared_libs += libbinder_ndk.so
-namespace.resolv.link.default.shared_libs += liblog.so
-namespace.resolv.link.default.shared_libs += libvndksupport.so
-
-###############################################################################
-# "sphal" namespace
-#
-# SP-HAL(Sameprocess-HAL)s are the only vendor libraries that are allowed to be
-# loaded inside system processes. libEGL_<chipset>.so, libGLESv2_<chipset>.so,
-# android.hardware.graphics.mapper@2.0-impl.so, etc are SP-HALs.
-#
-# This namespace is exclusivly for SP-HALs. When the framework tries to dynami-
-# cally load SP-HALs, android_dlopen_ext() is used to explicitly specifying
-# that they should be searched and loaded from this namespace.
-#
-# Note that there is no link from the default namespace to this namespace.
-###############################################################################
-namespace.sphal.isolated = true
-# Visible to allow links to be created at runtime, e.g. through
-# android_link_namespaces in libnativeloader.
-namespace.sphal.visible = true
-
-namespace.sphal.search.paths  = /odm/${LIB}
-namespace.sphal.search.paths += /vendor/${LIB}
-namespace.sphal.search.paths += /vendor/${LIB}/hw
-
-namespace.sphal.permitted.paths  = /odm/${LIB}
-namespace.sphal.permitted.paths += /vendor/${LIB}
-namespace.sphal.permitted.paths += /system/vendor/${LIB}
-
-namespace.sphal.asan.search.paths  = /data/asan/odm/${LIB}
-namespace.sphal.asan.search.paths +=           /odm/${LIB}
-namespace.sphal.asan.search.paths += /data/asan/vendor/${LIB}
-namespace.sphal.asan.search.paths +=           /vendor/${LIB}
-
-namespace.sphal.asan.permitted.paths  = /data/asan/odm/${LIB}
-namespace.sphal.asan.permitted.paths +=           /odm/${LIB}
-namespace.sphal.asan.permitted.paths += /data/asan/vendor/${LIB}
-namespace.sphal.asan.permitted.paths +=           /vendor/${LIB}
-
-# Once in this namespace, access to libraries in /system/lib is restricted. Only
-# libs listed here can be used. Order is important here as the namespaces are
-# tried in this order. rs should be before vndk because both are capable
-# of loading libRS_internal.so
-namespace.sphal.links = rs,default,vndk,neuralnetworks
-
-# Renderscript gets separate namespace
-namespace.sphal.link.rs.shared_libs = libRS_internal.so
-
-namespace.sphal.link.default.shared_libs  = %LLNDK_LIBRARIES%
-namespace.sphal.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-
-namespace.sphal.link.vndk.shared_libs = %VNDK_SAMEPROCESS_LIBRARIES%
-
-# LLNDK library moved into apex
-namespace.sphal.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-
-###############################################################################
-# "rs" namespace
-#
-# This namespace is exclusively for Renderscript internal libraries.
-# This namespace has slightly looser restriction than the vndk namespace because
-# of the genuine characteristics of Renderscript; /data is in the permitted path
-# to load the compiled *.so file and libmediandk.so can be used here.
-###############################################################################
-namespace.rs.isolated = true
-namespace.rs.visible = true
-
-namespace.rs.search.paths  = /odm/${LIB}/vndk-sp
-namespace.rs.search.paths += /vendor/${LIB}/vndk-sp
-namespace.rs.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
-namespace.rs.search.paths += /odm/${LIB}
-namespace.rs.search.paths += /vendor/${LIB}
-
-namespace.rs.permitted.paths  = /odm/${LIB}
-namespace.rs.permitted.paths += /vendor/${LIB}
-namespace.rs.permitted.paths += /system/vendor/${LIB}
-namespace.rs.permitted.paths += /data
-
-namespace.rs.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp
-namespace.rs.asan.search.paths +=           /odm/${LIB}/vndk-sp
-namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
-namespace.rs.asan.search.paths +=           /vendor/${LIB}/vndk-sp
-namespace.rs.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
-namespace.rs.asan.search.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%
-namespace.rs.asan.search.paths += /data/asan/odm/${LIB}
-namespace.rs.asan.search.paths +=           /odm/${LIB}
-namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}
-namespace.rs.asan.search.paths +=           /vendor/${LIB}
-
-namespace.rs.asan.permitted.paths  = /data/asan/odm/${LIB}
-namespace.rs.asan.permitted.paths +=           /odm/${LIB}
-namespace.rs.asan.permitted.paths += /data/asan/vendor/${LIB}
-namespace.rs.asan.permitted.paths +=           /vendor/${LIB}
-namespace.rs.asan.permitted.paths += /data
-
-namespace.rs.links = default,neuralnetworks
-
-namespace.rs.link.default.shared_libs  = %LLNDK_LIBRARIES%
-namespace.rs.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-# Private LLNDK libs (e.g. libft2.so) are exceptionally allowed to this
-# namespace because RS framework libs are using them.
-namespace.rs.link.default.shared_libs += %PRIVATE_LLNDK_LIBRARIES%
-
-# LLNDK library moved into apex
-namespace.rs.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-
-###############################################################################
-# "vndk" namespace
-#
-# This namespace is exclusively for vndk-sp libs.
-###############################################################################
-namespace.vndk.isolated = true
-# Visible to allow links to be created at runtime, e.g. through
-# android_link_namespaces in libnativeloader.
-namespace.vndk.visible = true
-
-namespace.vndk.search.paths  = /odm/${LIB}/vndk-sp
-namespace.vndk.search.paths += /vendor/${LIB}/vndk-sp
-namespace.vndk.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
-
-namespace.vndk.permitted.paths  = /odm/${LIB}/hw
-namespace.vndk.permitted.paths += /odm/${LIB}/egl
-namespace.vndk.permitted.paths += /vendor/${LIB}/hw
-namespace.vndk.permitted.paths += /vendor/${LIB}/egl
-namespace.vndk.permitted.paths += /system/vendor/${LIB}/hw
-namespace.vndk.permitted.paths += /system/vendor/${LIB}/egl
-# This is exceptionally required since android.hidl.memory@1.0-impl.so is here
-namespace.vndk.permitted.paths += /system/${LIB}/vndk-sp%VNDK_VER%/hw
-
-namespace.vndk.asan.search.paths  = /data/asan/odm/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths +=           /odm/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths +=           /vendor/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
-namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%
-
-namespace.vndk.asan.permitted.paths  = /data/asan/odm/${LIB}/hw
-namespace.vndk.asan.permitted.paths +=           /odm/${LIB}/hw
-namespace.vndk.asan.permitted.paths += /data/asan/odm/${LIB}/egl
-namespace.vndk.asan.permitted.paths +=           /odm/${LIB}/egl
-namespace.vndk.asan.permitted.paths += /data/asan/vendor/${LIB}/hw
-namespace.vndk.asan.permitted.paths +=           /vendor/${LIB}/hw
-namespace.vndk.asan.permitted.paths += /data/asan/vendor/${LIB}/egl
-namespace.vndk.asan.permitted.paths +=           /vendor/${LIB}/egl
-
-namespace.vndk.asan.permitted.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%/hw
-namespace.vndk.asan.permitted.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%/hw
-
-# The "vndk" namespace links to "default" namespace for LLNDK libs and links to
-# "sphal" namespace for vendor libs.  The ordering matters.  The "default"
-# namespace has higher priority than the "sphal" namespace.
-namespace.vndk.links = default,sphal,runtime,neuralnetworks
-
-# When these NDK libs are required inside this namespace, then it is redirected
-# to the default namespace. This is possible since their ABI is stable across
-# Android releases.
-namespace.vndk.link.default.shared_libs  = %LLNDK_LIBRARIES%
-namespace.vndk.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-
-namespace.vndk.link.runtime.shared_libs = %SANITIZER_RUNTIME_LIBRARIES%
-
-# Allow VNDK-SP extensions to use vendor libraries
-namespace.vndk.link.sphal.allow_all_shared_libs = true
-
-# LLNDK library moved into apex
-namespace.vndk.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-###############################################################################
-# "neuralnetworks" APEX namespace
-#
-# This namespace is for libraries within the NNAPI APEX.
-###############################################################################
-namespace.neuralnetworks.isolated = true
-namespace.neuralnetworks.visible = true
-
-namespace.neuralnetworks.search.paths = /apex/com.android.neuralnetworks/${LIB}
-namespace.neuralnetworks.asan.search.paths = /apex/com.android.neuralnetworks/${LIB}
-namespace.neuralnetworks.links = default
-namespace.neuralnetworks.link.default.shared_libs  = libc.so
-namespace.neuralnetworks.link.default.shared_libs += libcgrouprc.so
-namespace.neuralnetworks.link.default.shared_libs += libdl.so
-namespace.neuralnetworks.link.default.shared_libs += liblog.so
-namespace.neuralnetworks.link.default.shared_libs += libm.so
-namespace.neuralnetworks.link.default.shared_libs += libnativewindow.so
-namespace.neuralnetworks.link.default.shared_libs += libneuralnetworks_packageinfo.so
-namespace.neuralnetworks.link.default.shared_libs += libsync.so
-namespace.neuralnetworks.link.default.shared_libs += libvndksupport.so
-
-###############################################################################
-# Namespace config for vendor processes. In O, no restriction is enforced for
-# them. However, in O-MR1, access to /system/${LIB} will not be allowed to
-# the default namespace. 'system' namespace will be added to give limited
-# (LL-NDK only) access.
-###############################################################################
-[vendor]
-additional.namespaces = runtime,system,neuralnetworks,vndk%VNDK_IN_SYSTEM_NS%
-
-###############################################################################
-# "default" namespace
-#
-# This is the default linker namespace for a vendor process (a process started
-# from /vendor/bin/*). The main executable and the libs under /vendor/lib[64]
-# are loaded directly into this namespace. However, other libs under the system
-# partition (VNDK and LLNDK libraries) are not loaded here but from the
-# separate namespace 'system'. The delegation to the system namespace is done
-# via the 'namespace.default.link.system.shared_libs' property below.
-#
-# '#VNDK27#' TAG is only for building ld.config.27.txt for backward
-# compatibility. (TODO:b/123390078) Move them to a separate file.
-###############################################################################
-namespace.default.isolated = true
-namespace.default.visible = true
-
-namespace.default.search.paths  = /odm/${LIB}
-namespace.default.search.paths += /vendor/${LIB}
-
-namespace.default.permitted.paths  = /odm
-namespace.default.permitted.paths += /vendor
-namespace.default.permitted.paths += /system/vendor
-#VNDK27#namespace.default.search.paths += /vendor/${LIB}/hw
-#VNDK27#namespace.default.search.paths += /vendor/${LIB}/egl
-
-namespace.default.asan.search.paths  = /data/asan/odm/${LIB}
-namespace.default.asan.search.paths +=           /odm/${LIB}
-namespace.default.asan.search.paths += /data/asan/vendor/${LIB}
-namespace.default.asan.search.paths +=           /vendor/${LIB}
-#VNDK27#namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/hw
-#VNDK27#namespace.default.asan.search.paths +=           /vendor/${LIB}/hw
-#VNDK27#namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/egl
-#VNDK27#namespace.default.asan.search.paths +=           /vendor/${LIB}/egl
-
-namespace.default.asan.permitted.paths  = /data/asan/odm
-namespace.default.asan.permitted.paths +=           /odm
-namespace.default.asan.permitted.paths += /data/asan/vendor
-namespace.default.asan.permitted.paths +=           /vendor
-
-namespace.default.links = system,vndk%VNDK_IN_SYSTEM_NS%,runtime,neuralnetworks
-namespace.default.link.runtime.shared_libs = %SANITIZER_RUNTIME_LIBRARIES%
-namespace.default.link.system.shared_libs  = %LLNDK_LIBRARIES%
-namespace.default.link.system.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-namespace.default.link.vndk_in_system.shared_libs = %VNDK_USING_CORE_VARIANT_LIBRARIES%
-namespace.default.link.vndk.shared_libs  = %VNDK_SAMEPROCESS_LIBRARIES%
-namespace.default.link.vndk.shared_libs += %VNDK_CORE_LIBRARIES%
-
-# LLNDK library moved into apex
-namespace.default.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-###############################################################################
-# "runtime" APEX namespace
-#
-# This namespace exposes externally accessible libraries from the Runtime APEX.
-# Keep in sync with the "runtime" namespace in art/build/apex/ld.config.txt.
-###############################################################################
-# TODO(b/139408016): Rename this namespace to "art".
-namespace.runtime.isolated = true
-
-namespace.runtime.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.asan.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.links = system
-# TODO(b/130340935): Use a dynamically created linker namespace similar to
-# classloader-namespace for oat files, and tighten this up.
-namespace.runtime.link.system.allow_all_shared_libs = true
-
-
-###############################################################################
-# "vndk" namespace
-#
-# This namespace is where VNDK and VNDK-SP libraries are loaded for
-# a vendor process.
-###############################################################################
-namespace.vndk.isolated = false
-
-namespace.vndk.search.paths  = /odm/${LIB}/vndk
-namespace.vndk.search.paths += /odm/${LIB}/vndk-sp
-namespace.vndk.search.paths += /vendor/${LIB}/vndk
-namespace.vndk.search.paths += /vendor/${LIB}/vndk-sp
-namespace.vndk.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
-namespace.vndk.search.paths += /system/${LIB}/vndk%VNDK_VER%
-
-namespace.vndk.asan.search.paths  = /data/asan/odm/${LIB}/vndk
-namespace.vndk.asan.search.paths +=           /odm/${LIB}/vndk
-namespace.vndk.asan.search.paths += /data/asan/odm/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths +=           /odm/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths += /data/asan/vendor/${LIB}/vndk
-namespace.vndk.asan.search.paths +=           /vendor/${LIB}/vndk
-namespace.vndk.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths +=           /vendor/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
-namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk-sp%VNDK_VER%
-namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk%VNDK_VER%
-namespace.vndk.asan.search.paths +=           /system/${LIB}/vndk%VNDK_VER%
-
-# When these NDK libs are required inside this namespace, then it is redirected
-# to the system namespace. This is possible since their ABI is stable across
-# Android releases.  The links here should be identical to that of the
-# 'vndk_in_system' namespace, except for the link between 'vndk' and
-# 'vndk_in_system'.
-namespace.vndk.links = system,default%VNDK_IN_SYSTEM_NS%,runtime,neuralnetworks
-
-namespace.vndk.link.system.shared_libs  = %LLNDK_LIBRARIES%
-namespace.vndk.link.system.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-
-namespace.vndk.link.default.allow_all_shared_libs = true
-
-namespace.vndk.link.runtime.shared_libs = %SANITIZER_RUNTIME_LIBRARIES%
-
-namespace.vndk.link.vndk_in_system.shared_libs = %VNDK_USING_CORE_VARIANT_LIBRARIES%
-
-# LLNDK library moved into apex
-namespace.vndk.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-###############################################################################
-# "system" namespace
-#
-# This namespace is where system libs (VNDK and LLNDK libs) are loaded for
-# a vendor process.
-###############################################################################
-namespace.system.isolated = false
-
-namespace.system.search.paths  = /system/${LIB}
-namespace.system.search.paths += /%SYSTEM_EXT%/${LIB}
-namespace.system.search.paths += /%PRODUCT%/${LIB}
-
-namespace.system.asan.search.paths  = /data/asan/system/${LIB}
-namespace.system.asan.search.paths +=           /system/${LIB}
-namespace.system.asan.search.paths += /data/asan/%SYSTEM_EXT%/${LIB}
-namespace.system.asan.search.paths +=           /%SYSTEM_EXT%/${LIB}
-namespace.system.asan.search.paths += /data/asan/%PRODUCT%/${LIB}
-namespace.system.asan.search.paths +=           /%PRODUCT%/${LIB}
-
-namespace.system.links = runtime
-namespace.system.link.runtime.shared_libs  = libdexfile_external.so
-namespace.system.link.runtime.shared_libs += libdexfiled_external.so
-# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
-namespace.system.link.runtime.shared_libs += libicui18n.so
-namespace.system.link.runtime.shared_libs += libicuuc.so
-namespace.system.link.runtime.shared_libs += libnativebridge.so
-namespace.system.link.runtime.shared_libs += libnativehelper.so
-namespace.system.link.runtime.shared_libs += libnativeloader.so
-# Workaround for b/124772622
-namespace.system.link.runtime.shared_libs += libandroidicu.so
-namespace.system.link.runtime.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-
-###############################################################################
-# "vndk_in_system" namespace
-#
-# This namespace is where no-vendor-variant VNDK libraries are loaded for a
-# vendor process.  Note that we do not simply export these libraries from
-# "system" namespace, because in some case both the core variant and the
-# vendor variant of a VNDK library may be loaded.  In such case, we do not
-# want to eliminate double-loading because doing so means the global states
-# of the library would be shared.
-#
-# Only the no-vendor-variant VNDK libraries are whitelisted in this namespace.
-# This is to ensure that we do not load libraries needed by no-vendor-variant
-# VNDK libraries into vndk_in_system namespace.
-###############################################################################
-namespace.vndk_in_system.isolated = true
-namespace.vndk_in_system.visible = true
-
-# The search paths here should be kept the same as that of the 'system'
-# namespace.
-namespace.vndk_in_system.search.paths  = /system/${LIB}
-namespace.vndk_in_system.search.paths += /%SYSTEM_EXT%/${LIB}
-namespace.vndk_in_system.search.paths += /%PRODUCT%/${LIB}
-
-namespace.vndk_in_system.asan.search.paths  = /data/asan/system/${LIB}
-namespace.vndk_in_system.asan.search.paths +=           /system/${LIB}
-namespace.vndk_in_system.asan.search.paths += /data/asan/%SYSTEM_EXT%/${LIB}
-namespace.vndk_in_system.asan.search.paths +=           /%SYSTEM_EXT%/${LIB}
-namespace.vndk_in_system.asan.search.paths += /data/asan/%PRODUCT%/${LIB}
-namespace.vndk_in_system.asan.search.paths +=           /%PRODUCT%/${LIB}
-
-namespace.vndk_in_system.whitelisted = %VNDK_USING_CORE_VARIANT_LIBRARIES%
-
-# The links here should be identical to that of the 'vndk' namespace, with the
-# following exception:
-#   1. 'vndk_in_system' needs to be freely linked back to 'vndk'.
-#   2. 'vndk_in_system' does not need to link to 'default', as any library that
-#      requires anything vendor would not be a vndk_in_system library.
-namespace.vndk_in_system.links = vndk,system,runtime,neuralnetworks
-namespace.vndk_in_system.link.runtime.shared_libs = %SANITIZER_RUNTIME_LIBRARIES%
-
-namespace.vndk_in_system.link.system.shared_libs  = %LLNDK_LIBRARIES%
-namespace.vndk_in_system.link.system.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-
-namespace.vndk_in_system.link.vndk.allow_all_shared_libs = true
-namespace.vndk_in_system.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-###############################################################################
-# "neuralnetworks" APEX namespace
-#
-# This namespace is for libraries within the NNAPI APEX.
-###############################################################################
-namespace.neuralnetworks.isolated = true
-namespace.neuralnetworks.visible = true
-
-namespace.neuralnetworks.search.paths = /apex/com.android.neuralnetworks/${LIB}
-namespace.neuralnetworks.asan.search.paths = /apex/com.android.neuralnetworks/${LIB}
-namespace.neuralnetworks.links = system
-namespace.neuralnetworks.link.system.shared_libs  = libc.so
-namespace.neuralnetworks.link.system.shared_libs += libcgrouprc.so
-namespace.neuralnetworks.link.system.shared_libs += libdl.so
-namespace.neuralnetworks.link.system.shared_libs += liblog.so
-namespace.neuralnetworks.link.system.shared_libs += libm.so
-namespace.neuralnetworks.link.system.shared_libs += libnativewindow.so
-namespace.neuralnetworks.link.system.shared_libs += libneuralnetworks_packageinfo.so
-namespace.neuralnetworks.link.system.shared_libs += libsync.so
-namespace.neuralnetworks.link.system.shared_libs += libvndksupport.so
-
-###############################################################################
-# Namespace config for native tests that need access to both system and vendor
-# libraries. This replicates the default linker config (done by
-# init_default_namespace_no_config in bionic/linker/linker.cpp), except that it
-# includes the requisite namespace setup for APEXes.
-###############################################################################
-[unrestricted]
-additional.namespaces = runtime,media,conscrypt,resolv,neuralnetworks
-
-# Visible to allow links to be created at runtime, e.g. through
-# android_link_namespaces in libnativeloader.
-namespace.default.visible = true
-
-namespace.default.search.paths  = /system/${LIB}
-namespace.default.search.paths += /odm/${LIB}
-namespace.default.search.paths += /vendor/${LIB}
-
-namespace.default.asan.search.paths  = /data/asan/system/${LIB}
-namespace.default.asan.search.paths +=           /system/${LIB}
-namespace.default.asan.search.paths += /data/asan/odm/${LIB}
-namespace.default.asan.search.paths +=           /odm/${LIB}
-namespace.default.asan.search.paths += /data/asan/vendor/${LIB}
-namespace.default.asan.search.paths +=           /vendor/${LIB}
-
-# Keep in sync with the "platform" namespace in art/build/apex/ld.config.txt.
-namespace.default.links = runtime,resolv,neuralnetworks
-namespace.default.link.runtime.shared_libs  = libandroidicu.so
-namespace.default.link.runtime.shared_libs += libdexfile_external.so
-namespace.default.link.runtime.shared_libs += libdexfiled_external.so
-# TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
-namespace.default.link.runtime.shared_libs += libicui18n.so
-namespace.default.link.runtime.shared_libs += libicuuc.so
-namespace.default.link.runtime.shared_libs += libnativebridge.so
-namespace.default.link.runtime.shared_libs += libnativehelper.so
-namespace.default.link.runtime.shared_libs += libnativeloader.so
-
-# TODO(b/122876336): Remove libpac.so once it's migrated to Webview
-namespace.default.link.runtime.shared_libs += libpac.so
-namespace.default.link.runtime.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-
-namespace.default.link.resolv.shared_libs = libnetd_resolv.so
-namespace.default.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-###############################################################################
-# "runtime" APEX namespace
-#
-# This namespace exposes externally accessible libraries from the Runtime APEX.
-# Keep in sync with the "runtime" namespace in art/build/apex/ld.config.txt.
-###############################################################################
-# TODO(b/139408016): Rename this namespace to "art".
-namespace.runtime.isolated = true
-# Visible to allow links to be created at runtime, e.g. through
-# android_link_namespaces in libnativeloader.
-namespace.runtime.visible = true
-
-namespace.runtime.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.asan.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.links = default
-# TODO(b/130340935): Use a dynamically created linker namespace similar to
-# classloader-namespace for oat files, and tighten this up.
-namespace.runtime.link.default.allow_all_shared_libs = true
-
-###############################################################################
-# "media" APEX namespace
-#
-# This namespace is for libraries within the media APEX.
-###############################################################################
-namespace.media.isolated = true
-namespace.media.visible = true
-
-namespace.media.search.paths = /apex/com.android.media/${LIB}
-namespace.media.asan.search.paths = /apex/com.android.media/${LIB}
-
-namespace.media.permitted.paths = /apex/com.android.media/${LIB}/extractors
-namespace.media.asan.permitted.paths = /apex/com.android.media/${LIB}/extractors
-
-namespace.media.links = default,neuralnetworks
-namespace.media.link.default.shared_libs  = %LLNDK_LIBRARIES%
-namespace.media.link.default.shared_libs += libbinder_ndk.so
-namespace.media.link.default.shared_libs += libmediametrics.so
-namespace.media.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
-
-# LLNDK library moved into apex
-namespace.media.link.neuralnetworks.shared_libs = libneuralnetworks.so
-
-
-###############################################################################
-# "conscrypt" APEX namespace
-#
-# This namespace is for libraries within the conscrypt APEX.
-# Keep in sync with the "conscrypt" namespace in art/build/apex/ld.config.txt.
-###############################################################################
-namespace.conscrypt.isolated = true
-namespace.conscrypt.visible = true
-
-namespace.conscrypt.search.paths = /apex/com.android.conscrypt/${LIB}
-namespace.conscrypt.asan.search.paths = /apex/com.android.conscrypt/${LIB}
-namespace.conscrypt.links = runtime,default
-namespace.conscrypt.link.runtime.shared_libs  = libandroidio.so
-namespace.conscrypt.link.default.shared_libs  = libc.so
-namespace.conscrypt.link.default.shared_libs += libm.so
-namespace.conscrypt.link.default.shared_libs += libdl.so
-namespace.conscrypt.link.default.shared_libs += liblog.so
-
-###############################################################################
-# "resolv" APEX namespace
-#
-# This namespace is for libraries within the resolv APEX.
-###############################################################################
-namespace.resolv.isolated = true
-namespace.resolv.visible = true
-
-namespace.resolv.search.paths = /apex/com.android.resolv/${LIB}
-namespace.resolv.asan.search.paths = /apex/com.android.resolv/${LIB}
-namespace.resolv.links = default
-namespace.resolv.link.default.shared_libs  = libc.so
-namespace.resolv.link.default.shared_libs += libm.so
-namespace.resolv.link.default.shared_libs += libdl.so
-namespace.resolv.link.default.shared_libs += libbinder_ndk.so
-namespace.resolv.link.default.shared_libs += liblog.so
-
-###############################################################################
-# "neuralnetworks" APEX namespace
-#
-# This namespace is for libraries within the NNAPI APEX.
-###############################################################################
-namespace.neuralnetworks.isolated = true
-namespace.neuralnetworks.visible = true
-
-namespace.neuralnetworks.search.paths = /apex/com.android.neuralnetworks/${LIB}
-namespace.neuralnetworks.asan.search.paths = /apex/com.android.neuralnetworks/${LIB}
-namespace.neuralnetworks.links = default
-namespace.neuralnetworks.link.default.shared_libs  = libc.so
-namespace.neuralnetworks.link.default.shared_libs += libcgrouprc.so
-namespace.neuralnetworks.link.default.shared_libs += libdl.so
-namespace.neuralnetworks.link.default.shared_libs += liblog.so
-namespace.neuralnetworks.link.default.shared_libs += libm.so
-namespace.neuralnetworks.link.default.shared_libs += libnativewindow.so
-namespace.neuralnetworks.link.default.shared_libs += libneuralnetworks_packageinfo.so
-namespace.neuralnetworks.link.default.shared_libs += libsync.so
-namespace.neuralnetworks.link.default.shared_libs += libvndksupport.so
-
-###############################################################################
-# Namespace config for binaries under /postinstall.
-# Only default namespace is defined and default has no directories
-# other than /system/lib in the search paths. This is because linker calls
-# realpath on the search paths and this causes selinux denial if the paths
-# (/vendor, /odm) are not allowed to the postinstall binaries. There is no
-# reason to allow the binaries to access the paths.
-###############################################################################
-[postinstall]
-namespace.default.isolated = false
-namespace.default.search.paths  = /system/${LIB}
-namespace.default.search.paths += /%SYSTEM_EXT%/${LIB}
-namespace.default.search.paths += /%PRODUCT%/${LIB}
+# This file is no longer in use.
+# Please update linker configuration generator instead.
+# You can find the code from /system/linkerconfig
\ No newline at end of file
diff --git a/rootdir/etc/ld.config.vndk_lite.txt b/rootdir/etc/ld.config.vndk_lite.txt
index b9b95a6..9c9f4a9 100644
--- a/rootdir/etc/ld.config.vndk_lite.txt
+++ b/rootdir/etc/ld.config.vndk_lite.txt
@@ -35,7 +35,7 @@
 dir.system = /data
 
 [system]
-additional.namespaces = runtime,conscrypt,media,neuralnetworks,resolv,sphal,vndk,rs
+additional.namespaces = art,conscrypt,media,neuralnetworks,resolv,sphal,vndk,rs
 
 ###############################################################################
 # "default" namespace
@@ -68,23 +68,23 @@
 # Keep in sync with the "platform" namespace in art/build/apex/ld.config.txt.
 # If a shared library or an executable requests a shared library that
 # cannot be loaded into the default namespace, the dynamic linker tries
-# to load the shared library from the runtime namespace. And then, if the
-# shared library cannot be loaded from the runtime namespace either, the
+# to load the shared library from the art namespace. And then, if the
+# shared library cannot be loaded from the art namespace either, the
 # dynamic linker tries to load the shared library from the resolv namespace.
 # Finally, if all attempts fail, the dynamic linker returns an error.
-namespace.default.links = runtime,resolv,neuralnetworks
-namespace.default.link.runtime.shared_libs  = libandroidicu.so
-namespace.default.link.runtime.shared_libs += libdexfile_external.so
-namespace.default.link.runtime.shared_libs += libdexfiled_external.so
+namespace.default.links = art,resolv,neuralnetworks
+namespace.default.link.art.shared_libs  = libandroidicu.so
+namespace.default.link.art.shared_libs += libdexfile_external.so
+namespace.default.link.art.shared_libs += libdexfiled_external.so
 # TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
-namespace.default.link.runtime.shared_libs += libicui18n.so
-namespace.default.link.runtime.shared_libs += libicuuc.so
-namespace.default.link.runtime.shared_libs += libnativebridge.so
-namespace.default.link.runtime.shared_libs += libnativehelper.so
-namespace.default.link.runtime.shared_libs += libnativeloader.so
+namespace.default.link.art.shared_libs += libicui18n.so
+namespace.default.link.art.shared_libs += libicuuc.so
+namespace.default.link.art.shared_libs += libnativebridge.so
+namespace.default.link.art.shared_libs += libnativehelper.so
+namespace.default.link.art.shared_libs += libnativeloader.so
 
 # TODO(b/122876336): Remove libpac.so once it's migrated to Webview
-namespace.default.link.runtime.shared_libs += libpac.so
+namespace.default.link.art.shared_libs += libpac.so
 
 # When libnetd_resolv.so can't be found in the default namespace, search for it
 # in the resolv namespace. Don't allow any other libraries from the resolv namespace
@@ -95,25 +95,25 @@
 namespace.default.link.neuralnetworks.shared_libs = libneuralnetworks.so
 
 ###############################################################################
-# "runtime" APEX namespace
+# "art" APEX namespace
 #
-# This namespace pulls in externally accessible libs from the Runtime APEX.
-# Keep in sync with the "runtime" namespace in art/build/apex/ld.config.txt.
+# This namespace pulls in externally accessible libs from the ART APEX.
+# Keep in sync with the "art" namespace in art/build/apex/ld.config.txt.
 ###############################################################################
-# TODO(b/139408016): Rename this namespace to "art".
-namespace.runtime.isolated = true
+namespace.art.isolated = true
 # Visible to allow links to be created at runtime, e.g. through
 # android_link_namespaces in libnativeloader.
-namespace.runtime.visible = true
+namespace.art.visible = true
 
-namespace.runtime.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.asan.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.links = default
+namespace.art.search.paths = /apex/com.android.art/${LIB}
+namespace.art.asan.search.paths = /apex/com.android.art/${LIB}
+namespace.art.links = default,neuralnetworks
 # Need allow_all_shared_libs because libart.so can dlopen oat files in
 # /system/framework and /data.
 # TODO(b/130340935): Use a dynamically created linker namespace similar to
 # classloader-namespace for oat files, and tighten this up.
-namespace.runtime.link.default.allow_all_shared_libs = true
+namespace.art.link.default.allow_all_shared_libs = true
+namespace.art.link.neuralnetworks.shared_libs = libneuralnetworks.so
 
 ###############################################################################
 # "media" APEX namespace
@@ -148,12 +148,13 @@
 
 namespace.conscrypt.search.paths = /apex/com.android.conscrypt/${LIB}
 namespace.conscrypt.asan.search.paths = /apex/com.android.conscrypt/${LIB}
-namespace.conscrypt.links = runtime,default
-namespace.conscrypt.link.runtime.shared_libs  = libandroidio.so
+namespace.conscrypt.links = art,default
+namespace.conscrypt.link.art.shared_libs = libandroidio.so
 namespace.conscrypt.link.default.shared_libs  = libc.so
 namespace.conscrypt.link.default.shared_libs += libm.so
 namespace.conscrypt.link.default.shared_libs += libdl.so
 namespace.conscrypt.link.default.shared_libs += liblog.so
+namespace.conscrypt.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
 
 ###############################################################################
 # "resolv" APEX namespace
@@ -173,6 +174,7 @@
 namespace.resolv.link.default.shared_libs += libbinder_ndk.so
 namespace.resolv.link.default.shared_libs += liblog.so
 namespace.resolv.link.default.shared_libs += libvndksupport.so
+namespace.resolv.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
 
 ###############################################################################
 # "sphal" namespace
@@ -347,7 +349,7 @@
 namespace.neuralnetworks.link.default.shared_libs += libneuralnetworks_packageinfo.so
 namespace.neuralnetworks.link.default.shared_libs += libsync.so
 namespace.neuralnetworks.link.default.shared_libs += libvndksupport.so
-
+namespace.neuralnetworks.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
 
 ###############################################################################
 # Namespace config for vendor processes. In O, no restriction is enforced for
@@ -356,7 +358,7 @@
 # (LL-NDK only) access.
 ###############################################################################
 [vendor]
-additional.namespaces = runtime,neuralnetworks
+additional.namespaces = art,neuralnetworks
 
 namespace.default.isolated = false
 
@@ -398,36 +400,35 @@
 namespace.default.asan.search.paths += /data/asan/system/${LIB}/vndk%VNDK_VER%
 namespace.default.asan.search.paths +=           /system/${LIB}/vndk%VNDK_VER%
 
-namespace.default.links = runtime,neuralnetworks
-namespace.default.link.runtime.shared_libs  = libdexfile_external.so
-namespace.default.link.runtime.shared_libs += libdexfiled_external.so
+namespace.default.links = art,neuralnetworks
+namespace.default.link.art.shared_libs  = libdexfile_external.so
+namespace.default.link.art.shared_libs += libdexfiled_external.so
 # TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
-namespace.default.link.runtime.shared_libs += libicui18n.so
-namespace.default.link.runtime.shared_libs += libicuuc.so
-namespace.default.link.runtime.shared_libs += libnativebridge.so
-namespace.default.link.runtime.shared_libs += libnativehelper.so
-namespace.default.link.runtime.shared_libs += libnativeloader.so
+namespace.default.link.art.shared_libs += libicui18n.so
+namespace.default.link.art.shared_libs += libicuuc.so
+namespace.default.link.art.shared_libs += libnativebridge.so
+namespace.default.link.art.shared_libs += libnativehelper.so
+namespace.default.link.art.shared_libs += libnativeloader.so
 # Workaround for b/124772622
-namespace.default.link.runtime.shared_libs += libandroidicu.so
+namespace.default.link.art.shared_libs += libandroidicu.so
 
 # LLNDK library moved into apex
 namespace.default.link.neuralnetworks.shared_libs = libneuralnetworks.so
 
 ###############################################################################
-# "runtime" APEX namespace
+# "art" APEX namespace
 #
-# This namespace exposes externally accessible libraries from the Runtime APEX.
-# Keep in sync with the "runtime" namespace in art/build/apex/ld.config.txt.
+# This namespace exposes externally accessible libraries from the ART APEX.
+# Keep in sync with the "art" namespace in art/build/apex/ld.config.txt.
 ###############################################################################
-# TODO(b/139408016): Rename this namespace to "art".
-namespace.runtime.isolated = true
+namespace.art.isolated = true
 
-namespace.runtime.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.asan.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.links = default
+namespace.art.search.paths = /apex/com.android.art/${LIB}
+namespace.art.asan.search.paths = /apex/com.android.art/${LIB}
+namespace.art.links = default
 # TODO(b/130340935): Use a dynamically created linker namespace similar to
 # classloader-namespace for oat files, and tighten this up.
-namespace.runtime.link.default.allow_all_shared_libs = true
+namespace.art.link.default.allow_all_shared_libs = true
 
 ###############################################################################
 # "neuralnetworks" APEX namespace
@@ -449,7 +450,7 @@
 namespace.neuralnetworks.link.default.shared_libs += libneuralnetworks_packageinfo.so
 namespace.neuralnetworks.link.default.shared_libs += libsync.so
 namespace.neuralnetworks.link.default.shared_libs += libvndksupport.so
-
+namespace.neuralnetworks.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
 
 ###############################################################################
 # Namespace config for native tests that need access to both system and vendor
@@ -458,7 +459,7 @@
 # includes the requisite namespace setup for APEXes.
 ###############################################################################
 [unrestricted]
-additional.namespaces = runtime,media,conscrypt,resolv,neuralnetworks
+additional.namespaces = art,media,conscrypt,resolv,neuralnetworks
 
 # Visible to allow links to be created at runtime, e.g. through
 # android_link_namespaces in libnativeloader.
@@ -476,20 +477,19 @@
 namespace.default.asan.search.paths +=           /vendor/${LIB}
 
 # Keep in sync with the "platform" namespace in art/build/apex/ld.config.txt.
-namespace.default.links = runtime,resolv,neuralnetworks
-namespace.default.link.runtime.shared_libs  = libandroidicu.so
-namespace.default.link.runtime.shared_libs += libdexfile_external.so
-namespace.default.link.runtime.shared_libs += libdexfiled_external.so
+namespace.default.links = art,resolv,neuralnetworks
+namespace.default.link.art.shared_libs  = libandroidicu.so
+namespace.default.link.art.shared_libs += libdexfile_external.so
+namespace.default.link.art.shared_libs += libdexfiled_external.so
 # TODO(b/120786417 or b/134659294): libicuuc.so and libicui18n.so are kept for app compat.
-namespace.default.link.runtime.shared_libs += libicui18n.so
-namespace.default.link.runtime.shared_libs += libicuuc.so
-namespace.default.link.runtime.shared_libs += libnativebridge.so
-namespace.default.link.runtime.shared_libs += libnativehelper.so
-namespace.default.link.runtime.shared_libs += libnativeloader.so
+namespace.default.link.art.shared_libs += libicui18n.so
+namespace.default.link.art.shared_libs += libicuuc.so
+namespace.default.link.art.shared_libs += libnativebridge.so
+namespace.default.link.art.shared_libs += libnativehelper.so
+namespace.default.link.art.shared_libs += libnativeloader.so
 
 # TODO(b/122876336): Remove libpac.so once it's migrated to Webview
-namespace.default.link.runtime.shared_libs += libpac.so
-namespace.default.link.runtime.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
+namespace.default.link.art.shared_libs += libpac.so
 
 namespace.default.link.resolv.shared_libs = libnetd_resolv.so
 
@@ -497,22 +497,22 @@
 namespace.default.link.neuralnetworks.shared_libs = libneuralnetworks.so
 
 ###############################################################################
-# "runtime" APEX namespace
+# "art" APEX namespace
 #
-# This namespace exposes externally accessible libraries from the Runtime APEX.
-# Keep in sync with the "runtime" namespace in art/build/apex/ld.config.txt.
+# This namespace exposes externally accessible libraries from the ART APEX.
+# Keep in sync with the "art" namespace in art/build/apex/ld.config.txt.
 ###############################################################################
-# TODO(b/139408016): Rename this namespace to "art".
-namespace.runtime.isolated = true
+namespace.art.isolated = true
 # Visible to allow links to be created at runtime, e.g. through
 # android_link_namespaces in libnativeloader.
-namespace.runtime.visible = true
+namespace.art.visible = true
 
-namespace.runtime.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.asan.search.paths = /apex/com.android.art/${LIB}
-namespace.runtime.links = default
+namespace.art.search.paths = /apex/com.android.art/${LIB}
+namespace.art.asan.search.paths = /apex/com.android.art/${LIB}
+namespace.art.links = default
 # TODO(b/130340935): Use a dynamically created linker namespace similar to
 # classloader-namespace for oat files, and tighten this up.
+namespace.runtime.link.default.allow_all_shared_libs = true
 
 ###############################################################################
 # "media" APEX namespace
@@ -547,11 +547,12 @@
 
 namespace.conscrypt.search.paths = /apex/com.android.conscrypt/${LIB}
 namespace.conscrypt.asan.search.paths = /apex/com.android.conscrypt/${LIB}
-namespace.conscrypt.links = runtime,default
-namespace.conscrypt.link.runtime.shared_libs  = libandroidio.so
+namespace.conscrypt.links = art,default
+namespace.conscrypt.link.art.shared_libs = libandroidio.so
 namespace.conscrypt.link.default.shared_libs  = libc.so
 namespace.conscrypt.link.default.shared_libs += libm.so
 namespace.conscrypt.link.default.shared_libs += libdl.so
+namespace.conscrypt.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
 
 ###############################################################################
 # "resolv" APEX namespace
@@ -569,6 +570,7 @@
 namespace.resolv.link.default.shared_libs += libm.so
 namespace.resolv.link.default.shared_libs += libdl.so
 namespace.resolv.link.default.shared_libs += libbinder_ndk.so
+namespace.resolv.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
 
 ###############################################################################
 # "neuralnetworks" APEX namespace
@@ -590,7 +592,7 @@
 namespace.neuralnetworks.link.default.shared_libs += libneuralnetworks_packageinfo.so
 namespace.neuralnetworks.link.default.shared_libs += libsync.so
 namespace.neuralnetworks.link.default.shared_libs += libvndksupport.so
-
+namespace.neuralnetworks.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
 
 ###############################################################################
 # Namespace config for binaries under /postinstall.
diff --git a/rootdir/etc/public.libraries.android.txt b/rootdir/etc/public.libraries.android.txt
index 27e855f..405f5a9 100644
--- a/rootdir/etc/public.libraries.android.txt
+++ b/rootdir/etc/public.libraries.android.txt
@@ -17,7 +17,7 @@
 libmediandk.so
 libm.so
 libnativewindow.so
-libneuralnetworks.so
+libneuralnetworks.so nopreload
 libOpenMAXAL.so
 libOpenSLES.so
 libRS.so
diff --git a/rootdir/init.rc b/rootdir/init.rc
index bad0642..c5bf1603 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -918,6 +918,17 @@
 on init && property:ro.debuggable=1
     start console
 
-service flash_recovery /system/bin/install-recovery.sh
-    class main
-    oneshot
+on userspace-reboot
+  # TODO(b/135984674): reset all necessary properties here.
+  setprop sys.init.userspace_reboot_in_progress 1
+  setprop sys.boot_completed 0
+  setprop sys.init.updatable_crashing 0
+  setprop apexd.status 0
+
+on userspace-reboot-resume
+  # TODO(b/135984674): remount userdata and reset checkpointing
+  trigger nonencrypted
+  trigger post-fs-data
+  trigger zygote-start
+  trigger early-boot
+  trigger boot
diff --git a/rootdir/update_and_install_ld_config.mk b/rootdir/update_and_install_ld_config.mk
index c4b8e4e..44f7b65 100644
--- a/rootdir/update_and_install_ld_config.mk
+++ b/rootdir/update_and_install_ld_config.mk
@@ -38,8 +38,8 @@
 
 llndk_libraries_file := $(library_lists_dir)/llndk.libraries.$(vndk_version).txt
 vndksp_libraries_file := $(library_lists_dir)/vndksp.libraries.$(vndk_version).txt
-vndkcore_libraries_file := $(library_lists_dir)/vndkcore.libraries.txt
-vndkprivate_libraries_file := $(library_lists_dir)/vndkprivate.libraries.txt
+vndkcore_libraries_file := $(library_lists_dir)/vndkcore.libraries.$(vndk_version).txt
+vndkprivate_libraries_file := $(library_lists_dir)/vndkprivate.libraries.$(vndk_version).txt
 llndk_moved_to_apex_libraries_file := $(library_lists_dir)/llndkinapex.libraries.txt
 ifeq ($(my_vndk_use_core_variant),true)
 vndk_using_core_variant_libraries_file := $(library_lists_dir)/vndk_using_core_variant.libraries.$(vndk_version).txt