Merge "Use optional for nullable types"
diff --git a/adb/client/transport_mdns.cpp b/adb/client/transport_mdns.cpp
index ff1f7b4..22b9b18 100644
--- a/adb/client/transport_mdns.cpp
+++ b/adb/client/transport_mdns.cpp
@@ -409,9 +409,9 @@
     }
 
     std::string sName(serviceName);
-    std::remove_if(services->begin(), services->end(), [&sName](ResolvedService* service) {
-        return (sName == service->serviceName());
-    });
+    services->erase(std::remove_if(
+            services->begin(), services->end(),
+            [&sName](ResolvedService* service) { return (sName == service->serviceName()); }));
 }
 
 // Returns the version the device wanted to advertise,
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index aad9f77..5223087 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -512,8 +512,7 @@
 // Enable casefold if needed.
 static void tune_casefold(const std::string& blk_device, const struct ext4_super_block* sb,
                           int* fs_stat) {
-    bool has_casefold =
-            (sb->s_feature_ro_compat & cpu_to_le32(EXT4_FEATURE_INCOMPAT_CASEFOLD)) != 0;
+    bool has_casefold = (sb->s_feature_incompat & cpu_to_le32(EXT4_FEATURE_INCOMPAT_CASEFOLD)) != 0;
     bool wants_casefold = android::base::GetBoolProperty("ro.emulated_storage.casefold", false);
 
     if (!wants_casefold || has_casefold) return;
@@ -573,9 +572,8 @@
 
     // requires to give last_fsck_time to current to avoid insane time.
     // otherwise, tune2fs won't enable metadata_csum.
-    std::string now = std::to_string(time(0));
     const char* tune2fs_args[] = {TUNE2FS_BIN, "-O",        "metadata_csum,64bit,extent",
-                                  "-T",        now.c_str(), blk_device.c_str()};
+                                  "-T",        "now", blk_device.c_str()};
     const char* resize2fs_args[] = {RESIZE2FS_BIN, "-b", blk_device.c_str()};
 
     if (!run_command(tune2fs_args, ARRAY_SIZE(tune2fs_args))) {
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
index 65f710a..4ebe085 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -30,6 +30,7 @@
 
 #include <android-base/file.h>
 #include <android-base/parseint.h>
+#include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <libgsi/libgsi.h>
@@ -659,6 +660,21 @@
     }
 }
 
+void EnableMandatoryFlags(Fstab* fstab) {
+    // Devices launched in R and after should enable fs_verity on userdata. The flag causes tune2fs
+    // to enable the feature. A better alternative would be to enable on mkfs at the beginning.
+    if (android::base::GetIntProperty("ro.product.first_api_level", 0) >= 30) {
+        std::vector<FstabEntry*> data_entries = GetEntriesForMountPoint(fstab, "/data");
+        for (auto&& entry : data_entries) {
+            // Besides ext4, f2fs is also supported. But the image is already created with verity
+            // turned on when it was first introduced.
+            if (entry->fs_type == "ext4") {
+                entry->fs_mgr_flags.fs_verity = true;
+            }
+        }
+    }
+}
+
 bool ReadFstabFromFile(const std::string& path, Fstab* fstab) {
     auto fstab_file = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
     if (!fstab_file) {
@@ -679,6 +695,7 @@
     }
 
     SkipMountingPartitions(fstab);
+    EnableMandatoryFlags(fstab);
 
     return true;
 }
diff --git a/fs_mgr/libsnapshot/snapshot.cpp b/fs_mgr/libsnapshot/snapshot.cpp
index 2fe06fb..187f24c 100644
--- a/fs_mgr/libsnapshot/snapshot.cpp
+++ b/fs_mgr/libsnapshot/snapshot.cpp
@@ -2352,6 +2352,9 @@
 
     ss << "Current slot: " << device_->GetSlotSuffix() << std::endl;
     ss << "Boot indicator: booting from " << GetCurrentSlot() << " slot" << std::endl;
+    ss << "Rollback indicator: "
+       << (access(GetRollbackIndicatorPath().c_str(), F_OK) == 0 ? "exists" : strerror(errno))
+       << std::endl;
 
     bool ok = true;
     std::vector<std::string> snapshots;
diff --git a/init/Android.bp b/init/Android.bp
index f28934e..52628f3 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -28,6 +28,7 @@
     "rlimit_parser.cpp",
     "service.cpp",
     "service_list.cpp",
+    "service_lock.cpp",
     "service_parser.cpp",
     "service_utils.cpp",
     "subcontext.cpp",
@@ -81,6 +82,7 @@
         "-Wextra",
         "-Wno-unused-parameter",
         "-Werror",
+        "-Wthread-safety",
         "-DALLOW_FIRST_STAGE_CONSOLE=0",
         "-DALLOW_LOCAL_PROP_OVERRIDE=0",
         "-DALLOW_PERMISSIVE_SELINUX=0",
@@ -88,6 +90,7 @@
         "-DWORLD_WRITABLE_KMSG=0",
         "-DDUMP_ON_UMOUNT_FAILURE=0",
         "-DSHUTDOWN_ZERO_TIMEOUT=0",
+        "-DINIT_FULL_SOURCES",
     ],
     product_variables: {
         debuggable: {
@@ -267,6 +270,37 @@
     static_libs: ["libinit"],
 }
 
+cc_defaults {
+    name: "libinit_test_utils_libraries_defaults",
+    shared_libs: [
+        "libbase",
+        "libcutils",
+        "libselinux",
+        "libhidl-gen-utils",
+        "liblog",
+        "libprocessgroup",
+        "libprotobuf-cpp-lite",
+    ],
+}
+
+cc_library_static {
+    name: "libinit_test_utils",
+    defaults: ["libinit_test_utils_libraries_defaults"],
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Wno-unused-parameter",
+        "-Werror",
+    ],
+    srcs: init_common_sources + [
+        "test_utils/service_utils.cpp",
+    ],
+    whole_static_libs: [
+        "libcap",
+    ],
+    export_include_dirs: ["test_utils/include"], // for tests
+}
+
 // Host Verifier
 // ------------------------------------------------------------------------------
 
diff --git a/init/action_manager.cpp b/init/action_manager.cpp
index ebca762..b45f5cd 100644
--- a/init/action_manager.cpp
+++ b/init/action_manager.cpp
@@ -41,10 +41,12 @@
 }
 
 void ActionManager::QueueEventTrigger(const std::string& trigger) {
+    auto lock = std::lock_guard{event_queue_lock_};
     event_queue_.emplace(trigger);
 }
 
 void ActionManager::QueuePropertyChange(const std::string& name, const std::string& value) {
+    auto lock = std::lock_guard{event_queue_lock_};
     event_queue_.emplace(std::make_pair(name, value));
 }
 
@@ -53,6 +55,7 @@
 }
 
 void ActionManager::QueueBuiltinAction(BuiltinFunction func, const std::string& name) {
+    auto lock = std::lock_guard{event_queue_lock_};
     auto action = std::make_unique<Action>(true, nullptr, "<Builtin Action>", 0, name,
                                            std::map<std::string, std::string>{});
     action->AddCommand(std::move(func), {name}, 0);
@@ -62,15 +65,18 @@
 }
 
 void ActionManager::ExecuteOneCommand() {
-    // Loop through the event queue until we have an action to execute
-    while (current_executing_actions_.empty() && !event_queue_.empty()) {
-        for (const auto& action : actions_) {
-            if (std::visit([&action](const auto& event) { return action->CheckEvent(event); },
-                           event_queue_.front())) {
-                current_executing_actions_.emplace(action.get());
+    {
+        auto lock = std::lock_guard{event_queue_lock_};
+        // Loop through the event queue until we have an action to execute
+        while (current_executing_actions_.empty() && !event_queue_.empty()) {
+            for (const auto& action : actions_) {
+                if (std::visit([&action](const auto& event) { return action->CheckEvent(event); },
+                               event_queue_.front())) {
+                    current_executing_actions_.emplace(action.get());
+                }
             }
+            event_queue_.pop();
         }
-        event_queue_.pop();
     }
 
     if (current_executing_actions_.empty()) {
@@ -103,6 +109,7 @@
 }
 
 bool ActionManager::HasMoreCommands() const {
+    auto lock = std::lock_guard{event_queue_lock_};
     return !current_executing_actions_.empty() || !event_queue_.empty();
 }
 
@@ -113,6 +120,7 @@
 }
 
 void ActionManager::ClearQueue() {
+    auto lock = std::lock_guard{event_queue_lock_};
     // We are shutting down so don't claim the oneshot builtin actions back
     current_executing_actions_ = {};
     event_queue_ = {};
diff --git a/init/action_manager.h b/init/action_manager.h
index a2b95ac..b6f93d9 100644
--- a/init/action_manager.h
+++ b/init/action_manager.h
@@ -16,9 +16,12 @@
 
 #pragma once
 
+#include <mutex>
 #include <string>
 #include <vector>
 
+#include <android-base/thread_annotations.h>
+
 #include "action.h"
 #include "builtins.h"
 
@@ -48,7 +51,9 @@
     void operator=(ActionManager const&) = delete;
 
     std::vector<std::unique_ptr<Action>> actions_;
-    std::queue<std::variant<EventTrigger, PropertyChange, BuiltinAction>> event_queue_;
+    std::queue<std::variant<EventTrigger, PropertyChange, BuiltinAction>> event_queue_
+            GUARDED_BY(event_queue_lock_);
+    mutable std::mutex event_queue_lock_;
     std::queue<const Action*> current_executing_actions_;
     std::size_t current_command_;
 };
diff --git a/init/action_parser.cpp b/init/action_parser.cpp
index f316871..52f6a1f 100644
--- a/init/action_parser.cpp
+++ b/init/action_parser.cpp
@@ -21,7 +21,7 @@
 #include <android-base/properties.h>
 #include <android-base/strings.h>
 
-#if defined(__ANDROID__)
+#ifdef INIT_FULL_SOURCES
 #include "property_service.h"
 #include "selinux.h"
 #else
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 200bfff..dd5af72 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -151,6 +151,7 @@
 
 template <typename F>
 static void ForEachServiceInClass(const std::string& classname, F function) {
+    auto lock = std::lock_guard{service_lock};
     for (const auto& service : ServiceList::GetInstance()) {
         if (service->classnames().count(classname)) std::invoke(function, service);
     }
@@ -162,6 +163,7 @@
         return {};
     // Starting a class does not start services which are explicitly disabled.
     // They must  be started individually.
+    auto lock = std::lock_guard{service_lock};
     for (const auto& service : ServiceList::GetInstance()) {
         if (service->classnames().count(args[1])) {
             if (auto result = service->StartIfNotDisabled(); !result.ok()) {
@@ -184,6 +186,7 @@
         // stopped either.
         return {};
     }
+    auto lock = std::lock_guard{service_lock};
     for (const auto& service : ServiceList::GetInstance()) {
         if (service->classnames().count(args[1])) {
             if (auto result = service->StartIfPostData(); !result.ok()) {
@@ -234,6 +237,7 @@
 }
 
 static Result<void> do_enable(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     Service* svc = ServiceList::GetInstance().FindService(args[1]);
     if (!svc) return Error() << "Could not find service";
 
@@ -245,6 +249,7 @@
 }
 
 static Result<void> do_exec(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     auto service = Service::MakeTemporaryOneshotService(args.args);
     if (!service.ok()) {
         return Error() << "Could not create exec service: " << service.error();
@@ -258,6 +263,7 @@
 }
 
 static Result<void> do_exec_background(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     auto service = Service::MakeTemporaryOneshotService(args.args);
     if (!service.ok()) {
         return Error() << "Could not create exec background service: " << service.error();
@@ -271,6 +277,7 @@
 }
 
 static Result<void> do_exec_start(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     Service* service = ServiceList::GetInstance().FindService(args[1]);
     if (!service) {
         return Error() << "Service not found";
@@ -340,6 +347,7 @@
 }
 
 static Result<void> do_interface_restart(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
     if (!svc) return Error() << "interface " << args[1] << " not found";
     svc->Restart();
@@ -347,6 +355,7 @@
 }
 
 static Result<void> do_interface_start(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
     if (!svc) return Error() << "interface " << args[1] << " not found";
     if (auto result = svc->Start(); !result.ok()) {
@@ -356,6 +365,7 @@
 }
 
 static Result<void> do_interface_stop(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
     if (!svc) return Error() << "interface " << args[1] << " not found";
     svc->Stop();
@@ -740,6 +750,7 @@
 }
 
 static Result<void> do_start(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     Service* svc = ServiceList::GetInstance().FindService(args[1]);
     if (!svc) return Error() << "service " << args[1] << " not found";
     if (auto result = svc->Start(); !result.ok()) {
@@ -749,6 +760,7 @@
 }
 
 static Result<void> do_stop(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     Service* svc = ServiceList::GetInstance().FindService(args[1]);
     if (!svc) return Error() << "service " << args[1] << " not found";
     svc->Stop();
@@ -756,6 +768,7 @@
 }
 
 static Result<void> do_restart(const BuiltinArguments& args) {
+    auto lock = std::lock_guard{service_lock};
     Service* svc = ServiceList::GetInstance().FindService(args[1]);
     if (!svc) return Error() << "service " << args[1] << " not found";
     svc->Restart();
@@ -1111,6 +1124,7 @@
             function(StringPrintf("Exec service failed, status %d", siginfo.si_status));
         }
     });
+    auto lock = std::lock_guard{service_lock};
     if (auto result = (*service)->ExecStart(); !result.ok()) {
         function("ExecStart failed: " + result.error().message());
     }
@@ -1250,6 +1264,7 @@
         }
         success &= parser.ParseConfigFile(c);
     }
+    auto lock = std::lock_guard{service_lock};
     ServiceList::GetInstance().MarkServicesUpdate();
     if (success) {
         return {};
diff --git a/init/init.cpp b/init/init.cpp
index 5bf1b36..bfef9e5 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -33,7 +33,9 @@
 #include <functional>
 #include <map>
 #include <memory>
+#include <mutex>
 #include <optional>
+#include <thread>
 #include <vector>
 
 #include <android-base/chrono_utils.h>
@@ -95,15 +97,148 @@
 static int signal_fd = -1;
 static int property_fd = -1;
 
-static std::unique_ptr<Timer> waiting_for_prop(nullptr);
-static std::string wait_prop_name;
-static std::string wait_prop_value;
-static std::string shutdown_command;
-static bool do_shutdown = false;
-
 static std::unique_ptr<Subcontext> subcontext;
 
+// Init epolls various FDs to wait for various inputs.  It previously waited on property changes
+// with a blocking socket that contained the information related to the change, however, it was easy
+// to fill that socket and deadlock the system.  Now we use locks to handle the property changes
+// directly in the property thread, however we still must wake the epoll to inform init that there
+// is a change to process, so we use this FD.  It is non-blocking, since we do not care how many
+// times WakeEpoll() is called, only that the epoll will wake.
+static int wake_epoll_fd = -1;
+static void InstallInitNotifier(Epoll* epoll) {
+    int sockets[2];
+    if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0, sockets) != 0) {
+        PLOG(FATAL) << "Failed to socketpair() between property_service and init";
+    }
+    int epoll_fd = sockets[0];
+    wake_epoll_fd = sockets[1];
+
+    auto drain_socket = [epoll_fd] {
+        char buf[512];
+        while (read(epoll_fd, buf, sizeof(buf)) > 0) {
+        }
+    };
+
+    if (auto result = epoll->RegisterHandler(epoll_fd, drain_socket); !result) {
+        LOG(FATAL) << result.error();
+    }
+}
+
+static void WakeEpoll() {
+    constexpr char value[] = "1";
+    write(wake_epoll_fd, value, sizeof(value));
+}
+
+static class PropWaiterState {
+  public:
+    bool StartWaiting(const char* name, const char* value) {
+        auto lock = std::lock_guard{lock_};
+        if (waiting_for_prop_) {
+            return false;
+        }
+        if (GetProperty(name, "") != value) {
+            // Current property value is not equal to expected value
+            wait_prop_name_ = name;
+            wait_prop_value_ = value;
+            waiting_for_prop_.reset(new Timer());
+        } else {
+            LOG(INFO) << "start_waiting_for_property(\"" << name << "\", \"" << value
+                      << "\"): already set";
+        }
+        return true;
+    }
+
+    void ResetWaitForProp() {
+        auto lock = std::lock_guard{lock_};
+        ResetWaitForPropLocked();
+    }
+
+    void CheckAndResetWait(const std::string& name, const std::string& value) {
+        auto lock = std::lock_guard{lock_};
+        // We always record how long init waited for ueventd to tell us cold boot finished.
+        // If we aren't waiting on this property, it means that ueventd finished before we even
+        // started to wait.
+        if (name == kColdBootDoneProp) {
+            auto time_waited = waiting_for_prop_ ? waiting_for_prop_->duration().count() : 0;
+            std::thread([time_waited] {
+                SetProperty("ro.boottime.init.cold_boot_wait", std::to_string(time_waited));
+            }).detach();
+        }
+
+        if (waiting_for_prop_) {
+            if (wait_prop_name_ == name && wait_prop_value_ == value) {
+                LOG(INFO) << "Wait for property '" << wait_prop_name_ << "=" << wait_prop_value_
+                          << "' took " << *waiting_for_prop_;
+                ResetWaitForPropLocked();
+                WakeEpoll();
+            }
+        }
+    }
+
+    // This is not thread safe because it releases the lock when it returns, so the waiting state
+    // may change.  However, we only use this function to prevent running commands in the main
+    // thread loop when we are waiting, so we do not care about false positives; only false
+    // negatives.  StartWaiting() and this function are always called from the same thread, so false
+    // negatives are not possible and therefore we're okay.
+    bool MightBeWaiting() {
+        auto lock = std::lock_guard{lock_};
+        return static_cast<bool>(waiting_for_prop_);
+    }
+
+  private:
+    void ResetWaitForPropLocked() {
+        wait_prop_name_.clear();
+        wait_prop_value_.clear();
+        waiting_for_prop_.reset();
+    }
+
+    std::mutex lock_;
+    std::unique_ptr<Timer> waiting_for_prop_{nullptr};
+    std::string wait_prop_name_;
+    std::string wait_prop_value_;
+
+} prop_waiter_state;
+
+bool start_waiting_for_property(const char* name, const char* value) {
+    return prop_waiter_state.StartWaiting(name, value);
+}
+
+void ResetWaitForProp() {
+    prop_waiter_state.ResetWaitForProp();
+}
+
+static class ShutdownState {
+  public:
+    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
+        // action queue.  Instead we set this flag and ensure that shutdown happens before the next
+        // command is run in the main init loop.
+        auto lock = std::lock_guard{shutdown_command_lock_};
+        shutdown_command_ = command;
+        do_shutdown_ = true;
+        WakeEpoll();
+    }
+
+    std::optional<std::string> CheckShutdown() {
+        auto lock = std::lock_guard{shutdown_command_lock_};
+        if (do_shutdown_ && !IsShuttingDown()) {
+            do_shutdown_ = false;
+            return shutdown_command_;
+        }
+        return {};
+    }
+
+  private:
+    std::mutex shutdown_command_lock_;
+    std::string shutdown_command_;
+    bool do_shutdown_ = false;
+} shutdown_state;
+
 void DumpState() {
+    auto lock = std::lock_guard{service_lock};
     ServiceList::GetInstance().DumpState();
     ActionManager::GetInstance().DumpState();
 }
@@ -156,40 +291,7 @@
     }
 }
 
-bool start_waiting_for_property(const char *name, const char *value)
-{
-    if (waiting_for_prop) {
-        return false;
-    }
-    if (GetProperty(name, "") != value) {
-        // Current property value is not equal to expected value
-        wait_prop_name = name;
-        wait_prop_value = value;
-        waiting_for_prop.reset(new Timer());
-    } else {
-        LOG(INFO) << "start_waiting_for_property(\""
-                  << name << "\", \"" << value << "\"): already set";
-    }
-    return true;
-}
-
-void ResetWaitForProp() {
-    wait_prop_name.clear();
-    wait_prop_value.clear();
-    waiting_for_prop.reset();
-}
-
-static 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
-    // action queue.  Instead we set this flag and ensure that shutdown happens before the next
-    // command is run in the main init loop.
-    shutdown_command = command;
-    do_shutdown = true;
-}
-
-void property_changed(const std::string& name, const std::string& value) {
+void PropertyChanged(const std::string& name, const std::string& value) {
     // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
     // This is to ensure that init will always and immediately shutdown/reboot, regardless of
     // if there are other pending events to process or if init is waiting on an exec service or
@@ -197,30 +299,20 @@
     // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific
     // commands to be executed.
     if (name == "sys.powerctl") {
-        TriggerShutdown(value);
+        trigger_shutdown(value);
     }
 
-    if (property_triggers_enabled) ActionManager::GetInstance().QueuePropertyChange(name, value);
-
-    // We always record how long init waited for ueventd to tell us cold boot finished.
-    // If we aren't waiting on this property, it means that ueventd finished before we even started
-    // to wait.
-    if (name == kColdBootDoneProp) {
-        auto time_waited = waiting_for_prop ? waiting_for_prop->duration().count() : 0;
-        SetProperty("ro.boottime.init.cold_boot_wait", std::to_string(time_waited));
+    if (property_triggers_enabled) {
+        ActionManager::GetInstance().QueuePropertyChange(name, value);
+        WakeEpoll();
     }
 
-    if (waiting_for_prop) {
-        if (wait_prop_name == name && wait_prop_value == value) {
-            LOG(INFO) << "Wait for property '" << wait_prop_name << "=" << wait_prop_value
-                      << "' took " << *waiting_for_prop;
-            ResetWaitForProp();
-        }
-    }
+    prop_waiter_state.CheckAndResetWait(name, value);
 }
 
 static std::optional<boot_clock::time_point> HandleProcessActions() {
     std::optional<boot_clock::time_point> next_process_action_time;
+    auto lock = std::lock_guard{service_lock};
     for (const auto& s : ServiceList::GetInstance()) {
         if ((s->flags() & SVC_RUNNING) && s->timeout_period()) {
             auto timeout_time = s->time_started() + *s->timeout_period();
@@ -249,7 +341,7 @@
     return next_process_action_time;
 }
 
-static Result<void> DoControlStart(Service* service) {
+static Result<void> DoControlStart(Service* service) REQUIRES(service_lock) {
     return service->Start();
 }
 
@@ -258,7 +350,7 @@
     return {};
 }
 
-static Result<void> DoControlRestart(Service* service) {
+static Result<void> DoControlRestart(Service* service) REQUIRES(service_lock) {
     service->Restart();
     return {};
 }
@@ -292,7 +384,7 @@
     return control_message_functions;
 }
 
-bool HandleControlMessage(const std::string& msg, const std::string& name, pid_t pid) {
+bool HandleControlMessage(const std::string& msg, const std::string& name, pid_t from_pid) {
     const auto& map = get_control_message_map();
     const auto it = map.find(msg);
 
@@ -301,7 +393,7 @@
         return false;
     }
 
-    std::string cmdline_path = StringPrintf("proc/%d/cmdline", pid);
+    std::string cmdline_path = StringPrintf("proc/%d/cmdline", from_pid);
     std::string process_cmdline;
     if (ReadFileToString(cmdline_path, &process_cmdline)) {
         std::replace(process_cmdline.begin(), process_cmdline.end(), '\0', ' ');
@@ -312,6 +404,8 @@
 
     const ControlMessageFunction& function = it->second;
 
+    auto lock = std::lock_guard{service_lock};
+
     Service* svc = nullptr;
 
     switch (function.target) {
@@ -329,23 +423,24 @@
 
     if (svc == nullptr) {
         LOG(ERROR) << "Control message: Could not find '" << name << "' for ctl." << msg
-                   << " from pid: " << pid << " (" << process_cmdline << ")";
+                   << " from pid: " << from_pid << " (" << process_cmdline << ")";
         return false;
     }
 
     if (auto result = function.action(svc); !result.ok()) {
         LOG(ERROR) << "Control message: Could not ctl." << msg << " for '" << name
-                   << "' from pid: " << pid << " (" << process_cmdline << "): " << result.error();
+                   << "' from pid: " << from_pid << " (" << process_cmdline
+                   << "): " << result.error();
         return false;
     }
 
     LOG(INFO) << "Control message: Processed ctl." << msg << " for '" << name
-              << "' from pid: " << pid << " (" << process_cmdline << ")";
+              << "' from pid: " << from_pid << " (" << process_cmdline << ")";
     return true;
 }
 
 static Result<void> wait_for_coldboot_done_action(const BuiltinArguments& args) {
-    if (!start_waiting_for_property(kColdBootDoneProp, "true")) {
+    if (!prop_waiter_state.StartWaiting(kColdBootDoneProp, "true")) {
         LOG(FATAL) << "Could not wait for '" << kColdBootDoneProp << "'";
     }
 
@@ -493,6 +588,7 @@
     }
 
     auto found = false;
+    auto lock = std::lock_guard{service_lock};
     for (const auto& service : ServiceList::GetInstance()) {
         auto svc = service.get();
         if (svc->keycodes() == keycodes) {
@@ -579,44 +675,6 @@
     }
 }
 
-static void HandlePropertyFd() {
-    auto message = ReadMessage(property_fd);
-    if (!message.ok()) {
-        LOG(ERROR) << "Could not read message from property service: " << message.error();
-        return;
-    }
-
-    auto property_message = PropertyMessage{};
-    if (!property_message.ParseFromString(*message)) {
-        LOG(ERROR) << "Could not parse message from property service";
-        return;
-    }
-
-    switch (property_message.msg_case()) {
-        case PropertyMessage::kControlMessage: {
-            auto& control_message = property_message.control_message();
-            bool success = HandleControlMessage(control_message.msg(), control_message.name(),
-                                                control_message.pid());
-
-            uint32_t response = success ? PROP_SUCCESS : PROP_ERROR_HANDLE_CONTROL_MESSAGE;
-            if (control_message.has_fd()) {
-                int fd = control_message.fd();
-                TEMP_FAILURE_RETRY(send(fd, &response, sizeof(response), 0));
-                close(fd);
-            }
-            break;
-        }
-        case PropertyMessage::kChangedMessage: {
-            auto& changed_message = property_message.changed_message();
-            property_changed(changed_message.name(), changed_message.value());
-            break;
-        }
-        default:
-            LOG(ERROR) << "Unknown message type from property service: "
-                       << property_message.msg_case();
-    }
-}
-
 int SecondStageMain(int argc, char** argv) {
     if (REBOOT_BOOTLOADER_ON_PANIC) {
         InstallRebootSignalHandlers();
@@ -624,7 +682,7 @@
 
     boot_clock::time_point start_time = boot_clock::now();
 
-    trigger_shutdown = TriggerShutdown;
+    trigger_shutdown = [](const std::string& command) { shutdown_state.TriggerShutdown(command); };
 
     SetStdioToDevNull(argv);
     InitKernelLogging(argv);
@@ -684,11 +742,8 @@
     }
 
     InstallSignalFdHandler(&epoll);
-
+    InstallInitNotifier(&epoll);
     StartPropertyService(&property_fd);
-    if (auto result = epoll.RegisterHandler(property_fd, HandlePropertyFd); !result.ok()) {
-        LOG(FATAL) << "Could not register epoll handler for property fd: " << result.error();
-    }
 
     // Make the time that init stages started available for bootstat to log.
     RecordStageBoottimes(start_time);
@@ -742,6 +797,7 @@
     Keychords keychords;
     am.QueueBuiltinAction(
             [&epoll, &keychords](const BuiltinArguments& args) -> Result<void> {
+                auto lock = std::lock_guard{service_lock};
                 for (const auto& svc : ServiceList::GetInstance()) {
                     keychords.Register(svc->keycodes());
                 }
@@ -772,12 +828,12 @@
         // By default, sleep until something happens.
         auto epoll_timeout = std::optional<std::chrono::milliseconds>{};
 
-        if (do_shutdown && !IsShuttingDown()) {
-            do_shutdown = false;
-            HandlePowerctlMessage(shutdown_command);
+        auto shutdown_command = shutdown_state.CheckShutdown();
+        if (shutdown_command) {
+            HandlePowerctlMessage(*shutdown_command);
         }
 
-        if (!(waiting_for_prop || Service::is_exec_service_running())) {
+        if (!(prop_waiter_state.MightBeWaiting() || Service::is_exec_service_running())) {
             am.ExecuteOneCommand();
         }
         if (!IsShuttingDown()) {
@@ -791,7 +847,7 @@
             }
         }
 
-        if (!(waiting_for_prop || Service::is_exec_service_running())) {
+        if (!(prop_waiter_state.MightBeWaiting() || Service::is_exec_service_running())) {
             // If there's more work to do, wake up again immediately.
             if (am.HasMoreCommands()) epoll_timeout = 0ms;
         }
diff --git a/init/init.h b/init/init.h
index 4bbca6f..bcf24e7 100644
--- a/init/init.h
+++ b/init/init.h
@@ -41,6 +41,9 @@
 void SendStopSendingMessagesMessage();
 void SendStartSendingMessagesMessage();
 
+void PropertyChanged(const std::string& name, const std::string& value);
+bool HandleControlMessage(const std::string& msg, const std::string& name, pid_t from_pid);
+
 int SecondStageMain(int argc, char** argv);
 
 }  // namespace init
diff --git a/init/init_test.cpp b/init/init_test.cpp
index caf3e03..3053bd8 100644
--- a/init/init_test.cpp
+++ b/init/init_test.cpp
@@ -167,6 +167,7 @@
 
     ServiceList service_list;
     TestInitText(init_script, BuiltinFunctionMap(), {}, &service_list);
+    auto lock = std::lock_guard{service_lock};
     ASSERT_EQ(1, std::distance(service_list.begin(), service_list.end()));
 
     auto service = service_list.begin()->get();
diff --git a/init/lmkd_service.cpp b/init/lmkd_service.cpp
index dd1ab4d..a531d0a 100644
--- a/init/lmkd_service.cpp
+++ b/init/lmkd_service.cpp
@@ -79,7 +79,8 @@
 }
 
 static void RegisterServices(pid_t exclude_pid) {
-    for (const auto& service : ServiceList::GetInstance().services()) {
+    auto lock = std::lock_guard{service_lock};
+    for (const auto& service : ServiceList::GetInstance()) {
         auto svc = service.get();
         if (svc->oom_score_adjust() != DEFAULT_OOM_SCORE_ADJUST) {
             // skip if process is excluded or not yet forked (pid==0)
diff --git a/init/mount_namespace.cpp b/init/mount_namespace.cpp
index 0749fe3..aa36849 100644
--- a/init/mount_namespace.cpp
+++ b/init/mount_namespace.cpp
@@ -29,6 +29,7 @@
 #include <android-base/unique_fd.h>
 #include <apex_manifest.pb.h>
 
+#include "property_service.h"
 #include "util.h"
 
 namespace android {
@@ -290,6 +291,14 @@
         return true;
     }
     if (default_ns_id != GetMountNamespaceId()) {
+        // The property service thread and its descendent threads must be in the correct mount
+        // namespace to call Service::Start(), however setns() only operates on a single thread and
+        // fails when secondary threads attempt to join the same mount namespace.  Therefore, we
+        // must join the property service thread and its descendents before the setns() call.  Those
+        // threads are then started again after the setns() call, and they'll be in the proper
+        // namespace.
+        PausePropertyService();
+
         if (setns(default_ns_fd.get(), CLONE_NEWNS) == -1) {
             PLOG(ERROR) << "Failed to switch back to the default mount namespace.";
             return false;
@@ -299,6 +308,8 @@
             LOG(ERROR) << result.error();
             return false;
         }
+
+        ResumePropertyService();
     }
 
     LOG(INFO) << "Switched to default mount namespace";
diff --git a/init/property_service.cpp b/init/property_service.cpp
index 84644e8..b140ee4 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -92,8 +92,10 @@
 static bool persistent_properties_loaded = false;
 
 static int property_set_fd = -1;
+static int from_init_socket = -1;
 static int init_socket = -1;
 static bool accept_messages = false;
+static std::thread property_service_thread;
 
 static PropertyInfoAreaFile property_info_area;
 
@@ -147,17 +149,6 @@
     return has_access;
 }
 
-static void SendPropertyChanged(const std::string& name, const std::string& value) {
-    auto property_msg = PropertyMessage{};
-    auto* changed_message = property_msg.mutable_changed_message();
-    changed_message->set_name(name);
-    changed_message->set_value(value);
-
-    if (auto result = SendMessage(init_socket, property_msg); !result.ok()) {
-        LOG(ERROR) << "Failed to send property changed message: " << result.error();
-    }
-}
-
 static uint32_t PropertySet(const std::string& name, const std::string& value, std::string* error) {
     size_t valuelen = value.size();
 
@@ -196,47 +187,137 @@
     // 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 (accept_messages) {
-        SendPropertyChanged(name, value);
+        PropertyChanged(name, value);
     }
     return PROP_SUCCESS;
 }
 
-class AsyncRestorecon {
+template <typename T>
+class SingleThreadExecutor {
   public:
-    void TriggerRestorecon(const std::string& path) {
-        auto guard = std::lock_guard{mutex_};
-        paths_.emplace(path);
+    virtual ~SingleThreadExecutor() {}
 
-        if (!thread_started_) {
-            thread_started_ = true;
-            std::thread{&AsyncRestorecon::ThreadFunction, this}.detach();
+    template <typename F = T>
+    void Run(F&& item) {
+        auto guard = std::lock_guard{mutex_};
+        items_.emplace(std::forward<F>(item));
+
+        if (thread_state_ == ThreadState::kRunning || thread_state_ == ThreadState::kStopped) {
+            return;
+        }
+
+        if (thread_state_ == ThreadState::kPendingJoin) {
+            thread_.join();
+        }
+
+        StartThread();
+    }
+
+    void StopAndJoin() {
+        auto lock = std::unique_lock{mutex_};
+        if (thread_state_ == ThreadState::kPendingJoin) {
+            thread_.join();
+        } else if (thread_state_ == ThreadState::kRunning) {
+            thread_state_ = ThreadState::kStopped;
+            lock.unlock();
+            thread_.join();
+            lock.lock();
+        }
+
+        thread_state_ = ThreadState::kStopped;
+    }
+
+    void Restart() {
+        auto guard = std::lock_guard{mutex_};
+        if (items_.empty()) {
+            thread_state_ = ThreadState::kNotStarted;
+        } else {
+            StartThread();
+        }
+    }
+
+    void MaybeJoin() {
+        auto guard = std::lock_guard{mutex_};
+        if (thread_state_ == ThreadState::kPendingJoin) {
+            thread_.join();
+            thread_state_ = ThreadState::kNotStarted;
         }
     }
 
   private:
+    virtual void Execute(T&& item) = 0;
+
+    void StartThread() {
+        thread_state_ = ThreadState::kRunning;
+        auto thread = std::thread{&SingleThreadExecutor::ThreadFunction, this};
+        std::swap(thread_, thread);
+    }
+
     void ThreadFunction() {
         auto lock = std::unique_lock{mutex_};
 
-        while (!paths_.empty()) {
-            auto path = paths_.front();
-            paths_.pop();
+        while (!items_.empty()) {
+            auto item = items_.front();
+            items_.pop();
 
             lock.unlock();
-            if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
-                LOG(ERROR) << "Asynchronous restorecon of '" << path << "' failed'";
-            }
-            android::base::SetProperty(kRestoreconProperty, path);
+            Execute(std::move(item));
             lock.lock();
         }
 
-        thread_started_ = false;
+        if (thread_state_ != ThreadState::kStopped) {
+            thread_state_ = ThreadState::kPendingJoin;
+        }
     }
 
     std::mutex mutex_;
-    std::queue<std::string> paths_;
-    bool thread_started_ = false;
+    std::queue<T> items_;
+    enum class ThreadState {
+        kNotStarted,  // Initial state when starting the program or when restarting with no items to
+                      // process.
+        kRunning,     // The thread is running and is in a state that it will process new items if
+                      // are run.
+        kPendingJoin,  // The thread has run to completion and is pending join().  A new thread must
+                       // be launched for new items to be processed.
+        kStopped,  // This executor has stopped and will not process more items until Restart() is
+                   // called.  Currently pending items will be processed and the thread will be
+                   // joined.
+    };
+    ThreadState thread_state_ = ThreadState::kNotStarted;
+    std::thread thread_;
 };
 
+class RestoreconThread : public SingleThreadExecutor<std::string> {
+    virtual void Execute(std::string&& path) override {
+        if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
+            LOG(ERROR) << "Asynchronous restorecon of '" << path << "' failed'";
+        }
+        android::base::SetProperty(kRestoreconProperty, path);
+    }
+};
+
+struct ControlMessageInfo {
+    std::string message;
+    std::string name;
+    pid_t pid;
+    int fd;
+};
+
+class ControlMessageThread : public SingleThreadExecutor<ControlMessageInfo> {
+    virtual void Execute(ControlMessageInfo&& info) override {
+        bool success = HandleControlMessage(info.message, info.name, info.pid);
+
+        uint32_t response = success ? PROP_SUCCESS : PROP_ERROR_HANDLE_CONTROL_MESSAGE;
+        if (info.fd != -1) {
+            TEMP_FAILURE_RETRY(send(info.fd, &response, sizeof(response), 0));
+            close(info.fd);
+        }
+    }
+};
+
+static RestoreconThread restorecon_thread;
+static ControlMessageThread control_message_thread;
+
 class SocketConnection {
   public:
     SocketConnection(int socket, const ucred& cred) : socket_(socket), cred_(cred) {}
@@ -378,29 +459,17 @@
         return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
     }
 
-    auto property_msg = PropertyMessage{};
-    auto* control_message = property_msg.mutable_control_message();
-    control_message->set_msg(msg);
-    control_message->set_name(name);
-    control_message->set_pid(pid);
-
-    // We must release the fd before sending it to init, otherwise there will be a race with init.
-    // If init calls close() before Release(), then fdsan will see the wrong tag and abort().
+    // We must release the fd before spawning the thread, otherwise there will be a race with the
+    // thread. If the thread calls close() before this function calls Release(), then fdsan will see
+    // the wrong tag and abort().
     int fd = -1;
     if (socket != nullptr && SelinuxGetVendorAndroidVersion() > __ANDROID_API_Q__) {
         fd = socket->Release();
-        control_message->set_fd(fd);
     }
 
-    if (auto result = SendMessage(init_socket, property_msg); !result.ok()) {
-        // We've already released the fd above, so if we fail to send the message to init, we need
-        // to manually free it here.
-        if (fd != -1) {
-            close(fd);
-        }
-        *error = "Failed to send control message: " + result.error().message();
-        return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
-    }
+    // Handling a control message likely calls SetProperty, which we must synchronously handle,
+    // therefore we must fork a thread to handle it.
+    control_message_thread.Run({msg, name, pid, fd});
 
     return PROP_SUCCESS;
 }
@@ -502,8 +571,7 @@
     // We use a thread to do this restorecon operation to prevent holding up init, as it may take
     // a long time to complete.
     if (name == kRestoreconProperty && cr.pid != 1 && !value.empty()) {
-        static AsyncRestorecon async_restorecon;
-        async_restorecon.TriggerRestorecon(value);
+        restorecon_thread.Run(value);
         return PROP_SUCCESS;
     }
 
@@ -1082,6 +1150,8 @@
     PropertyLoadBootDefaults();
 }
 
+static bool pause_property_service = false;
+
 static void HandleInitSocket() {
     auto message = ReadMessage(init_socket);
     if (!message.ok()) {
@@ -1116,6 +1186,10 @@
             accept_messages = true;
             break;
         }
+        case InitMessage::kPausePropertyService: {
+            pause_property_service = true;
+            break;
+        }
         default:
             LOG(ERROR) << "Unknown message type from init: " << init_message.msg_case();
     }
@@ -1136,7 +1210,7 @@
         LOG(FATAL) << result.error();
     }
 
-    while (true) {
+    while (!pause_property_service) {
         auto pending_functions = epoll.Wait(std::nullopt);
         if (!pending_functions.ok()) {
             LOG(ERROR) << pending_functions.error();
@@ -1145,9 +1219,34 @@
                 (*function)();
             }
         }
+        control_message_thread.MaybeJoin();
+        restorecon_thread.MaybeJoin();
     }
 }
 
+void SendStopPropertyServiceMessage() {
+    auto init_message = InitMessage{};
+    init_message.set_pause_property_service(true);
+    if (auto result = SendMessage(from_init_socket, init_message); !result.ok()) {
+        LOG(ERROR) << "Failed to send stop property service message: " << result.error();
+    }
+}
+
+void PausePropertyService() {
+    control_message_thread.StopAndJoin();
+    restorecon_thread.StopAndJoin();
+    SendStopPropertyServiceMessage();
+    property_service_thread.join();
+}
+
+void ResumePropertyService() {
+    pause_property_service = false;
+    auto new_thread = std::thread{PropertyServiceThread};
+    property_service_thread.swap(new_thread);
+    restorecon_thread.Restart();
+    control_message_thread.Restart();
+}
+
 void StartPropertyService(int* epoll_socket) {
     InitPropertySet("ro.property_service.version", "2");
 
@@ -1155,7 +1254,7 @@
     if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != 0) {
         PLOG(FATAL) << "Failed to socketpair() between property_service and init";
     }
-    *epoll_socket = sockets[0];
+    *epoll_socket = from_init_socket = sockets[0];
     init_socket = sockets[1];
     accept_messages = true;
 
@@ -1169,7 +1268,8 @@
 
     listen(property_set_fd, 8);
 
-    std::thread{PropertyServiceThread}.detach();
+    auto new_thread = std::thread{PropertyServiceThread};
+    property_service_thread.swap(new_thread);
 }
 
 }  // namespace init
diff --git a/init/property_service.h b/init/property_service.h
index 506d116..e921326 100644
--- a/init/property_service.h
+++ b/init/property_service.h
@@ -31,6 +31,8 @@
 
 void PropertyInit();
 void StartPropertyService(int* epoll_socket);
+void ResumePropertyService();
+void PausePropertyService();
 
 }  // namespace init
 }  // namespace android
diff --git a/init/property_service.proto b/init/property_service.proto
index 08268d9..36245b2 100644
--- a/init/property_service.proto
+++ b/init/property_service.proto
@@ -41,5 +41,6 @@
         bool load_persistent_properties = 1;
         bool stop_sending_messages = 2;
         bool start_sending_messages = 3;
+        bool pause_property_service = 4;
     };
 }
diff --git a/init/reboot.cpp b/init/reboot.cpp
index 048c1e7..f7cc36e 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -85,7 +85,7 @@
 
 static const std::set<std::string> kDebuggingServices{"tombstoned", "logd", "adbd", "console"};
 
-static std::vector<Service*> GetDebuggingServices(bool only_post_data) {
+static std::vector<Service*> GetDebuggingServices(bool only_post_data) REQUIRES(service_lock) {
     std::vector<Service*> ret;
     ret.reserve(kDebuggingServices.size());
     for (const auto& s : ServiceList::GetInstance()) {
@@ -179,7 +179,7 @@
 };
 
 // Turn off backlight while we are performing power down cleanup activities.
-static void TurnOffBacklight() {
+static void TurnOffBacklight() REQUIRES(service_lock) {
     Service* service = ServiceList::GetInstance().FindService("blank_screen");
     if (service == nullptr) {
         LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
@@ -587,6 +587,7 @@
     // Start reboot monitor thread
     sem_post(&reboot_semaphore);
 
+    auto lock = std::lock_guard{service_lock};
     // 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;
@@ -706,6 +707,7 @@
     // Skip wait for prop if it is in progress
     ResetWaitForProp();
     // Clear EXEC flag if there is one pending
+    auto lock = std::lock_guard{service_lock};
     for (const auto& s : ServiceList::GetInstance()) {
         s->UnSetExec();
     }
@@ -749,6 +751,7 @@
         return Error() << "Failed to set sys.init.userspace_reboot.in_progress property";
     }
     EnterShutdown();
+    auto lock = std::lock_guard{service_lock};
     if (!SetProperty("sys.powerctl", "")) {
         return Error() << "Failed to reset sys.powerctl property";
     }
@@ -907,6 +910,7 @@
                 run_fsck = true;
             } else if (cmd_params[1] == "thermal") {
                 // Turn off sources of heat immediately.
+                auto lock = std::lock_guard{service_lock};
                 TurnOffBacklight();
                 // run_fsck is false to avoid delay
                 cmd = ANDROID_RB_THERMOFF;
diff --git a/init/selinux.cpp b/init/selinux.cpp
index c5b7576..2faa167 100644
--- a/init/selinux.cpp
+++ b/init/selinux.cpp
@@ -535,7 +535,9 @@
 
     selinux_android_restorecon("/linkerconfig", 0);
 
-    selinux_android_restorecon(gsi::kDsuAvbKeyDir, SELINUX_ANDROID_RESTORECON_RECURSE);
+    // adb remount, snapshot-based updates, and DSUs all create files during
+    // first-stage init.
+    selinux_android_restorecon("/metadata", SELINUX_ANDROID_RESTORECON_RECURSE);
 }
 
 int SelinuxKlogCallback(int type, const char* fmt, ...) {
diff --git a/init/service.cpp b/init/service.cpp
index 665a1b0..b12d11a 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -40,7 +40,7 @@
 #include "service_list.h"
 #include "util.h"
 
-#if defined(__ANDROID__)
+#ifdef INIT_FULL_SOURCES
 #include <ApexProperties.sysprop.h>
 #include <android/api-level.h>
 
@@ -303,7 +303,7 @@
         return;
     }
 
-#if defined(__ANDROID__)
+#if INIT_FULL_SOURCES
     static bool is_apex_updatable = android::sysprop::ApexProperties::updatable().value_or(false);
 #else
     static bool is_apex_updatable = false;
diff --git a/init/service.h b/init/service.h
index cf3f0c2..d2a4462 100644
--- a/init/service.h
+++ b/init/service.h
@@ -27,12 +27,14 @@
 #include <vector>
 
 #include <android-base/chrono_utils.h>
+#include <android-base/thread_annotations.h>
 #include <cutils/iosched_policy.h>
 
 #include "action.h"
 #include "capabilities.h"
 #include "keyword_map.h"
 #include "parser.h"
+#include "service_lock.h"
 #include "service_utils.h"
 #include "subcontext.h"
 
@@ -77,17 +79,17 @@
 
     bool IsRunning() { return (flags_ & SVC_RUNNING) != 0; }
     bool IsEnabled() { return (flags_ & SVC_DISABLED) == 0; }
-    Result<void> ExecStart();
-    Result<void> Start();
-    Result<void> StartIfNotDisabled();
-    Result<void> StartIfPostData();
-    Result<void> Enable();
+    Result<void> ExecStart() REQUIRES(service_lock);
+    Result<void> Start() REQUIRES(service_lock);
+    Result<void> StartIfNotDisabled() REQUIRES(service_lock);
+    Result<void> StartIfPostData() REQUIRES(service_lock);
+    Result<void> Enable() REQUIRES(service_lock);
     void Reset();
     void ResetIfPostData();
     void Stop();
     void Terminate();
     void Timeout();
-    void Restart();
+    void Restart() REQUIRES(service_lock);
     void Reap(const siginfo_t& siginfo);
     void DumpState() const;
     void SetShutdownCritical() { flags_ |= SVC_SHUTDOWN_CRITICAL; }
diff --git a/init/service_list.h b/init/service_list.h
index 1838624..8cbc878 100644
--- a/init/service_list.h
+++ b/init/service_list.h
@@ -17,9 +17,13 @@
 #pragma once
 
 #include <memory>
+#include <mutex>
 #include <vector>
 
+#include <android-base/thread_annotations.h>
+
 #include "service.h"
+#include "service_lock.h"
 
 namespace android {
 namespace init {
@@ -32,16 +36,16 @@
     ServiceList();
     size_t CheckAllCommands();
 
-    void AddService(std::unique_ptr<Service> service);
-    void RemoveService(const Service& svc);
+    void AddService(std::unique_ptr<Service> service) REQUIRES(service_lock);
+    void RemoveService(const Service& svc) REQUIRES(service_lock);
     template <class UnaryPredicate>
-    void RemoveServiceIf(UnaryPredicate predicate) {
+    void RemoveServiceIf(UnaryPredicate predicate) REQUIRES(service_lock) {
         services_.erase(std::remove_if(services_.begin(), services_.end(), predicate),
                         services_.end());
     }
 
     template <typename T, typename F = decltype(&Service::name)>
-    Service* FindService(T value, F function = &Service::name) const {
+    Service* FindService(T value, F function = &Service::name) const REQUIRES(service_lock) {
         auto svc = std::find_if(services_.begin(), services_.end(),
                                 [&function, &value](const std::unique_ptr<Service>& s) {
                                     return std::invoke(function, s) == value;
@@ -52,7 +56,7 @@
         return nullptr;
     }
 
-    Service* FindInterface(const std::string& interface_name) {
+    Service* FindInterface(const std::string& interface_name) REQUIRES(service_lock) {
         for (const auto& svc : services_) {
             if (svc->interfaces().count(interface_name) > 0) {
                 return svc.get();
@@ -62,18 +66,20 @@
         return nullptr;
     }
 
-    void DumpState() const;
+    void DumpState() const REQUIRES(service_lock);
 
-    auto begin() const { return services_.begin(); }
-    auto end() const { return services_.end(); }
-    const std::vector<std::unique_ptr<Service>>& services() const { return services_; }
-    const std::vector<Service*> services_in_shutdown_order() const;
+    auto begin() const REQUIRES(service_lock) { return services_.begin(); }
+    auto end() const REQUIRES(service_lock) { return services_.end(); }
+    const std::vector<std::unique_ptr<Service>>& services() const REQUIRES(service_lock) {
+        return services_;
+    }
+    const std::vector<Service*> services_in_shutdown_order() const REQUIRES(service_lock);
 
     void MarkPostData();
     bool IsPostData();
-    void MarkServicesUpdate();
+    void MarkServicesUpdate() REQUIRES(service_lock);
     bool IsServicesUpdated() const { return services_update_finished_; }
-    void DelayService(const Service& service);
+    void DelayService(const Service& service) REQUIRES(service_lock);
 
   private:
     std::vector<std::unique_ptr<Service>> services_;
diff --git a/init/service_lock.cpp b/init/service_lock.cpp
new file mode 100644
index 0000000..404d439
--- /dev/null
+++ b/init/service_lock.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2020 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 "service_lock.h"
+
+namespace android {
+namespace init {
+
+RecursiveMutex service_lock;
+
+}  // namespace init
+}  // namespace android
diff --git a/init/service_lock.h b/init/service_lock.h
new file mode 100644
index 0000000..6b94271
--- /dev/null
+++ b/init/service_lock.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2020 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 <mutex>
+
+#include <android-base/thread_annotations.h>
+
+namespace android {
+namespace init {
+
+// This class exists to add thread annotations, since they're absent from std::recursive_mutex.
+
+class CAPABILITY("mutex") RecursiveMutex {
+  public:
+    void lock() ACQUIRE() { mutex_.lock(); }
+    void unlock() RELEASE() { mutex_.unlock(); }
+
+  private:
+    std::recursive_mutex mutex_;
+};
+
+extern RecursiveMutex service_lock;
+
+}  // namespace init
+}  // namespace android
diff --git a/init/service_parser.cpp b/init/service_parser.cpp
index 4b04ba0..51f4c97 100644
--- a/init/service_parser.cpp
+++ b/init/service_parser.cpp
@@ -34,7 +34,7 @@
 #include "service_utils.h"
 #include "util.h"
 
-#if defined(__ANDROID__)
+#ifdef INIT_FULL_SOURCES
 #include <android/api-level.h>
 #include <sys/system_properties.h>
 
@@ -168,6 +168,7 @@
 
     const std::string fullname = interface_name + "/" + instance_name;
 
+    auto lock = std::lock_guard{service_lock};
     for (const auto& svc : *service_list_) {
         if (svc->interfaces().count(fullname) > 0) {
             return Error() << "Interface '" << fullname << "' redefined in " << service_->name()
@@ -598,6 +599,7 @@
         }
     }
 
+    auto lock = std::lock_guard{service_lock};
     Service* old_service = service_list_->FindService(service_->name());
     if (old_service) {
         if (!service_->is_override()) {
diff --git a/init/sigchld_handler.cpp b/init/sigchld_handler.cpp
index 9b2c7d9..064d64d 100644
--- a/init/sigchld_handler.cpp
+++ b/init/sigchld_handler.cpp
@@ -64,6 +64,8 @@
     std::string wait_string;
     Service* service = nullptr;
 
+    auto lock = std::lock_guard{service_lock};
+
     if (SubcontextChildReap(pid)) {
         name = "Subcontext";
     } else {
diff --git a/init/subcontext.cpp b/init/subcontext.cpp
index 3260159..5263c14 100644
--- a/init/subcontext.cpp
+++ b/init/subcontext.cpp
@@ -31,7 +31,7 @@
 #include "proto_utils.h"
 #include "util.h"
 
-#if defined(__ANDROID__)
+#ifdef INIT_FULL_SOURCES
 #include <android/api-level.h>
 #include "property_service.h"
 #include "selabel.h"
diff --git a/init/test_utils/Android.bp b/init/test_utils/Android.bp
deleted file mode 100644
index 1cb05b6..0000000
--- a/init/test_utils/Android.bp
+++ /dev/null
@@ -1,27 +0,0 @@
-cc_library_static {
-    name: "libinit_test_utils",
-    cflags: [
-        "-Wall",
-        "-Wextra",
-        "-Wno-unused-parameter",
-        "-Werror",
-    ],
-    srcs: [
-        "service_utils.cpp",
-    ],
-    shared_libs: [
-        "libcutils",
-        "liblog",
-        "libjsoncpp",
-        "libprotobuf-cpp-lite",
-        "libhidl-gen-utils",
-    ],
-    whole_static_libs: [
-        "libinit",
-        "libpropertyinfoparser",
-    ],
-    static_libs: [
-        "libbase",
-    ],
-    export_include_dirs: ["include"], // for tests
-}
diff --git a/init/util.cpp b/init/util.cpp
index 503c705..24f94ec 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -41,7 +41,7 @@
 #include <cutils/sockets.h>
 #include <selinux/android.h>
 
-#if defined(__ANDROID__)
+#ifdef INIT_FULL_SOURCES
 #include <android/api-level.h>
 #include <sys/system_properties.h>
 
diff --git a/libcutils/include/private/android_filesystem_config.h b/libcutils/include/private/android_filesystem_config.h
index a2d36ff..b73a29b 100644
--- a/libcutils/include/private/android_filesystem_config.h
+++ b/libcutils/include/private/android_filesystem_config.h
@@ -133,6 +133,7 @@
 #define AID_EXTERNAL_STORAGE 1077 /* Full external storage access including USB OTG volumes */
 #define AID_EXT_DATA_RW 1078      /* GID for app-private data directories on external storage */
 #define AID_EXT_OBB_RW 1079       /* GID for OBB directories on external storage */
+#define AID_CONTEXT_HUB 1080      /* GID for access to the Context Hub */
 /* Changes to this file must be made in AOSP, *not* in internal branches. */
 
 #define AID_SHELL 2000 /* adb and debug shell user */
diff --git a/liblog/logger_write.cpp b/liblog/logger_write.cpp
index cf82e0f..1b6b0c6 100644
--- a/liblog/logger_write.cpp
+++ b/liblog/logger_write.cpp
@@ -348,7 +348,7 @@
     return 0;
   }
 
-  char buf[LOG_BUF_SIZE];
+  __attribute__((uninitialized)) char buf[LOG_BUF_SIZE];
 
   vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
 
@@ -366,7 +366,7 @@
   }
 
   va_list ap;
-  char buf[LOG_BUF_SIZE];
+  __attribute__((uninitialized)) char buf[LOG_BUF_SIZE];
 
   va_start(ap, fmt);
   vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
@@ -386,7 +386,7 @@
   }
 
   va_list ap;
-  char buf[LOG_BUF_SIZE];
+  __attribute__((uninitialized)) char buf[LOG_BUF_SIZE];
 
   va_start(ap, fmt);
   vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
@@ -398,7 +398,7 @@
 }
 
 void __android_log_assert(const char* cond, const char* tag, const char* fmt, ...) {
-  char buf[LOG_BUF_SIZE];
+  __attribute__((uninitialized)) char buf[LOG_BUF_SIZE];
 
   if (fmt) {
     va_list ap;
diff --git a/liblog/tests/liblog_benchmark.cpp b/liblog/tests/liblog_benchmark.cpp
index 39ac7a5..4366f3d 100644
--- a/liblog/tests/liblog_benchmark.cpp
+++ b/liblog/tests/liblog_benchmark.cpp
@@ -27,6 +27,7 @@
 #include <unordered_set>
 
 #include <android-base/file.h>
+#include <android-base/properties.h>
 #include <benchmark/benchmark.h>
 #include <cutils/sockets.h>
 #include <log/event_tag_map.h>
@@ -1025,3 +1026,14 @@
   }
 }
 BENCHMARK(BM_lookupEventTagNum_logd_existing);
+
+static void BM_log_verbose_overhead(benchmark::State& state) {
+  std::string test_log_tag = "liblog_verbose_tag";
+  android::base::SetProperty("log.tag." + test_log_tag, "I");
+  for (auto _ : state) {
+    __android_log_print(ANDROID_LOG_VERBOSE, test_log_tag.c_str(), "%s test log message %d %d",
+                        "test test", 123, 456);
+  }
+  android::base::SetProperty("log.tag." + test_log_tag, "");
+}
+BENCHMARK(BM_log_verbose_overhead);
diff --git a/libutils/String16.cpp b/libutils/String16.cpp
index e2a8c59..d514f29 100644
--- a/libutils/String16.cpp
+++ b/libutils/String16.cpp
@@ -90,19 +90,6 @@
 {
 }
 
-String16::String16(StaticLinkage)
-    : mString(nullptr)
-{
-    // this constructor is used when we can't rely on the static-initializers
-    // having run. In this case we always allocate an empty string. It's less
-    // efficient than using getEmptyString(), but we assume it's uncommon.
-
-    SharedBuffer* buf = static_cast<SharedBuffer*>(alloc(sizeof(char16_t)));
-    char16_t* data = static_cast<char16_t*>(buf->data());
-    data[0] = 0;
-    mString = data;
-}
-
 String16::String16(const String16& o)
     : mString(o.mString)
 {
diff --git a/libutils/String8.cpp b/libutils/String8.cpp
index d13548e..d00e39c 100644
--- a/libutils/String8.cpp
+++ b/libutils/String8.cpp
@@ -125,19 +125,6 @@
 {
 }
 
-String8::String8(StaticLinkage)
-    : mString(nullptr)
-{
-    // this constructor is used when we can't rely on the static-initializers
-    // having run. In this case we always allocate an empty string. It's less
-    // efficient than using getEmptyString(), but we assume it's uncommon.
-
-    char* data = static_cast<char*>(
-            SharedBuffer::alloc(sizeof(char))->data());
-    data[0] = 0;
-    mString = data;
-}
-
 String8::String8(const String8& o)
     : mString(o.mString)
 {
diff --git a/libutils/StrongPointer_test.cpp b/libutils/StrongPointer_test.cpp
index 7b2e37f..d37c1de 100644
--- a/libutils/StrongPointer_test.cpp
+++ b/libutils/StrongPointer_test.cpp
@@ -36,10 +36,8 @@
 
 TEST(StrongPointer, move) {
     bool isDeleted;
-    SPFoo* foo = new SPFoo(&isDeleted);
-    ASSERT_EQ(0, foo->getStrongCount());
-    ASSERT_FALSE(isDeleted) << "Already deleted...?";
-    sp<SPFoo> sp1(foo);
+    sp<SPFoo> sp1 = sp<SPFoo>::make(&isDeleted);
+    SPFoo* foo = sp1.get();
     ASSERT_EQ(1, foo->getStrongCount());
     {
         sp<SPFoo> sp2 = std::move(sp1);
@@ -65,7 +63,7 @@
 
 TEST(StrongPointer, PointerComparison) {
     bool isDeleted;
-    sp<SPFoo> foo = new SPFoo(&isDeleted);
+    sp<SPFoo> foo = sp<SPFoo>::make(&isDeleted);
     ASSERT_EQ(foo.get(), foo);
     ASSERT_EQ(foo, foo.get());
     ASSERT_NE(nullptr, foo);
diff --git a/libutils/include/utils/RefBase.h b/libutils/include/utils/RefBase.h
index 89f048d..e7acd17 100644
--- a/libutils/include/utils/RefBase.h
+++ b/libutils/include/utils/RefBase.h
@@ -297,6 +297,11 @@
     }
 
 protected:
+    // When constructing these objects, prefer using sp::make<>. Using a RefBase
+    // object on the stack or with other refcount mechanisms (e.g.
+    // std::shared_ptr) is inherently wrong. RefBase types have an implicit
+    // ownership model and cannot be safely used with other ownership models.
+
                             RefBase();
     virtual                 ~RefBase();
     
diff --git a/libutils/include/utils/String16.h b/libutils/include/utils/String16.h
index c0e3f1e..013705b 100644
--- a/libutils/include/utils/String16.h
+++ b/libutils/include/utils/String16.h
@@ -39,17 +39,7 @@
 class String16
 {
 public:
-    /*
-     * Use String16(StaticLinkage) if you're statically linking against
-     * libutils and declaring an empty static String16, e.g.:
-     *
-     *   static String16 sAStaticEmptyString(String16::kEmptyString);
-     *   static String16 sAnotherStaticEmptyString(sAStaticEmptyString);
-     */
-    enum StaticLinkage { kEmptyString };
-
                                 String16();
-    explicit                    String16(StaticLinkage);
                                 String16(const String16& o);
                                 String16(const String16& o,
                                          size_t len,
diff --git a/libutils/include/utils/String8.h b/libutils/include/utils/String8.h
index 0ddcbb2..d0ad314 100644
--- a/libutils/include/utils/String8.h
+++ b/libutils/include/utils/String8.h
@@ -39,16 +39,7 @@
 class String8
 {
 public:
-    /* use String8(StaticLinkage) if you're statically linking against
-     * libutils and declaring an empty static String8, e.g.:
-     *
-     *   static String8 sAStaticEmptyString(String8::kEmptyString);
-     *   static String8 sAnotherStaticEmptyString(sAStaticEmptyString);
-     */
-    enum StaticLinkage { kEmptyString };
-
                                 String8();
-    explicit                    String8(StaticLinkage);
                                 String8(const String8& o);
     explicit                    String8(const char* o);
     explicit                    String8(const char* o, size_t numChars);
diff --git a/libutils/include/utils/StrongPointer.h b/libutils/include/utils/StrongPointer.h
index 6f4fb47..11128f2 100644
--- a/libutils/include/utils/StrongPointer.h
+++ b/libutils/include/utils/StrongPointer.h
@@ -32,6 +32,12 @@
 public:
     inline sp() : m_ptr(nullptr) { }
 
+    // TODO: switch everyone to using this over new, and make RefBase operator
+    // new private to that class so that we can avoid RefBase being used with
+    // other memory management mechanisms.
+    template <typename... Args>
+    static inline sp<T> make(Args&&... args);
+
     sp(T* other);  // NOLINT(implicit)
     sp(const sp<T>& other);
     sp(sp<T>&& other) noexcept;
@@ -160,9 +166,6 @@
 // It does not appear safe to broaden this check to include adjacent pages; apparently this code
 // is used in environments where there may not be a guard page below (at higher addresses than)
 // the bottom of the stack.
-//
-// TODO: Consider adding make_sp<T>() to allocate an object and wrap the resulting pointer safely
-// without checking overhead.
 template <typename T>
 void sp<T>::check_not_on_stack(const void* ptr) {
     static constexpr int MIN_PAGE_SIZE = 0x1000;  // 4K. Safer than including sys/user.h.
@@ -174,6 +177,18 @@
     }
 }
 
+// TODO: Ideally we should find a way to increment the reference count before running the
+// constructor, so that generating an sp<> to this in the constructor is no longer dangerous.
+template <typename T>
+template <typename... Args>
+sp<T> sp<T>::make(Args&&... args) {
+    T* t = new T(std::forward<Args>(args)...);
+    sp<T> result;
+    result.m_ptr = t;
+    t->incStrong(t);  // bypass check_not_on_stack for heap allocation
+    return result;
+}
+
 template<typename T>
 sp<T>::sp(T* other)
         : m_ptr(other) {
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 834b20b..1cf2061 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -207,31 +207,37 @@
     // exact entry with time specified in ms or us precision.
     if ((realtime.tv_nsec % 1000) == 0) ++realtime.tv_nsec;
 
-    LogBufferElement* elem =
-        new LogBufferElement(log_id, realtime, uid, pid, tid, msg, len);
-    if (log_id != LOG_ID_SECURITY) {
-        int prio = ANDROID_LOG_INFO;
-        const char* tag = nullptr;
-        size_t tag_len = 0;
-        if (log_id == LOG_ID_EVENTS || log_id == LOG_ID_STATS) {
-            tag = tagToName(elem->getTag());
-            if (tag) {
-                tag_len = strlen(tag);
-            }
-        } else {
-            prio = *msg;
-            tag = msg + 1;
-            tag_len = strnlen(tag, len - 1);
+    LogBufferElement* elem = new LogBufferElement(log_id, realtime, uid, pid, tid, msg, len);
+
+    // b/137093665: don't coalesce security messages.
+    if (log_id == LOG_ID_SECURITY) {
+        wrlock();
+        log(elem);
+        unlock();
+
+        return len;
+    }
+
+    int prio = ANDROID_LOG_INFO;
+    const char* tag = nullptr;
+    size_t tag_len = 0;
+    if (log_id == LOG_ID_EVENTS || log_id == LOG_ID_STATS) {
+        tag = tagToName(elem->getTag());
+        if (tag) {
+            tag_len = strlen(tag);
         }
-        if (!__android_log_is_loggable_len(prio, tag, tag_len,
-                                           ANDROID_LOG_VERBOSE)) {
-            // Log traffic received to total
-            wrlock();
-            stats.addTotal(elem);
-            unlock();
-            delete elem;
-            return -EACCES;
-        }
+    } else {
+        prio = *msg;
+        tag = msg + 1;
+        tag_len = strnlen(tag, len - 1);
+    }
+    if (!__android_log_is_loggable_len(prio, tag, tag_len, ANDROID_LOG_VERBOSE)) {
+        // Log traffic received to total
+        wrlock();
+        stats.addTotal(elem);
+        unlock();
+        delete elem;
+        return -EACCES;
     }
 
     wrlock();
diff --git a/trusty/keymaster/Android.bp b/trusty/keymaster/Android.bp
index f32a69e..6840baa 100644
--- a/trusty/keymaster/Android.bp
+++ b/trusty/keymaster/Android.bp
@@ -14,70 +14,6 @@
 // limitations under the License.
 //
 
-// WARNING: Everything listed here will be built on ALL platforms,
-// including x86, the emulator, and the SDK.  Modules must be uniquely
-// named (liblights.panda), and must build everywhere, or limit themselves
-// to only building on ARM if they include assembly. Individual makefiles
-// are responsible for having their own logic, for fine-grained control.
-
-// trusty_keymaster is a binary used only for on-device testing.  It
-// runs Trusty Keymaster through a basic set of operations with RSA
-// and ECDSA keys.
-cc_binary {
-    name: "trusty_keymaster_tipc",
-    vendor: true,
-    srcs: [
-        "ipc/trusty_keymaster_ipc.cpp",
-        "legacy/trusty_keymaster_device.cpp",
-        "legacy/trusty_keymaster_main.cpp",
-    ],
-    cflags: [
-        "-Wall",
-        "-Werror",
-    ],
-
-    local_include_dirs: ["include"],
-
-    shared_libs: [
-        "libcrypto",
-        "libcutils",
-        "libkeymaster_portable",
-        "libtrusty",
-        "libkeymaster_messages",
-        "libsoftkeymasterdevice",
-        "liblog",
-    ],
-}
-
-// keystore.trusty is the HAL used by keystore on Trusty devices.
-cc_library_shared {
-    name: "keystore.trusty",
-    vendor: true,
-    relative_install_path: "hw",
-    srcs: [
-        "ipc/trusty_keymaster_ipc.cpp",
-        "legacy/module.cpp",
-        "legacy/trusty_keymaster_device.cpp",
-    ],
-
-    cflags: [
-        "-fvisibility=hidden",
-        "-Wall",
-        "-Werror",
-    ],
-
-    local_include_dirs: ["include"],
-
-    shared_libs: [
-        "libcrypto",
-        "libkeymaster_messages",
-        "libtrusty",
-        "liblog",
-        "libcutils",
-    ],
-    header_libs: ["libhardware_headers"],
-}
-
 cc_binary {
     name: "android.hardware.keymaster@3.0-service.trusty",
     defaults: ["hidl_defaults"],
diff --git a/trusty/keymaster/legacy/Makefile b/trusty/keymaster/legacy/Makefile
deleted file mode 100644
index f575381..0000000
--- a/trusty/keymaster/legacy/Makefile
+++ /dev/null
@@ -1,199 +0,0 @@
-#####
-# Local unit test Makefile
-#
-# This makefile builds and runs the trusty_keymaster unit tests locally on the development
-# machine, not on an Android device.
-#
-# To build and run these tests, one pre-requisite must be manually installed: BoringSSL.
-# This Makefile expects to find BoringSSL in a directory adjacent to $ANDROID_BUILD_TOP.
-# To get and build it, first install the Ninja build tool (e.g. apt-get install
-# ninja-build), then do:
-#
-# cd $ANDROID_BUILD_TOP/..
-# git clone https://boringssl.googlesource.com/boringssl
-# cd boringssl
-# mdkir build
-# cd build
-# cmake -GNinja ..
-# ninja
-#
-# Then return to $ANDROID_BUILD_TOP/system/keymaster and run "make".
-#####
-
-BASE=../../../..
-SUBS=system/core \
-	system/keymaster \
-	hardware/libhardware \
-	external/gtest
-GTEST=$(BASE)/external/gtest
-KM=$(BASE)/system/keymaster
-
-INCLUDES=$(foreach dir,$(SUBS),-I $(BASE)/$(dir)/include) \
-	-I $(BASE)/libnativehelper/include/nativehelper \
-	-I ../tipc/include \
-	-I $(BASE)/system/keymaster \
-	-I $(GTEST) \
-	-I$(BASE)/../boringssl/include
-
-ifdef USE_CLANG
-CC=/usr/bin/clang
-CXX=/usr/bin/clang
-CLANG_TEST_DEFINE=-DKEYMASTER_CLANG_TEST_BUILD
-COMPILER_SPECIFIC_ARGS=-std=c++11 $(CLANG_TEST_DEFINE)
-else
-COMPILER_SPECIFIC_ARGS=-std=c++0x -fprofile-arcs
-endif
-
-CPPFLAGS=$(INCLUDES) -g -O0 -MD
-CXXFLAGS=-Wall -Werror -Wno-unused -Winit-self -Wpointer-arith	-Wunused-parameter \
-	-Wmissing-declarations -ftest-coverage \
-	-Wno-deprecated-declarations -fno-exceptions -DKEYMASTER_NAME_TAGS \
-	$(COMPILER_SPECIFIC_ARGS)
-LDLIBS=-L$(BASE)/../boringssl/build/crypto -lcrypto -lpthread -lstdc++
-
-CPPSRCS=\
-	$(KM)/aead_mode_operation.cpp \
-	$(KM)/aes_key.cpp \
-	$(KM)/aes_operation.cpp \
-	$(KM)/android_keymaster.cpp \
-	$(KM)/android_keymaster_messages.cpp \
-	$(KM)/android_keymaster_messages_test.cpp \
-	$(KM)/android_keymaster_test.cpp \
-	$(KM)/android_keymaster_test_utils.cpp \
-	$(KM)/android_keymaster_utils.cpp \
-	$(KM)/asymmetric_key.cpp \
-	$(KM)/auth_encrypted_key_blob.cpp \
-	$(KM)/auth_encrypted_key_blob.cpp \
-	$(KM)/authorization_set.cpp \
-	$(KM)/authorization_set_test.cpp \
-	$(KM)/ec_key.cpp \
-	$(KM)/ec_keymaster0_key.cpp \
-	$(KM)/ecdsa_operation.cpp \
-	$(KM)/hmac_key.cpp \
-	$(KM)/hmac_operation.cpp \
-	$(KM)/integrity_assured_key_blob.cpp \
-	$(KM)/key.cpp \
-	$(KM)/key_blob_test.cpp \
-	$(KM)/keymaster0_engine.cpp \
-	$(KM)/logger.cpp \
-	$(KM)/ocb_utils.cpp \
-	$(KM)/openssl_err.cpp \
-	$(KM)/openssl_utils.cpp \
-	$(KM)/operation.cpp \
-	$(KM)/operation_table.cpp \
-	$(KM)/rsa_key.cpp \
-	$(KM)/rsa_keymaster0_key.cpp \
-	$(KM)/rsa_operation.cpp \
-	$(KM)/serializable.cpp \
-	$(KM)/soft_keymaster_context.cpp \
-	$(KM)/symmetric_key.cpp \
-	$(KM)/unencrypted_key_blob.cpp \
-	trusty_keymaster_device.cpp \
-	trusty_keymaster_device_test.cpp
-CCSRCS=$(GTEST)/src/gtest-all.cc
-CSRCS=ocb.c
-
-OBJS=$(CPPSRCS:.cpp=.o) $(CCSRCS:.cc=.o) $(CSRCS:.c=.o)
-DEPS=$(CPPSRCS:.cpp=.d) $(CCSRCS:.cc=.d) $(CSRCS:.c=.d)
-GCDA=$(CPPSRCS:.cpp=.gcda) $(CCSRCS:.cc=.gcda) $(CSRCS:.c=.gcda)
-GCNO=$(CPPSRCS:.cpp=.gcno) $(CCSRCS:.cc=.gcno) $(CSRCS:.c=.gcno)
-
-LINK.o=$(LINK.cc)
-
-BINARIES=trusty_keymaster_device_test
-
-ifdef TRUSTY
-BINARIES += trusty_keymaster_device_test
-endif # TRUSTY
-
-.PHONY: coverage memcheck massif clean run
-
-%.run: %
-	./$<
-	touch $@
-
-run: $(BINARIES:=.run)
-
-coverage: coverage.info
-	genhtml coverage.info --output-directory coverage
-
-coverage.info: run
-	lcov --capture --directory=. --output-file coverage.info
-
-%.coverage : %
-	$(MAKE) clean && $(MAKE) $<
-	./$<
-	lcov --capture --directory=. --output-file coverage.info
-	genhtml coverage.info --output-directory coverage
-
-#UNINIT_OPTS=--track-origins=yes
-UNINIT_OPTS=--undef-value-errors=no
-
-MEMCHECK_OPTS=--leak-check=full \
-	--show-reachable=yes \
-	--vgdb=full \
-	$(UNINIT_OPTS) \
-	--error-exitcode=1
-
-MASSIF_OPTS=--tool=massif \
-	--stacks=yes
-
-%.memcheck : %
-	valgrind $(MEMCHECK_OPTS) ./$< && \
-	touch $@
-
-%.massif : %
-	valgrind $(MASSIF_OPTS) --massif-out-file=$@ ./$<
-
-memcheck: $(BINARIES:=.memcheck)
-
-massif: $(BINARIES:=.massif)
-
-trusty_keymaster_device_test: trusty_keymaster_device_test.o \
-	trusty_keymaster_device.o \
-	$(KM)/aead_mode_operation.o \
-	$(KM)/aes_key.o \
-	$(KM)/aes_operation.o \
-	$(KM)/android_keymaster.o \
-	$(KM)/android_keymaster_messages.o \
-	$(KM)/android_keymaster_test_utils.o \
-	$(KM)/android_keymaster_utils.o \
-	$(KM)/asymmetric_key.o \
-	$(KM)/auth_encrypted_key_blob.o \
-	$(KM)/auth_encrypted_key_blob.o \
-	$(KM)/authorization_set.o \
-	$(KM)/ec_key.o \
-	$(KM)/ec_keymaster0_key.cpp \
-	$(KM)/ecdsa_operation.o \
-	$(KM)/hmac_key.o \
-	$(KM)/hmac_operation.o \
-	$(KM)/integrity_assured_key_blob.o \
-	$(KM)/key.o \
-	$(KM)/keymaster0_engine.o \
-	$(KM)/logger.o \
-	$(KM)/ocb.o \
-	$(KM)/ocb_utils.o \
-	$(KM)/openssl_err.o \
-	$(KM)/openssl_utils.o \
-	$(KM)/operation.o \
-	$(KM)/operation_table.o \
-	$(KM)/rsa_key.o \
-	$(KM)/rsa_keymaster0_key.o \
-	$(KM)/rsa_operation.o \
-	$(KM)/serializable.o \
-	$(KM)/soft_keymaster_context.o \
-	$(KM)/symmetric_key.o \
-	$(GTEST)/src/gtest-all.o
-
-$(GTEST)/src/gtest-all.o: CXXFLAGS:=$(subst -Wmissing-declarations,,$(CXXFLAGS))
-ocb.o: CFLAGS=$(CLANG_TEST_DEFINE)
-
-clean:
-	rm -f $(OBJS) $(DEPS) $(GCDA) $(GCNO) $(BINARIES) \
-		$(BINARIES:=.run) $(BINARIES:=.memcheck) $(BINARIES:=.massif) \
-		coverage.info
-	rm -rf coverage
-
--include $(CPPSRCS:.cpp=.d)
--include $(CCSRCS:.cc=.d)
-
diff --git a/trusty/keymaster/legacy/module.cpp b/trusty/keymaster/legacy/module.cpp
deleted file mode 100644
index 7aa1a4e..0000000
--- a/trusty/keymaster/legacy/module.cpp
+++ /dev/null
@@ -1,62 +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 <errno.h>
-#include <string.h>
-
-#include <hardware/hardware.h>
-#include <hardware/keymaster0.h>
-
-#include <trusty_keymaster/legacy/trusty_keymaster_device.h>
-
-using keymaster::TrustyKeymasterDevice;
-
-/*
- * Generic device handling
- */
-static int trusty_keymaster_open(const hw_module_t* module, const char* name,
-                                 hw_device_t** device) {
-    if (strcmp(name, KEYSTORE_KEYMASTER) != 0) {
-        return -EINVAL;
-    }
-
-    TrustyKeymasterDevice* dev = new TrustyKeymasterDevice(module);
-    if (dev == NULL) {
-        return -ENOMEM;
-    }
-    *device = dev->hw_device();
-    // Do not delete dev; it will get cleaned up when the caller calls device->close(), and must
-    // exist until then.
-    return 0;
-}
-
-static struct hw_module_methods_t keystore_module_methods = {
-        .open = trusty_keymaster_open,
-};
-
-struct keystore_module HAL_MODULE_INFO_SYM __attribute__((visibility("default"))) = {
-        .common =
-                {
-                        .tag = HARDWARE_MODULE_TAG,
-                        .module_api_version = KEYMASTER_MODULE_API_VERSION_2_0,
-                        .hal_api_version = HARDWARE_HAL_API_VERSION,
-                        .id = KEYSTORE_HARDWARE_MODULE_ID,
-                        .name = "Trusty Keymaster HAL",
-                        .author = "The Android Open Source Project",
-                        .methods = &keystore_module_methods,
-                        .dso = 0,
-                        .reserved = {},
-                },
-};
diff --git a/trusty/keymaster/legacy/trusty_keymaster_device.cpp b/trusty/keymaster/legacy/trusty_keymaster_device.cpp
deleted file mode 100644
index 88c3e7b..0000000
--- a/trusty/keymaster/legacy/trusty_keymaster_device.cpp
+++ /dev/null
@@ -1,761 +0,0 @@
-/*
- * Copyright 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 "TrustyKeymaster"
-
-#include <assert.h>
-#include <errno.h>
-#include <openssl/evp.h>
-#include <openssl/x509.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-
-#include <algorithm>
-#include <type_traits>
-
-#include <hardware/keymaster2.h>
-#include <keymaster/authorization_set.h>
-#include <log/log.h>
-
-#include <trusty_keymaster/ipc/keymaster_ipc.h>
-#include <trusty_keymaster/ipc/trusty_keymaster_ipc.h>
-#include <trusty_keymaster/legacy/trusty_keymaster_device.h>
-
-const size_t kMaximumAttestationChallengeLength = 128;
-const size_t kMaximumFinishInputLength = 2048;
-
-namespace keymaster {
-
-TrustyKeymasterDevice::TrustyKeymasterDevice(const hw_module_t* module) {
-    static_assert(std::is_standard_layout<TrustyKeymasterDevice>::value,
-                  "TrustyKeymasterDevice must be standard layout");
-    static_assert(offsetof(TrustyKeymasterDevice, device_) == 0,
-                  "device_ must be the first member of TrustyKeymasterDevice");
-    static_assert(offsetof(TrustyKeymasterDevice, device_.common) == 0,
-                  "common must be the first member of keymaster2_device");
-
-    ALOGI("Creating device");
-    ALOGD("Device address: %p", this);
-
-    device_ = {};
-
-    device_.common.tag = HARDWARE_DEVICE_TAG;
-    device_.common.version = 1;
-    device_.common.module = const_cast<hw_module_t*>(module);
-    device_.common.close = close_device;
-
-    device_.flags = KEYMASTER_SUPPORTS_EC;
-
-    device_.configure = configure;
-    device_.add_rng_entropy = add_rng_entropy;
-    device_.generate_key = generate_key;
-    device_.get_key_characteristics = get_key_characteristics;
-    device_.import_key = import_key;
-    device_.export_key = export_key;
-    device_.attest_key = attest_key;
-    device_.upgrade_key = upgrade_key;
-    device_.delete_key = delete_key;
-    device_.delete_all_keys = delete_all_keys;
-    device_.begin = begin;
-    device_.update = update;
-    device_.finish = finish;
-    device_.abort = abort;
-
-    int rc = trusty_keymaster_connect();
-    error_ = translate_error(rc);
-    if (rc < 0) {
-        ALOGE("failed to connect to keymaster (%d)", rc);
-        return;
-    }
-
-    GetVersionRequest version_request;
-    GetVersionResponse version_response;
-    error_ = trusty_keymaster_send(KM_GET_VERSION, version_request, &version_response);
-    if (error_ == KM_ERROR_INVALID_ARGUMENT || error_ == KM_ERROR_UNIMPLEMENTED) {
-        ALOGE("\"Bad parameters\" error on GetVersion call.  Version 0 is not supported.");
-        error_ = KM_ERROR_VERSION_MISMATCH;
-        return;
-    }
-    message_version_ = MessageVersion(version_response.major_ver, version_response.minor_ver,
-                                      version_response.subminor_ver);
-    if (message_version_ < 0) {
-        // Can't translate version?  Keymaster implementation must be newer.
-        ALOGE("Keymaster version %d.%d.%d not supported.", version_response.major_ver,
-              version_response.minor_ver, version_response.subminor_ver);
-        error_ = KM_ERROR_VERSION_MISMATCH;
-    }
-}
-
-TrustyKeymasterDevice::~TrustyKeymasterDevice() {
-    trusty_keymaster_disconnect();
-}
-
-namespace {
-
-// Allocates a new buffer with malloc and copies the contents of |buffer| to it. Caller takes
-// ownership of the returned buffer.
-uint8_t* DuplicateBuffer(const uint8_t* buffer, size_t size) {
-    uint8_t* tmp = reinterpret_cast<uint8_t*>(malloc(size));
-    if (tmp) {
-        memcpy(tmp, buffer, size);
-    }
-    return tmp;
-}
-
-template <typename RequestType>
-void AddClientAndAppData(const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
-                         RequestType* request) {
-    request->additional_params.Clear();
-    if (client_id && client_id->data_length > 0) {
-        request->additional_params.push_back(TAG_APPLICATION_ID, *client_id);
-    }
-    if (app_data && app_data->data_length > 0) {
-        request->additional_params.push_back(TAG_APPLICATION_DATA, *app_data);
-    }
-}
-
-}  //  unnamed namespace
-
-keymaster_error_t TrustyKeymasterDevice::configure(const keymaster_key_param_set_t* params) {
-    ALOGD("Device received configure\n");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (!params) {
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-    }
-
-    AuthorizationSet params_copy(*params);
-    ConfigureRequest request(message_version_);
-    if (!params_copy.GetTagValue(TAG_OS_VERSION, &request.os_version) ||
-        !params_copy.GetTagValue(TAG_OS_PATCHLEVEL, &request.os_patchlevel)) {
-        ALOGD("Configuration parameters must contain OS version and patch level");
-        return KM_ERROR_INVALID_ARGUMENT;
-    }
-
-    ConfigureResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_CONFIGURE, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::add_rng_entropy(const uint8_t* data, size_t data_length) {
-    ALOGD("Device received add_rng_entropy");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-
-    AddEntropyRequest request(message_version_);
-    request.random_data.Reinitialize(data, data_length);
-    AddEntropyResponse response(message_version_);
-    return trusty_keymaster_send(KM_ADD_RNG_ENTROPY, request, &response);
-}
-
-keymaster_error_t TrustyKeymasterDevice::generate_key(
-        const keymaster_key_param_set_t* params, keymaster_key_blob_t* key_blob,
-        keymaster_key_characteristics_t* characteristics) {
-    ALOGD("Device received generate_key");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (!params) {
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-    }
-    if (!key_blob) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    GenerateKeyRequest request(message_version_);
-    request.key_description.Reinitialize(*params);
-    request.key_description.push_back(TAG_CREATION_DATETIME, java_time(time(NULL)));
-
-    GenerateKeyResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_GENERATE_KEY, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    key_blob->key_material_size = response.key_blob.key_material_size;
-    key_blob->key_material =
-            DuplicateBuffer(response.key_blob.key_material, response.key_blob.key_material_size);
-    if (!key_blob->key_material) {
-        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-    }
-
-    if (characteristics) {
-        response.enforced.CopyToParamSet(&characteristics->hw_enforced);
-        response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
-    }
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::get_key_characteristics(
-        const keymaster_key_blob_t* key_blob, const keymaster_blob_t* client_id,
-        const keymaster_blob_t* app_data, keymaster_key_characteristics_t* characteristics) {
-    ALOGD("Device received get_key_characteristics");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (!key_blob || !key_blob->key_material) {
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-    }
-    if (!characteristics) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    GetKeyCharacteristicsRequest request(message_version_);
-    request.SetKeyMaterial(*key_blob);
-    AddClientAndAppData(client_id, app_data, &request);
-
-    GetKeyCharacteristicsResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_GET_KEY_CHARACTERISTICS, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    response.enforced.CopyToParamSet(&characteristics->hw_enforced);
-    response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::import_key(
-        const keymaster_key_param_set_t* params, keymaster_key_format_t key_format,
-        const keymaster_blob_t* key_data, keymaster_key_blob_t* key_blob,
-        keymaster_key_characteristics_t* characteristics) {
-    ALOGD("Device received import_key");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (!params || !key_data) {
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-    }
-    if (!key_blob) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    ImportKeyRequest request(message_version_);
-    request.key_description.Reinitialize(*params);
-    request.key_description.push_back(TAG_CREATION_DATETIME, java_time(time(NULL)));
-
-    request.key_format = key_format;
-    request.SetKeyMaterial(key_data->data, key_data->data_length);
-
-    ImportKeyResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_IMPORT_KEY, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    key_blob->key_material_size = response.key_blob.key_material_size;
-    key_blob->key_material =
-            DuplicateBuffer(response.key_blob.key_material, response.key_blob.key_material_size);
-    if (!key_blob->key_material) {
-        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-    }
-
-    if (characteristics) {
-        response.enforced.CopyToParamSet(&characteristics->hw_enforced);
-        response.unenforced.CopyToParamSet(&characteristics->sw_enforced);
-    }
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::export_key(keymaster_key_format_t export_format,
-                                                    const keymaster_key_blob_t* key_to_export,
-                                                    const keymaster_blob_t* client_id,
-                                                    const keymaster_blob_t* app_data,
-                                                    keymaster_blob_t* export_data) {
-    ALOGD("Device received export_key");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (!key_to_export || !key_to_export->key_material) {
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-    }
-    if (!export_data) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    export_data->data = nullptr;
-    export_data->data_length = 0;
-
-    ExportKeyRequest request(message_version_);
-    request.key_format = export_format;
-    request.SetKeyMaterial(*key_to_export);
-    AddClientAndAppData(client_id, app_data, &request);
-
-    ExportKeyResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_EXPORT_KEY, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    export_data->data_length = response.key_data_length;
-    export_data->data = DuplicateBuffer(response.key_data, response.key_data_length);
-    if (!export_data->data) {
-        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-    }
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::attest_key(const keymaster_key_blob_t* key_to_attest,
-                                                    const keymaster_key_param_set_t* attest_params,
-                                                    keymaster_cert_chain_t* cert_chain) {
-    ALOGD("Device received attest_key");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (!key_to_attest || !attest_params) {
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-    }
-    if (!cert_chain) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    cert_chain->entry_count = 0;
-    cert_chain->entries = nullptr;
-
-    AttestKeyRequest request(message_version_);
-    request.SetKeyMaterial(*key_to_attest);
-    request.attest_params.Reinitialize(*attest_params);
-
-    keymaster_blob_t attestation_challenge = {};
-    request.attest_params.GetTagValue(TAG_ATTESTATION_CHALLENGE, &attestation_challenge);
-    if (attestation_challenge.data_length > kMaximumAttestationChallengeLength) {
-        ALOGE("%zu-byte attestation challenge; only %zu bytes allowed",
-              attestation_challenge.data_length, kMaximumAttestationChallengeLength);
-        return KM_ERROR_INVALID_INPUT_LENGTH;
-    }
-
-    AttestKeyResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_ATTEST_KEY, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    // Allocate and clear storage for cert_chain.
-    keymaster_cert_chain_t& rsp_chain = response.certificate_chain;
-    cert_chain->entries = reinterpret_cast<keymaster_blob_t*>(
-            malloc(rsp_chain.entry_count * sizeof(*cert_chain->entries)));
-    if (!cert_chain->entries) {
-        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-    }
-    cert_chain->entry_count = rsp_chain.entry_count;
-    for (keymaster_blob_t& entry : array_range(cert_chain->entries, cert_chain->entry_count)) {
-        entry = {};
-    }
-
-    // Copy cert_chain contents
-    size_t i = 0;
-    for (keymaster_blob_t& entry : array_range(rsp_chain.entries, rsp_chain.entry_count)) {
-        cert_chain->entries[i].data = DuplicateBuffer(entry.data, entry.data_length);
-        if (!cert_chain->entries[i].data) {
-            keymaster_free_cert_chain(cert_chain);
-            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-        }
-        cert_chain->entries[i].data_length = entry.data_length;
-        ++i;
-    }
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::upgrade_key(
-        const keymaster_key_blob_t* key_to_upgrade, const keymaster_key_param_set_t* upgrade_params,
-        keymaster_key_blob_t* upgraded_key) {
-    ALOGD("Device received upgrade_key");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (!key_to_upgrade || !upgrade_params) {
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-    }
-    if (!upgraded_key) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    UpgradeKeyRequest request(message_version_);
-    request.SetKeyMaterial(*key_to_upgrade);
-    request.upgrade_params.Reinitialize(*upgrade_params);
-
-    UpgradeKeyResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_UPGRADE_KEY, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    upgraded_key->key_material_size = response.upgraded_key.key_material_size;
-    upgraded_key->key_material = DuplicateBuffer(response.upgraded_key.key_material,
-                                                 response.upgraded_key.key_material_size);
-    if (!upgraded_key->key_material) {
-        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-    }
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::begin(keymaster_purpose_t purpose,
-                                               const keymaster_key_blob_t* key,
-                                               const keymaster_key_param_set_t* in_params,
-                                               keymaster_key_param_set_t* out_params,
-                                               keymaster_operation_handle_t* operation_handle) {
-    ALOGD("Device received begin");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (!key || !key->key_material) {
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-    }
-    if (!operation_handle) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    if (out_params) {
-        *out_params = {};
-    }
-
-    BeginOperationRequest request(message_version_);
-    request.purpose = purpose;
-    request.SetKeyMaterial(*key);
-    request.additional_params.Reinitialize(*in_params);
-
-    BeginOperationResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_BEGIN_OPERATION, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    if (response.output_params.size() > 0) {
-        if (out_params) {
-            response.output_params.CopyToParamSet(out_params);
-        } else {
-            return KM_ERROR_OUTPUT_PARAMETER_NULL;
-        }
-    }
-    *operation_handle = response.op_handle;
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::update(keymaster_operation_handle_t operation_handle,
-                                                const keymaster_key_param_set_t* in_params,
-                                                const keymaster_blob_t* input,
-                                                size_t* input_consumed,
-                                                keymaster_key_param_set_t* out_params,
-                                                keymaster_blob_t* output) {
-    ALOGD("Device received update");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (!input) {
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-    }
-    if (!input_consumed) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    if (out_params) {
-        *out_params = {};
-    }
-    if (output) {
-        *output = {};
-    }
-
-    UpdateOperationRequest request(message_version_);
-    request.op_handle = operation_handle;
-    if (in_params) {
-        request.additional_params.Reinitialize(*in_params);
-    }
-    if (input && input->data_length > 0) {
-        size_t max_input_size = TRUSTY_KEYMASTER_SEND_BUF_SIZE - request.SerializedSize();
-        request.input.Reinitialize(input->data, std::min(input->data_length, max_input_size));
-    }
-
-    UpdateOperationResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_UPDATE_OPERATION, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    if (response.output_params.size() > 0) {
-        if (out_params) {
-            response.output_params.CopyToParamSet(out_params);
-        } else {
-            return KM_ERROR_OUTPUT_PARAMETER_NULL;
-        }
-    }
-    *input_consumed = response.input_consumed;
-    if (output) {
-        output->data_length = response.output.available_read();
-        output->data = DuplicateBuffer(response.output.peek_read(), output->data_length);
-        if (!output->data) {
-            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-        }
-    } else if (response.output.available_read() > 0) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::finish(keymaster_operation_handle_t operation_handle,
-                                                const keymaster_key_param_set_t* in_params,
-                                                const keymaster_blob_t* input,
-                                                const keymaster_blob_t* signature,
-                                                keymaster_key_param_set_t* out_params,
-                                                keymaster_blob_t* output) {
-    ALOGD("Device received finish");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-    if (input && input->data_length > kMaximumFinishInputLength) {
-        ALOGE("%zu-byte input to finish; only %zu bytes allowed", input->data_length,
-              kMaximumFinishInputLength);
-        return KM_ERROR_INVALID_INPUT_LENGTH;
-    }
-
-    if (out_params) {
-        *out_params = {};
-    }
-    if (output) {
-        *output = {};
-    }
-
-    FinishOperationRequest request(message_version_);
-    request.op_handle = operation_handle;
-    if (signature && signature->data && signature->data_length > 0) {
-        request.signature.Reinitialize(signature->data, signature->data_length);
-    }
-    if (input && input->data && input->data_length) {
-        request.input.Reinitialize(input->data, input->data_length);
-    }
-    if (in_params) {
-        request.additional_params.Reinitialize(*in_params);
-    }
-
-    FinishOperationResponse response(message_version_);
-    keymaster_error_t err = trusty_keymaster_send(KM_FINISH_OPERATION, request, &response);
-    if (err != KM_ERROR_OK) {
-        return err;
-    }
-
-    if (response.output_params.size() > 0) {
-        if (out_params) {
-            response.output_params.CopyToParamSet(out_params);
-        } else {
-            return KM_ERROR_OUTPUT_PARAMETER_NULL;
-        }
-    }
-    if (output) {
-        output->data_length = response.output.available_read();
-        output->data = DuplicateBuffer(response.output.peek_read(), output->data_length);
-        if (!output->data) {
-            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
-        }
-    } else if (response.output.available_read() > 0) {
-        return KM_ERROR_OUTPUT_PARAMETER_NULL;
-    }
-
-    return KM_ERROR_OK;
-}
-
-keymaster_error_t TrustyKeymasterDevice::abort(keymaster_operation_handle_t operation_handle) {
-    ALOGD("Device received abort");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-
-    AbortOperationRequest request(message_version_);
-    request.op_handle = operation_handle;
-    AbortOperationResponse response(message_version_);
-    return trusty_keymaster_send(KM_ABORT_OPERATION, request, &response);
-}
-
-keymaster_error_t TrustyKeymasterDevice::delete_key(const keymaster_key_blob_t* key) {
-    ALOGD("Device received delete_key");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-
-    if (!key || !key->key_material)
-        return KM_ERROR_UNEXPECTED_NULL_POINTER;
-
-    DeleteKeyRequest request(message_version_);
-    request.SetKeyMaterial(*key);
-    DeleteKeyResponse response(message_version_);
-    return trusty_keymaster_send(KM_DELETE_KEY, request, &response);
-}
-
-keymaster_error_t TrustyKeymasterDevice::delete_all_keys() {
-    ALOGD("Device received delete_all_key");
-
-    if (error_ != KM_ERROR_OK) {
-        return error_;
-    }
-
-    DeleteAllKeysRequest request(message_version_);
-    DeleteAllKeysResponse response(message_version_);
-    return trusty_keymaster_send(KM_DELETE_ALL_KEYS, request, &response);
-}
-
-hw_device_t* TrustyKeymasterDevice::hw_device() {
-    return &device_.common;
-}
-
-static inline TrustyKeymasterDevice* convert_device(const keymaster2_device_t* dev) {
-    return reinterpret_cast<TrustyKeymasterDevice*>(const_cast<keymaster2_device_t*>(dev));
-}
-
-/* static */
-int TrustyKeymasterDevice::close_device(hw_device_t* dev) {
-    delete reinterpret_cast<TrustyKeymasterDevice*>(dev);
-    return 0;
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::configure(const keymaster2_device_t* dev,
-                                                   const keymaster_key_param_set_t* params) {
-    return convert_device(dev)->configure(params);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::add_rng_entropy(const keymaster2_device_t* dev,
-                                                         const uint8_t* data, size_t data_length) {
-    return convert_device(dev)->add_rng_entropy(data, data_length);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::generate_key(
-        const keymaster2_device_t* dev, const keymaster_key_param_set_t* params,
-        keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t* characteristics) {
-    return convert_device(dev)->generate_key(params, key_blob, characteristics);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::get_key_characteristics(
-        const keymaster2_device_t* dev, const keymaster_key_blob_t* key_blob,
-        const keymaster_blob_t* client_id, const keymaster_blob_t* app_data,
-        keymaster_key_characteristics_t* characteristics) {
-    return convert_device(dev)->get_key_characteristics(key_blob, client_id, app_data,
-                                                        characteristics);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::import_key(
-        const keymaster2_device_t* dev, const keymaster_key_param_set_t* params,
-        keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
-        keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t* characteristics) {
-    return convert_device(dev)->import_key(params, key_format, key_data, key_blob, characteristics);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::export_key(const keymaster2_device_t* dev,
-                                                    keymaster_key_format_t export_format,
-                                                    const keymaster_key_blob_t* key_to_export,
-                                                    const keymaster_blob_t* client_id,
-                                                    const keymaster_blob_t* app_data,
-                                                    keymaster_blob_t* export_data) {
-    return convert_device(dev)->export_key(export_format, key_to_export, client_id, app_data,
-                                           export_data);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::attest_key(const keymaster2_device_t* dev,
-                                                    const keymaster_key_blob_t* key_to_attest,
-                                                    const keymaster_key_param_set_t* attest_params,
-                                                    keymaster_cert_chain_t* cert_chain) {
-    return convert_device(dev)->attest_key(key_to_attest, attest_params, cert_chain);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::upgrade_key(
-        const keymaster2_device_t* dev, const keymaster_key_blob_t* key_to_upgrade,
-        const keymaster_key_param_set_t* upgrade_params, keymaster_key_blob_t* upgraded_key) {
-    return convert_device(dev)->upgrade_key(key_to_upgrade, upgrade_params, upgraded_key);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::begin(const keymaster2_device_t* dev,
-                                               keymaster_purpose_t purpose,
-                                               const keymaster_key_blob_t* key,
-                                               const keymaster_key_param_set_t* in_params,
-                                               keymaster_key_param_set_t* out_params,
-                                               keymaster_operation_handle_t* operation_handle) {
-    return convert_device(dev)->begin(purpose, key, in_params, out_params, operation_handle);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::update(
-        const keymaster2_device_t* dev, keymaster_operation_handle_t operation_handle,
-        const keymaster_key_param_set_t* in_params, const keymaster_blob_t* input,
-        size_t* input_consumed, keymaster_key_param_set_t* out_params, keymaster_blob_t* output) {
-    return convert_device(dev)->update(operation_handle, in_params, input, input_consumed,
-                                       out_params, output);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::finish(const keymaster2_device_t* dev,
-                                                keymaster_operation_handle_t operation_handle,
-                                                const keymaster_key_param_set_t* in_params,
-                                                const keymaster_blob_t* input,
-                                                const keymaster_blob_t* signature,
-                                                keymaster_key_param_set_t* out_params,
-                                                keymaster_blob_t* output) {
-    return convert_device(dev)->finish(operation_handle, in_params, input, signature, out_params,
-                                       output);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::abort(const keymaster2_device_t* dev,
-                                               keymaster_operation_handle_t operation_handle) {
-    return convert_device(dev)->abort(operation_handle);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::delete_key(const keymaster2_device_t* dev,
-                                               const keymaster_key_blob_t* key) {
-   return convert_device(dev)->delete_key(key);
-}
-
-/* static */
-keymaster_error_t TrustyKeymasterDevice::delete_all_keys(const keymaster2_device_t* dev) {
-   return convert_device(dev)->delete_all_keys();
-}
-
-}  // namespace keymaster
diff --git a/trusty/keymaster/legacy/trusty_keymaster_device_test.cpp b/trusty/keymaster/legacy/trusty_keymaster_device_test.cpp
deleted file mode 100644
index 68def58..0000000
--- a/trusty/keymaster/legacy/trusty_keymaster_device_test.cpp
+++ /dev/null
@@ -1,561 +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 <algorithm>
-#include <fstream>
-#include <memory>
-
-#include <gtest/gtest.h>
-#include <openssl/engine.h>
-
-#include <hardware/keymaster0.h>
-
-#include <keymaster/android_keymaster.h>
-#include <keymaster/android_keymaster_messages.h>
-#include <keymaster/android_keymaster_utils.h>
-#include <keymaster/keymaster_tags.h>
-#include <keymaster/soft_keymaster_context.h>
-
-#include <trusty_keymaster/legacy/trusty_keymaster_device.h>
-#include "android_keymaster_test_utils.h"
-#include "openssl_utils.h"
-
-using std::ifstream;
-using std::istreambuf_iterator;
-using std::string;
-
-static keymaster::AndroidKeymaster* impl_ = nullptr;
-
-extern "C" {
-int __android_log_print();
-}
-
-int __android_log_print() {
-    return 0;
-}
-
-int main(int argc, char** argv) {
-    ::testing::InitGoogleTest(&argc, argv);
-    int result = RUN_ALL_TESTS();
-    // Clean up stuff OpenSSL leaves around, so Valgrind doesn't complain.
-    CRYPTO_cleanup_all_ex_data();
-    ERR_free_strings();
-    return result;
-}
-
-int trusty_keymaster_connect() {
-    impl_ = new keymaster::AndroidKeymaster(new keymaster::SoftKeymasterContext(nullptr), 16);
-}
-
-void trusty_keymaster_disconnect() {
-    delete static_cast<keymaster::AndroidKeymaster*>(priv_);
-}
-
-template <typename Req, typename Rsp>
-static int fake_call(keymaster::AndroidKeymaster* device,
-                     void (keymaster::AndroidKeymaster::*method)(const Req&, Rsp*), void* in_buf,
-                     uint32_t in_size, void* out_buf, uint32_t* out_size) {
-    Req req;
-    const uint8_t* in = static_cast<uint8_t*>(in_buf);
-    req.Deserialize(&in, in + in_size);
-    Rsp rsp;
-    (device->*method)(req, &rsp);
-
-    *out_size = rsp.SerializedSize();
-    uint8_t* out = static_cast<uint8_t*>(out_buf);
-    rsp.Serialize(out, out + *out_size);
-    return 0;
-}
-
-int trusty_keymaster_call(uint32_t cmd, void* in_buf, uint32_t in_size, void* out_buf,
-                          uint32_t* out_size) {
-    switch (cmd) {
-        case KM_GENERATE_KEY:
-            return fake_call(impl_, &keymaster::AndroidKeymaster::GenerateKey, in_buf, in_size,
-                             out_buf, out_size);
-        case KM_BEGIN_OPERATION:
-            return fake_call(impl_, &keymaster::AndroidKeymaster::BeginOperation, in_buf, in_size,
-                             out_buf, out_size);
-        case KM_UPDATE_OPERATION:
-            return fake_call(impl_, &keymaster::AndroidKeymaster::UpdateOperation, in_buf, in_size,
-                             out_buf, out_size);
-        case KM_FINISH_OPERATION:
-            return fake_call(impl_, &keymaster::AndroidKeymaster::FinishOperation, in_buf, in_size,
-                             out_buf, out_size);
-        case KM_IMPORT_KEY:
-            return fake_call(impl_, &keymaster::AndroidKeymaster::ImportKey, in_buf, in_size,
-                             out_buf, out_size);
-        case KM_EXPORT_KEY:
-            return fake_call(impl_, &keymaster::AndroidKeymaster::ExportKey, in_buf, in_size,
-                             out_buf, out_size);
-    }
-    return -EINVAL;
-}
-
-namespace keymaster {
-namespace test {
-
-class TrustyKeymasterTest : public testing::Test {
-  protected:
-    TrustyKeymasterTest() : device(NULL) {}
-
-    keymaster_rsa_keygen_params_t build_rsa_params() {
-        keymaster_rsa_keygen_params_t rsa_params;
-        rsa_params.public_exponent = 65537;
-        rsa_params.modulus_size = 2048;
-        return rsa_params;
-    }
-
-    uint8_t* build_message(size_t length) {
-        uint8_t* msg = new uint8_t[length];
-        memset(msg, 'a', length);
-        return msg;
-    }
-
-    size_t dsa_message_len(const keymaster_dsa_keygen_params_t& params) {
-        switch (params.key_size) {
-            case 256:
-            case 1024:
-                return 48;
-            case 2048:
-            case 4096:
-                return 72;
-            default:
-                // Oops.
-                return 0;
-        }
-    }
-
-    TrustyKeymasterDevice device;
-};
-
-class Malloc_Delete {
-  public:
-    Malloc_Delete(void* p) : p_(p) {}
-    ~Malloc_Delete() { free(p_); }
-
-  private:
-    void* p_;
-};
-
-typedef TrustyKeymasterTest KeyGenTest;
-TEST_F(KeyGenTest, RsaSuccess) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-}
-
-TEST_F(KeyGenTest, EcdsaSuccess) {
-    keymaster_ec_keygen_params_t ec_params = {256};
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &ec_params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-}
-
-typedef TrustyKeymasterTest SigningTest;
-TEST_F(SigningTest, RsaSuccess) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8;
-    std::unique_ptr<uint8_t[]> message(build_message(message_len));
-    uint8_t* signature;
-    size_t siglen;
-    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
-                                            &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_EQ(message_len, siglen);
-}
-
-TEST_F(SigningTest, RsaShortMessage) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8 - 1;
-    std::unique_ptr<uint8_t[]> message(build_message(message_len));
-    uint8_t* signature;
-    size_t siglen;
-    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, device.sign_data(&sig_params, ptr, size, message.get(),
-                                                       message_len, &signature, &siglen));
-}
-
-TEST_F(SigningTest, RsaLongMessage) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8 + 1;
-    std::unique_ptr<uint8_t[]> message(build_message(message_len));
-    uint8_t* signature;
-    size_t siglen;
-    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, device.sign_data(&sig_params, ptr, size, message.get(),
-                                                       message_len, &signature, &siglen));
-}
-
-TEST_F(SigningTest, EcdsaSuccess) {
-    keymaster_ec_keygen_params_t params = {256};
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
-    uint8_t message[] = "12345678901234567890123456789012";
-    uint8_t* signature;
-    size_t siglen;
-    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message,
-                                            array_size(message) - 1, &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_GT(siglen, 69U);
-    EXPECT_LT(siglen, 73U);
-}
-
-TEST_F(SigningTest, EcdsaEmptyMessageSuccess) {
-    keymaster_ec_keygen_params_t params = {256};
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
-    uint8_t message[] = "";
-    uint8_t* signature;
-    size_t siglen;
-    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message,
-                                            array_size(message) - 1, &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_GT(siglen, 69U);
-    EXPECT_LT(siglen, 73U);
-}
-
-TEST_F(SigningTest, EcdsaLargeMessageSuccess) {
-    keymaster_ec_keygen_params_t params = {256};
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
-    size_t message_len = 1024 * 7;
-    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
-    // contents of message don't matter.
-    uint8_t* signature;
-    size_t siglen;
-    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
-                                            &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_GT(siglen, 69U);
-    EXPECT_LT(siglen, 73U);
-}
-
-typedef TrustyKeymasterTest VerificationTest;
-TEST_F(VerificationTest, RsaSuccess) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8;
-    std::unique_ptr<uint8_t[]> message(build_message(message_len));
-    uint8_t* signature;
-    size_t siglen;
-    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
-                                            &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-
-    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, ptr, size, message.get(), message_len,
-                                              signature, siglen));
-}
-
-TEST_F(VerificationTest, RsaBadSignature) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8;
-    std::unique_ptr<uint8_t[]> message(build_message(message_len));
-    uint8_t* signature;
-    size_t siglen;
-    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
-                                            &signature, &siglen));
-
-    Malloc_Delete sig_deleter(signature);
-    signature[siglen / 2]++;
-    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED,
-              device.verify_data(&sig_params, ptr, size, message.get(), message_len, signature,
-                                 siglen));
-}
-
-TEST_F(VerificationTest, RsaBadMessage) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8;
-    std::unique_ptr<uint8_t[]> message(build_message(message_len));
-    uint8_t* signature;
-    size_t siglen;
-    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
-                                            &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    message[0]++;
-    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED,
-              device.verify_data(&sig_params, ptr, size, message.get(), message_len, signature,
-                                 siglen));
-}
-
-TEST_F(VerificationTest, RsaShortMessage) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8;
-    std::unique_ptr<uint8_t[]> message(build_message(message_len));
-    uint8_t* signature;
-    size_t siglen;
-    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
-                                            &signature, &siglen));
-
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH,
-              device.verify_data(&sig_params, ptr, size, message.get(), message_len - 1, signature,
-                                 siglen));
-}
-
-TEST_F(VerificationTest, RsaLongMessage) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8;
-    std::unique_ptr<uint8_t[]> message(build_message(message_len + 1));
-    uint8_t* signature;
-    size_t siglen;
-    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
-                                            &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH,
-              device.verify_data(&sig_params, ptr, size, message.get(), message_len + 1, signature,
-                                 siglen));
-}
-
-TEST_F(VerificationTest, EcdsaSuccess) {
-    keymaster_ec_keygen_params_t params = {256};
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
-    uint8_t message[] = "12345678901234567890123456789012";
-    uint8_t* signature;
-    size_t siglen;
-    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message,
-                                            array_size(message) - 1, &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, ptr, size, message,
-                                              array_size(message) - 1, signature, siglen));
-}
-
-TEST_F(VerificationTest, EcdsaLargeMessageSuccess) {
-    keymaster_ec_keygen_params_t params = {256};
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
-    size_t message_len = 1024 * 7;
-    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
-    // contents of message don't matter.
-    uint8_t* signature;
-    size_t siglen;
-    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
-                                            &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, ptr, size, message.get(), message_len,
-                                              signature, siglen));
-}
-
-static string read_file(const string& file_name) {
-    ifstream file_stream(file_name, std::ios::binary);
-    istreambuf_iterator<char> file_begin(file_stream);
-    istreambuf_iterator<char> file_end;
-    return string(file_begin, file_end);
-}
-
-typedef TrustyKeymasterTest ImportKeyTest;
-TEST_F(ImportKeyTest, RsaSuccess) {
-    string pk8_key = read_file("../../../../system/keymaster/rsa_privkey_pk8.der");
-    ASSERT_EQ(633U, pk8_key.size());
-
-    uint8_t* key = NULL;
-    size_t size;
-    ASSERT_EQ(KM_ERROR_OK, device.import_keypair(reinterpret_cast<const uint8_t*>(pk8_key.data()),
-                                                 pk8_key.size(), &key, &size));
-    Malloc_Delete key_deleter(key);
-
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_size = 1024 /* key size */ / 8;
-    std::unique_ptr<uint8_t[]> message(new uint8_t[message_size]);
-    memset(message.get(), 'a', message_size);
-    uint8_t* signature;
-    size_t siglen;
-    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, key, size, message.get(), message_size,
-                                            &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, key, size, message.get(), message_size,
-                                              signature, siglen));
-}
-
-TEST_F(ImportKeyTest, EcdsaSuccess) {
-    string pk8_key = read_file("../../../../system/keymaster/ec_privkey_pk8.der");
-    ASSERT_EQ(138U, pk8_key.size());
-
-    uint8_t* key = NULL;
-    size_t size;
-    ASSERT_EQ(KM_ERROR_OK, device.import_keypair(reinterpret_cast<const uint8_t*>(pk8_key.data()),
-                                                 pk8_key.size(), &key, &size));
-    Malloc_Delete key_deleter(key);
-
-    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
-    uint8_t message[] = "12345678901234567890123456789012";
-    uint8_t* signature;
-    size_t siglen;
-    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, key, size, message,
-                                            array_size(message) - 1, &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, key, size, message,
-                                              array_size(message) - 1, signature, siglen));
-}
-
-struct EVP_PKEY_CTX_Delete {
-    void operator()(EVP_PKEY_CTX* p) { EVP_PKEY_CTX_free(p); }
-};
-
-static void VerifySignature(const uint8_t* key, size_t key_len, const uint8_t* signature,
-                            size_t signature_len, const uint8_t* message, size_t message_len) {
-    std::unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(d2i_PUBKEY(NULL, &key, key_len));
-    ASSERT_TRUE(pkey.get() != NULL);
-    std::unique_ptr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(EVP_PKEY_CTX_new(pkey.get(), NULL));
-    ASSERT_TRUE(ctx.get() != NULL);
-    ASSERT_EQ(1, EVP_PKEY_verify_init(ctx.get()));
-    if (EVP_PKEY_type(pkey->type) == EVP_PKEY_RSA)
-        ASSERT_EQ(1, EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING));
-    EXPECT_EQ(1, EVP_PKEY_verify(ctx.get(), signature, signature_len, message, message_len));
-}
-
-typedef TrustyKeymasterTest ExportKeyTest;
-TEST_F(ExportKeyTest, RsaSuccess) {
-    keymaster_rsa_keygen_params_t params = build_rsa_params();
-    uint8_t* ptr = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_RSA, &params, &ptr, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(ptr);
-
-    uint8_t* exported;
-    size_t exported_size;
-    EXPECT_EQ(KM_ERROR_OK, device.get_keypair_public(ptr, size, &exported, &exported_size));
-    Malloc_Delete exported_deleter(exported);
-
-    // Sign a message so we can verify it with the exported pubkey.
-    keymaster_rsa_sign_params_t sig_params = {DIGEST_NONE, PADDING_NONE};
-    size_t message_len = params.modulus_size / 8;
-    std::unique_ptr<uint8_t[]> message(build_message(message_len));
-    uint8_t* signature;
-    size_t siglen;
-    EXPECT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, ptr, size, message.get(), message_len,
-                                            &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_EQ(message_len, siglen);
-    const uint8_t* tmp = exported;
-
-    VerifySignature(exported, exported_size, signature, siglen, message.get(), message_len);
-}
-
-typedef TrustyKeymasterTest ExportKeyTest;
-TEST_F(ExportKeyTest, EcdsaSuccess) {
-    keymaster_ec_keygen_params_t params = {256};
-    uint8_t* key = NULL;
-    size_t size;
-    ASSERT_EQ(0, device.generate_keypair(TYPE_EC, &params, &key, &size));
-    EXPECT_GT(size, 0U);
-    Malloc_Delete key_deleter(key);
-
-    uint8_t* exported;
-    size_t exported_size;
-    EXPECT_EQ(KM_ERROR_OK, device.get_keypair_public(key, size, &exported, &exported_size));
-    Malloc_Delete exported_deleter(exported);
-
-    // Sign a message so we can verify it with the exported pubkey.
-    keymaster_ec_sign_params_t sig_params = {DIGEST_NONE};
-    uint8_t message[] = "12345678901234567890123456789012";
-    uint8_t* signature;
-    size_t siglen;
-    ASSERT_EQ(KM_ERROR_OK, device.sign_data(&sig_params, key, size, message,
-                                            array_size(message) - 1, &signature, &siglen));
-    Malloc_Delete sig_deleter(signature);
-    EXPECT_EQ(KM_ERROR_OK, device.verify_data(&sig_params, key, size, message,
-                                              array_size(message) - 1, signature, siglen));
-
-    VerifySignature(exported, exported_size, signature, siglen, message, array_size(message) - 1);
-}
-
-}  // namespace test
-}  // namespace keymaster
diff --git a/trusty/keymaster/legacy/trusty_keymaster_main.cpp b/trusty/keymaster/legacy/trusty_keymaster_main.cpp
deleted file mode 100644
index e3e70e6..0000000
--- a/trusty/keymaster/legacy/trusty_keymaster_main.cpp
+++ /dev/null
@@ -1,408 +0,0 @@
-/*
- * Copyright 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 <keymaster/keymaster_configuration.h>
-
-#include <stdio.h>
-#include <memory>
-
-#include <openssl/evp.h>
-#include <openssl/x509.h>
-
-#include <trusty_keymaster/legacy/trusty_keymaster_device.h>
-
-using keymaster::TrustyKeymasterDevice;
-
-unsigned char rsa_privkey_pk8_der[] = {
-        0x30, 0x82, 0x02, 0x75, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
-        0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, 0x02, 0x5f, 0x30, 0x82, 0x02, 0x5b,
-        0x02, 0x01, 0x00, 0x02, 0x81, 0x81, 0x00, 0xc6, 0x09, 0x54, 0x09, 0x04, 0x7d, 0x86, 0x34,
-        0x81, 0x2d, 0x5a, 0x21, 0x81, 0x76, 0xe4, 0x5c, 0x41, 0xd6, 0x0a, 0x75, 0xb1, 0x39, 0x01,
-        0xf2, 0x34, 0x22, 0x6c, 0xff, 0xe7, 0x76, 0x52, 0x1c, 0x5a, 0x77, 0xb9, 0xe3, 0x89, 0x41,
-        0x7b, 0x71, 0xc0, 0xb6, 0xa4, 0x4d, 0x13, 0xaf, 0xe4, 0xe4, 0xa2, 0x80, 0x5d, 0x46, 0xc9,
-        0xda, 0x29, 0x35, 0xad, 0xb1, 0xff, 0x0c, 0x1f, 0x24, 0xea, 0x06, 0xe6, 0x2b, 0x20, 0xd7,
-        0x76, 0x43, 0x0a, 0x4d, 0x43, 0x51, 0x57, 0x23, 0x3c, 0x6f, 0x91, 0x67, 0x83, 0xc3, 0x0e,
-        0x31, 0x0f, 0xcb, 0xd8, 0x9b, 0x85, 0xc2, 0xd5, 0x67, 0x71, 0x16, 0x97, 0x85, 0xac, 0x12,
-        0xbc, 0xa2, 0x44, 0xab, 0xda, 0x72, 0xbf, 0xb1, 0x9f, 0xc4, 0x4d, 0x27, 0xc8, 0x1e, 0x1d,
-        0x92, 0xde, 0x28, 0x4f, 0x40, 0x61, 0xed, 0xfd, 0x99, 0x28, 0x07, 0x45, 0xea, 0x6d, 0x25,
-        0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x81, 0x80, 0x1b, 0xe0, 0xf0, 0x4d, 0x9c, 0xae, 0x37,
-        0x18, 0x69, 0x1f, 0x03, 0x53, 0x38, 0x30, 0x8e, 0x91, 0x56, 0x4b, 0x55, 0x89, 0x9f, 0xfb,
-        0x50, 0x84, 0xd2, 0x46, 0x0e, 0x66, 0x30, 0x25, 0x7e, 0x05, 0xb3, 0xce, 0xab, 0x02, 0x97,
-        0x2d, 0xfa, 0xbc, 0xd6, 0xce, 0x5f, 0x6e, 0xe2, 0x58, 0x9e, 0xb6, 0x79, 0x11, 0xed, 0x0f,
-        0xac, 0x16, 0xe4, 0x3a, 0x44, 0x4b, 0x8c, 0x86, 0x1e, 0x54, 0x4a, 0x05, 0x93, 0x36, 0x57,
-        0x72, 0xf8, 0xba, 0xf6, 0xb2, 0x2f, 0xc9, 0xe3, 0xc5, 0xf1, 0x02, 0x4b, 0x06, 0x3a, 0xc0,
-        0x80, 0xa7, 0xb2, 0x23, 0x4c, 0xf8, 0xae, 0xe8, 0xf6, 0xc4, 0x7b, 0xbf, 0x4f, 0xd3, 0xac,
-        0xe7, 0x24, 0x02, 0x90, 0xbe, 0xf1, 0x6c, 0x0b, 0x3f, 0x7f, 0x3c, 0xdd, 0x64, 0xce, 0x3a,
-        0xb5, 0x91, 0x2c, 0xf6, 0xe3, 0x2f, 0x39, 0xab, 0x18, 0x83, 0x58, 0xaf, 0xcc, 0xcd, 0x80,
-        0x81, 0x02, 0x41, 0x00, 0xe4, 0xb4, 0x9e, 0xf5, 0x0f, 0x76, 0x5d, 0x3b, 0x24, 0xdd, 0xe0,
-        0x1a, 0xce, 0xaa, 0xf1, 0x30, 0xf2, 0xc7, 0x66, 0x70, 0xa9, 0x1a, 0x61, 0xae, 0x08, 0xaf,
-        0x49, 0x7b, 0x4a, 0x82, 0xbe, 0x6d, 0xee, 0x8f, 0xcd, 0xd5, 0xe3, 0xf7, 0xba, 0x1c, 0xfb,
-        0x1f, 0x0c, 0x92, 0x6b, 0x88, 0xf8, 0x8c, 0x92, 0xbf, 0xab, 0x13, 0x7f, 0xba, 0x22, 0x85,
-        0x22, 0x7b, 0x83, 0xc3, 0x42, 0xff, 0x7c, 0x55, 0x02, 0x41, 0x00, 0xdd, 0xab, 0xb5, 0x83,
-        0x9c, 0x4c, 0x7f, 0x6b, 0xf3, 0xd4, 0x18, 0x32, 0x31, 0xf0, 0x05, 0xb3, 0x1a, 0xa5, 0x8a,
-        0xff, 0xdd, 0xa5, 0xc7, 0x9e, 0x4c, 0xce, 0x21, 0x7f, 0x6b, 0xc9, 0x30, 0xdb, 0xe5, 0x63,
-        0xd4, 0x80, 0x70, 0x6c, 0x24, 0xe9, 0xeb, 0xfc, 0xab, 0x28, 0xa6, 0xcd, 0xef, 0xd3, 0x24,
-        0xb7, 0x7e, 0x1b, 0xf7, 0x25, 0x1b, 0x70, 0x90, 0x92, 0xc2, 0x4f, 0xf5, 0x01, 0xfd, 0x91,
-        0x02, 0x40, 0x23, 0xd4, 0x34, 0x0e, 0xda, 0x34, 0x45, 0xd8, 0xcd, 0x26, 0xc1, 0x44, 0x11,
-        0xda, 0x6f, 0xdc, 0xa6, 0x3c, 0x1c, 0xcd, 0x4b, 0x80, 0xa9, 0x8a, 0xd5, 0x2b, 0x78, 0xcc,
-        0x8a, 0xd8, 0xbe, 0xb2, 0x84, 0x2c, 0x1d, 0x28, 0x04, 0x05, 0xbc, 0x2f, 0x6c, 0x1b, 0xea,
-        0x21, 0x4a, 0x1d, 0x74, 0x2a, 0xb9, 0x96, 0xb3, 0x5b, 0x63, 0xa8, 0x2a, 0x5e, 0x47, 0x0f,
-        0xa8, 0x8d, 0xbf, 0x82, 0x3c, 0xdd, 0x02, 0x40, 0x1b, 0x7b, 0x57, 0x44, 0x9a, 0xd3, 0x0d,
-        0x15, 0x18, 0x24, 0x9a, 0x5f, 0x56, 0xbb, 0x98, 0x29, 0x4d, 0x4b, 0x6a, 0xc1, 0x2f, 0xfc,
-        0x86, 0x94, 0x04, 0x97, 0xa5, 0xa5, 0x83, 0x7a, 0x6c, 0xf9, 0x46, 0x26, 0x2b, 0x49, 0x45,
-        0x26, 0xd3, 0x28, 0xc1, 0x1e, 0x11, 0x26, 0x38, 0x0f, 0xde, 0x04, 0xc2, 0x4f, 0x91, 0x6d,
-        0xec, 0x25, 0x08, 0x92, 0xdb, 0x09, 0xa6, 0xd7, 0x7c, 0xdb, 0xa3, 0x51, 0x02, 0x40, 0x77,
-        0x62, 0xcd, 0x8f, 0x4d, 0x05, 0x0d, 0xa5, 0x6b, 0xd5, 0x91, 0xad, 0xb5, 0x15, 0xd2, 0x4d,
-        0x7c, 0xcd, 0x32, 0xcc, 0xa0, 0xd0, 0x5f, 0x86, 0x6d, 0x58, 0x35, 0x14, 0xbd, 0x73, 0x24,
-        0xd5, 0xf3, 0x36, 0x45, 0xe8, 0xed, 0x8b, 0x4a, 0x1c, 0xb3, 0xcc, 0x4a, 0x1d, 0x67, 0x98,
-        0x73, 0x99, 0xf2, 0xa0, 0x9f, 0x5b, 0x3f, 0xb6, 0x8c, 0x88, 0xd5, 0xe5, 0xd9, 0x0a, 0xc3,
-        0x34, 0x92, 0xd6};
-unsigned int rsa_privkey_pk8_der_len = 633;
-
-unsigned char dsa_privkey_pk8_der[] = {
-        0x30, 0x82, 0x01, 0x4b, 0x02, 0x01, 0x00, 0x30, 0x82, 0x01, 0x2b, 0x06, 0x07, 0x2a, 0x86,
-        0x48, 0xce, 0x38, 0x04, 0x01, 0x30, 0x82, 0x01, 0x1e, 0x02, 0x81, 0x81, 0x00, 0xa3, 0xf3,
-        0xe9, 0xb6, 0x7e, 0x7d, 0x88, 0xf6, 0xb7, 0xe5, 0xf5, 0x1f, 0x3b, 0xee, 0xac, 0xd7, 0xad,
-        0xbc, 0xc9, 0xd1, 0x5a, 0xf8, 0x88, 0xc4, 0xef, 0x6e, 0x3d, 0x74, 0x19, 0x74, 0xe7, 0xd8,
-        0xe0, 0x26, 0x44, 0x19, 0x86, 0xaf, 0x19, 0xdb, 0x05, 0xe9, 0x3b, 0x8b, 0x58, 0x58, 0xde,
-        0xe5, 0x4f, 0x48, 0x15, 0x01, 0xea, 0xe6, 0x83, 0x52, 0xd7, 0xc1, 0x21, 0xdf, 0xb9, 0xb8,
-        0x07, 0x66, 0x50, 0xfb, 0x3a, 0x0c, 0xb3, 0x85, 0xee, 0xbb, 0x04, 0x5f, 0xc2, 0x6d, 0x6d,
-        0x95, 0xfa, 0x11, 0x93, 0x1e, 0x59, 0x5b, 0xb1, 0x45, 0x8d, 0xe0, 0x3d, 0x73, 0xaa, 0xf2,
-        0x41, 0x14, 0x51, 0x07, 0x72, 0x3d, 0xa2, 0xf7, 0x58, 0xcd, 0x11, 0xa1, 0x32, 0xcf, 0xda,
-        0x42, 0xb7, 0xcc, 0x32, 0x80, 0xdb, 0x87, 0x82, 0xec, 0x42, 0xdb, 0x5a, 0x55, 0x24, 0x24,
-        0xa2, 0xd1, 0x55, 0x29, 0xad, 0xeb, 0x02, 0x15, 0x00, 0xeb, 0xea, 0x17, 0xd2, 0x09, 0xb3,
-        0xd7, 0x21, 0x9a, 0x21, 0x07, 0x82, 0x8f, 0xab, 0xfe, 0x88, 0x71, 0x68, 0xf7, 0xe3, 0x02,
-        0x81, 0x80, 0x19, 0x1c, 0x71, 0xfd, 0xe0, 0x03, 0x0c, 0x43, 0xd9, 0x0b, 0xf6, 0xcd, 0xd6,
-        0xa9, 0x70, 0xe7, 0x37, 0x86, 0x3a, 0x78, 0xe9, 0xa7, 0x47, 0xa7, 0x47, 0x06, 0x88, 0xb1,
-        0xaf, 0xd7, 0xf3, 0xf1, 0xa1, 0xd7, 0x00, 0x61, 0x28, 0x88, 0x31, 0x48, 0x60, 0xd8, 0x11,
-        0xef, 0xa5, 0x24, 0x1a, 0x81, 0xc4, 0x2a, 0xe2, 0xea, 0x0e, 0x36, 0xd2, 0xd2, 0x05, 0x84,
-        0x37, 0xcf, 0x32, 0x7d, 0x09, 0xe6, 0x0f, 0x8b, 0x0c, 0xc8, 0xc2, 0xa4, 0xb1, 0xdc, 0x80,
-        0xca, 0x68, 0xdf, 0xaf, 0xd2, 0x90, 0xc0, 0x37, 0x58, 0x54, 0x36, 0x8f, 0x49, 0xb8, 0x62,
-        0x75, 0x8b, 0x48, 0x47, 0xc0, 0xbe, 0xf7, 0x9a, 0x92, 0xa6, 0x68, 0x05, 0xda, 0x9d, 0xaf,
-        0x72, 0x9a, 0x67, 0xb3, 0xb4, 0x14, 0x03, 0xae, 0x4f, 0x4c, 0x76, 0xb9, 0xd8, 0x64, 0x0a,
-        0xba, 0x3b, 0xa8, 0x00, 0x60, 0x4d, 0xae, 0x81, 0xc3, 0xc5, 0x04, 0x17, 0x02, 0x15, 0x00,
-        0x81, 0x9d, 0xfd, 0x53, 0x0c, 0xc1, 0x8f, 0xbe, 0x8b, 0xea, 0x00, 0x26, 0x19, 0x29, 0x33,
-        0x91, 0x84, 0xbe, 0xad, 0x81};
-unsigned int dsa_privkey_pk8_der_len = 335;
-
-unsigned char ec_privkey_pk8_der[] = {
-        0x30, 0x81, 0x87, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce,
-        0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x04,
-        0x6d, 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20, 0x73, 0x7c, 0x2e, 0xcd, 0x7b, 0x8d,
-        0x19, 0x40, 0xbf, 0x29, 0x30, 0xaa, 0x9b, 0x4e, 0xd3, 0xff, 0x94, 0x1e, 0xed, 0x09,
-        0x36, 0x6b, 0xc0, 0x32, 0x99, 0x98, 0x64, 0x81, 0xf3, 0xa4, 0xd8, 0x59, 0xa1, 0x44,
-        0x03, 0x42, 0x00, 0x04, 0xbf, 0x85, 0xd7, 0x72, 0x0d, 0x07, 0xc2, 0x54, 0x61, 0x68,
-        0x3b, 0xc6, 0x48, 0xb4, 0x77, 0x8a, 0x9a, 0x14, 0xdd, 0x8a, 0x02, 0x4e, 0x3b, 0xdd,
-        0x8c, 0x7d, 0xdd, 0x9a, 0xb2, 0xb5, 0x28, 0xbb, 0xc7, 0xaa, 0x1b, 0x51, 0xf1, 0x4e,
-        0xbb, 0xbb, 0x0b, 0xd0, 0xce, 0x21, 0xbc, 0xc4, 0x1c, 0x6e, 0xb0, 0x00, 0x83, 0xcf,
-        0x33, 0x76, 0xd1, 0x1f, 0xd4, 0x49, 0x49, 0xe0, 0xb2, 0x18, 0x3b, 0xfe};
-unsigned int ec_privkey_pk8_der_len = 138;
-
-keymaster_key_param_t ec_params[] = {
-        keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_EC),
-        keymaster_param_long(KM_TAG_EC_CURVE, KM_EC_CURVE_P_521),
-        keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
-        keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY),
-        keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
-        keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
-};
-keymaster_key_param_set_t ec_param_set = {ec_params, sizeof(ec_params) / sizeof(*ec_params)};
-
-keymaster_key_param_t rsa_params[] = {
-        keymaster_param_enum(KM_TAG_ALGORITHM, KM_ALGORITHM_RSA),
-        keymaster_param_int(KM_TAG_KEY_SIZE, 1024),
-        keymaster_param_long(KM_TAG_RSA_PUBLIC_EXPONENT, 65537),
-        keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_SIGN),
-        keymaster_param_enum(KM_TAG_PURPOSE, KM_PURPOSE_VERIFY),
-        keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
-        keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
-        keymaster_param_bool(KM_TAG_NO_AUTH_REQUIRED),
-};
-keymaster_key_param_set_t rsa_param_set = {rsa_params, sizeof(rsa_params) / sizeof(*rsa_params)};
-
-struct EVP_PKEY_Delete {
-    void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); }
-};
-
-struct EVP_PKEY_CTX_Delete {
-    void operator()(EVP_PKEY_CTX* p) { EVP_PKEY_CTX_free(p); }
-};
-
-static bool do_operation(TrustyKeymasterDevice* device, keymaster_purpose_t purpose,
-                         keymaster_key_blob_t* key, keymaster_blob_t* input,
-                         keymaster_blob_t* signature, keymaster_blob_t* output) {
-    keymaster_key_param_t params[] = {
-            keymaster_param_enum(KM_TAG_PADDING, KM_PAD_NONE),
-            keymaster_param_enum(KM_TAG_DIGEST, KM_DIGEST_NONE),
-    };
-    keymaster_key_param_set_t param_set = {params, sizeof(params) / sizeof(*params)};
-    keymaster_operation_handle_t op_handle;
-    keymaster_error_t error = device->begin(purpose, key, &param_set, nullptr, &op_handle);
-    if (error != KM_ERROR_OK) {
-        printf("Keymaster begin() failed: %d\n", error);
-        return false;
-    }
-    size_t input_consumed;
-    error = device->update(op_handle, nullptr, input, &input_consumed, nullptr, nullptr);
-    if (error != KM_ERROR_OK) {
-        printf("Keymaster update() failed: %d\n", error);
-        return false;
-    }
-    if (input_consumed != input->data_length) {
-        // This should never happen. If it does, it's a bug in the keymaster implementation.
-        printf("Keymaster update() did not consume all data.\n");
-        device->abort(op_handle);
-        return false;
-    }
-    error = device->finish(op_handle, nullptr, nullptr, signature, nullptr, output);
-    if (error != KM_ERROR_OK) {
-        printf("Keymaster finish() failed: %d\n", error);
-        return false;
-    }
-    return true;
-}
-
-static bool test_import_rsa(TrustyKeymasterDevice* device) {
-    printf("===================\n");
-    printf("= RSA Import Test =\n");
-    printf("===================\n\n");
-
-    printf("=== Importing RSA keypair === \n");
-    keymaster_key_blob_t key;
-    keymaster_blob_t private_key = {rsa_privkey_pk8_der, rsa_privkey_pk8_der_len};
-    int error =
-            device->import_key(&rsa_param_set, KM_KEY_FORMAT_PKCS8, &private_key, &key, nullptr);
-    if (error != KM_ERROR_OK) {
-        printf("Error importing RSA key: %d\n\n", error);
-        return false;
-    }
-    std::unique_ptr<const uint8_t[]> key_deleter(key.key_material);
-
-    printf("=== Signing with imported RSA key ===\n");
-    size_t message_len = 1024 / 8;
-    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
-    memset(message.get(), 'a', message_len);
-    keymaster_blob_t input = {message.get(), message_len}, signature;
-
-    if (!do_operation(device, KM_PURPOSE_SIGN, &key, &input, nullptr, &signature)) {
-        printf("Error signing data with imported RSA key\n\n");
-        return false;
-    }
-    std::unique_ptr<const uint8_t[]> signature_deleter(signature.data);
-
-    printf("=== Verifying with imported RSA key === \n");
-    if (!do_operation(device, KM_PURPOSE_VERIFY, &key, &input, &signature, nullptr)) {
-        printf("Error verifying data with imported RSA key\n\n");
-        return false;
-    }
-
-    printf("\n");
-    return true;
-}
-
-static bool test_rsa(TrustyKeymasterDevice* device) {
-    printf("============\n");
-    printf("= RSA Test =\n");
-    printf("============\n\n");
-
-    printf("=== Generating RSA key pair ===\n");
-    keymaster_key_blob_t key;
-    int error = device->generate_key(&rsa_param_set, &key, nullptr);
-    if (error != KM_ERROR_OK) {
-        printf("Error generating RSA key pair: %d\n\n", error);
-        return false;
-    }
-    std::unique_ptr<const uint8_t[]> key_deleter(key.key_material);
-
-    printf("=== Signing with RSA key === \n");
-    size_t message_len = 1024 / 8;
-    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
-    memset(message.get(), 'a', message_len);
-    keymaster_blob_t input = {message.get(), message_len}, signature;
-
-    if (!do_operation(device, KM_PURPOSE_SIGN, &key, &input, nullptr, &signature)) {
-        printf("Error signing data with RSA key\n\n");
-        return false;
-    }
-    std::unique_ptr<const uint8_t[]> signature_deleter(signature.data);
-
-    printf("=== Verifying with RSA key === \n");
-    if (!do_operation(device, KM_PURPOSE_VERIFY, &key, &input, &signature, nullptr)) {
-        printf("Error verifying data with RSA key\n\n");
-        return false;
-    }
-
-    printf("=== Exporting RSA public key ===\n");
-    keymaster_blob_t exported_key;
-    error = device->export_key(KM_KEY_FORMAT_X509, &key, nullptr, nullptr, &exported_key);
-    if (error != KM_ERROR_OK) {
-        printf("Error exporting RSA public key: %d\n\n", error);
-        return false;
-    }
-
-    printf("=== Verifying with exported key ===\n");
-    const uint8_t* tmp = exported_key.data;
-    std::unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
-            d2i_PUBKEY(NULL, &tmp, exported_key.data_length));
-    std::unique_ptr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(EVP_PKEY_CTX_new(pkey.get(), NULL));
-    if (EVP_PKEY_verify_init(ctx.get()) != 1) {
-        printf("Error initializing openss EVP context\n\n");
-        return false;
-    }
-    if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
-        printf("Exported key was the wrong type?!?\n\n");
-        return false;
-    }
-
-    EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_NO_PADDING);
-    if (EVP_PKEY_verify(ctx.get(), signature.data, signature.data_length, message.get(),
-                        message_len) != 1) {
-        printf("Verification with exported pubkey failed.\n\n");
-        return false;
-    } else {
-        printf("Verification succeeded\n");
-    }
-
-    printf("\n");
-    return true;
-}
-
-static bool test_import_ecdsa(TrustyKeymasterDevice* device) {
-    printf("=====================\n");
-    printf("= ECDSA Import Test =\n");
-    printf("=====================\n\n");
-
-    printf("=== Importing ECDSA keypair === \n");
-    keymaster_key_blob_t key;
-    keymaster_blob_t private_key = {ec_privkey_pk8_der, ec_privkey_pk8_der_len};
-    int error = device->import_key(&ec_param_set, KM_KEY_FORMAT_PKCS8, &private_key, &key, nullptr);
-    if (error != KM_ERROR_OK) {
-        printf("Error importing ECDSA key: %d\n\n", error);
-        return false;
-    }
-    std::unique_ptr<const uint8_t[]> deleter(key.key_material);
-
-    printf("=== Signing with imported ECDSA key ===\n");
-    size_t message_len = 30 /* arbitrary */;
-    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
-    memset(message.get(), 'a', message_len);
-    keymaster_blob_t input = {message.get(), message_len}, signature;
-
-    if (!do_operation(device, KM_PURPOSE_SIGN, &key, &input, nullptr, &signature)) {
-        printf("Error signing data with imported ECDSA key\n\n");
-        return false;
-    }
-    std::unique_ptr<const uint8_t[]> signature_deleter(signature.data);
-
-    printf("=== Verifying with imported ECDSA key === \n");
-    if (!do_operation(device, KM_PURPOSE_VERIFY, &key, &input, &signature, nullptr)) {
-        printf("Error verifying data with imported ECDSA key\n\n");
-        return false;
-    }
-
-    printf("\n");
-    return true;
-}
-
-static bool test_ecdsa(TrustyKeymasterDevice* device) {
-    printf("==============\n");
-    printf("= ECDSA Test =\n");
-    printf("==============\n\n");
-
-    printf("=== Generating ECDSA key pair ===\n");
-    keymaster_key_blob_t key;
-    int error = device->generate_key(&ec_param_set, &key, nullptr);
-    if (error != KM_ERROR_OK) {
-        printf("Error generating ECDSA key pair: %d\n\n", error);
-        return false;
-    }
-    std::unique_ptr<const uint8_t[]> key_deleter(key.key_material);
-
-    printf("=== Signing with ECDSA key === \n");
-    size_t message_len = 30 /* arbitrary */;
-    std::unique_ptr<uint8_t[]> message(new uint8_t[message_len]);
-    memset(message.get(), 'a', message_len);
-    keymaster_blob_t input = {message.get(), message_len}, signature;
-
-    if (!do_operation(device, KM_PURPOSE_SIGN, &key, &input, nullptr, &signature)) {
-        printf("Error signing data with ECDSA key\n\n");
-        return false;
-    }
-    std::unique_ptr<const uint8_t[]> signature_deleter(signature.data);
-
-    printf("=== Verifying with ECDSA key === \n");
-    if (!do_operation(device, KM_PURPOSE_VERIFY, &key, &input, &signature, nullptr)) {
-        printf("Error verifying data with ECDSA key\n\n");
-        return false;
-    }
-
-    printf("=== Exporting ECDSA public key ===\n");
-    keymaster_blob_t exported_key;
-    error = device->export_key(KM_KEY_FORMAT_X509, &key, nullptr, nullptr, &exported_key);
-    if (error != KM_ERROR_OK) {
-        printf("Error exporting ECDSA public key: %d\n\n", error);
-        return false;
-    }
-
-    printf("=== Verifying with exported key ===\n");
-    const uint8_t* tmp = exported_key.data;
-    std::unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
-            d2i_PUBKEY(NULL, &tmp, exported_key.data_length));
-    std::unique_ptr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(EVP_PKEY_CTX_new(pkey.get(), NULL));
-    if (EVP_PKEY_verify_init(ctx.get()) != 1) {
-        printf("Error initializing openssl EVP context\n\n");
-        return false;
-    }
-    if (EVP_PKEY_type(pkey->type) != EVP_PKEY_EC) {
-        printf("Exported key was the wrong type?!?\n\n");
-        return false;
-    }
-
-    if (EVP_PKEY_verify(ctx.get(), signature.data, signature.data_length, message.get(),
-                        message_len) != 1) {
-        printf("Verification with exported pubkey failed.\n\n");
-        return false;
-    } else {
-        printf("Verification succeeded\n");
-    }
-
-    printf("\n");
-    return true;
-}
-
-int main(void) {
-    TrustyKeymasterDevice device(NULL);
-    keymaster::ConfigureDevice(reinterpret_cast<keymaster2_device_t*>(&device));
-    if (device.session_error() != KM_ERROR_OK) {
-        printf("Failed to initialize Trusty session: %d\n", device.session_error());
-        return 1;
-    }
-    printf("Trusty session initialized\n");
-
-    bool success = true;
-    success &= test_rsa(&device);
-    success &= test_import_rsa(&device);
-    success &= test_ecdsa(&device);
-    success &= test_import_ecdsa(&device);
-
-    if (success) {
-        printf("\nTESTS PASSED!\n");
-    } else {
-        printf("\n!!!!TESTS FAILED!!!\n");
-    }
-
-    return success ? 0 : 1;
-}