Merge "Add android::base::GetPids() function to return all pids"
diff --git a/adb/Android.bp b/adb/Android.bp
index 114eb2a..b6aff3e 100644
--- a/adb/Android.bp
+++ b/adb/Android.bp
@@ -344,6 +344,7 @@
     generated_headers: ["platform_tools_version"],
 
     static_libs: [
+        "libadbconnection_server",
         "libdiagnose_usb",
     ],
 
@@ -395,6 +396,7 @@
     ],
 
     static_libs: [
+        "libadbconnection_server",
         "libadbd_core",
         "libdiagnose_usb",
     ],
@@ -531,6 +533,7 @@
     },
 
     static_libs: [
+        "libadbconnection_server",
         "libadbd",
         "libadbd_services",
         "libasyncio",
diff --git a/adb/daemon/include/adbd/usb.h b/adb/daemon/include/adbd/usb.h
index fca3c58..2204246 100644
--- a/adb/daemon/include/adbd/usb.h
+++ b/adb/daemon/include/adbd/usb.h
@@ -16,6 +16,8 @@
  * limitations under the License.
  */
 
+#include <linux/usb/functionfs.h>
+
 #include <atomic>
 #include <condition_variable>
 #include <mutex>
diff --git a/adb/daemon/jdwp_service.cpp b/adb/daemon/jdwp_service.cpp
index cd9b669..b92a7de 100644
--- a/adb/daemon/jdwp_service.cpp
+++ b/adb/daemon/jdwp_service.cpp
@@ -30,15 +30,21 @@
 
 #include <list>
 #include <memory>
+#include <thread>
 #include <vector>
 
+#include <adbconnection/server.h>
 #include <android-base/cmsg.h>
+#include <android-base/unique_fd.h>
 
 #include "adb.h"
 #include "adb_io.h"
 #include "adb_unique_fd.h"
 #include "adb_utils.h"
 
+using android::base::borrowed_fd;
+using android::base::unique_fd;
+
 /* here's how these things work.
 
    when adbd starts, it creates a unix server socket
@@ -133,16 +139,16 @@
 static auto& _jdwp_list = *new std::list<std::unique_ptr<JdwpProcess>>();
 
 struct JdwpProcess {
-    explicit JdwpProcess(int socket) {
+    JdwpProcess(unique_fd socket, pid_t pid) {
+        CHECK(pid != 0);
+
         this->socket = socket;
-        this->fde = fdevent_create(socket, jdwp_process_event, this);
+        this->pid = pid;
+        this->fde = fdevent_create(socket.release(), jdwp_process_event, this);
 
         if (!this->fde) {
             LOG(FATAL) << "could not create fdevent for new JDWP process";
         }
-
-        /* start by waiting for the PID */
-        fdevent_add(this->fde, FDE_READ);
     }
 
     ~JdwpProcess() {
@@ -160,18 +166,12 @@
     }
 
     void RemoveFromList() {
-        if (this->pid >= 0) {
-            D("removing pid %d from jdwp process list", this->pid);
-        } else {
-            D("removing transient JdwpProcess from list");
-        }
-
         auto pred = [this](const auto& proc) { return proc.get() == this; };
         _jdwp_list.remove_if(pred);
     }
 
+    borrowed_fd socket = -1;
     int32_t pid = -1;
-    int socket = -1;
     fdevent* fde = nullptr;
 
     std::vector<unique_fd> out_fds;
@@ -181,11 +181,6 @@
     std::string temp;
 
     for (auto& proc : _jdwp_list) {
-        /* skip transient connections */
-        if (proc->pid < 0) {
-            continue;
-        }
-
         std::string next = std::to_string(proc->pid) + "\n";
         if (temp.length() + next.length() > bufferlen) {
             D("truncating JDWP process list (max len = %zu)", bufferlen);
@@ -214,24 +209,12 @@
 
 static void jdwp_process_event(int socket, unsigned events, void* _proc) {
     JdwpProcess* proc = reinterpret_cast<JdwpProcess*>(_proc);
-    CHECK_EQ(socket, proc->socket);
+    CHECK_EQ(socket, proc->socket.get());
 
     if (events & FDE_READ) {
-        if (proc->pid < 0) {
-            ssize_t rc = TEMP_FAILURE_RETRY(recv(socket, &proc->pid, sizeof(proc->pid), 0));
-            if (rc != sizeof(proc->pid)) {
-                D("failed to read jdwp pid: rc = %zd, errno = %s", rc, strerror(errno));
-                goto CloseProcess;
-            }
-
-            /* all is well, keep reading to detect connection closure */
-            D("Adding pid %d to jdwp process list", proc->pid);
-            jdwp_process_list_updated();
-        } else {
-            // We already have the PID, if we can read from the socket, we've probably hit EOF.
-            D("terminating JDWP connection %d", proc->pid);
-            goto CloseProcess;
-        }
+        // We already have the PID, if we can read from the socket, we've probably hit EOF.
+        D("terminating JDWP connection %d", proc->pid);
+        goto CloseProcess;
     }
 
     if (events & FDE_WRITE) {
@@ -284,98 +267,6 @@
     return unique_fd{};
 }
 
-/**  VM DEBUG CONTROL SOCKET
- **
- **  we do implement a custom asocket to receive the data
- **/
-
-/* name of the debug control Unix socket */
-#define JDWP_CONTROL_NAME "\0jdwp-control"
-#define JDWP_CONTROL_NAME_LEN (sizeof(JDWP_CONTROL_NAME) - 1)
-
-struct JdwpControl {
-    int listen_socket;
-    fdevent* fde;
-};
-
-static JdwpControl _jdwp_control;
-
-static void jdwp_control_event(int s, unsigned events, void* user);
-
-static int jdwp_control_init(JdwpControl* control, const char* sockname, int socknamelen) {
-    sockaddr_un addr;
-    socklen_t addrlen;
-    int maxpath = sizeof(addr.sun_path);
-    int pathlen = socknamelen;
-
-    if (pathlen >= maxpath) {
-        D("vm debug control socket name too long (%d extra chars)", pathlen + 1 - maxpath);
-        return -1;
-    }
-
-    memset(&addr, 0, sizeof(addr));
-    addr.sun_family = AF_UNIX;
-    memcpy(addr.sun_path, sockname, socknamelen);
-
-    unique_fd s(socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0));
-    if (s < 0) {
-        D("could not create vm debug control socket. %d: %s", errno, strerror(errno));
-        return -1;
-    }
-
-    addrlen = pathlen + sizeof(addr.sun_family);
-
-    if (bind(s.get(), reinterpret_cast<sockaddr*>(&addr), addrlen) < 0) {
-        D("could not bind vm debug control socket: %d: %s", errno, strerror(errno));
-        return -1;
-    }
-
-    if (listen(s.get(), 4) < 0) {
-        D("listen failed in jdwp control socket: %d: %s", errno, strerror(errno));
-        return -1;
-    }
-
-    control->listen_socket = s.release();
-    control->fde = fdevent_create(control->listen_socket, jdwp_control_event, control);
-    if (control->fde == nullptr) {
-        D("could not create fdevent for jdwp control socket");
-        return -1;
-    }
-
-    /* only wait for incoming connections */
-    fdevent_add(control->fde, FDE_READ);
-
-    D("jdwp control socket started (%d)", control->listen_socket);
-    return 0;
-}
-
-static void jdwp_control_event(int fd, unsigned events, void* _control) {
-    JdwpControl* control = (JdwpControl*)_control;
-
-    CHECK_EQ(fd, control->listen_socket);
-    if (events & FDE_READ) {
-        int s = adb_socket_accept(control->listen_socket, nullptr, nullptr);
-        if (s < 0) {
-            if (errno == ECONNABORTED) {
-                /* oops, the JDWP process died really quick */
-                D("oops, the JDWP process died really quick");
-                return;
-            } else {
-                /* the socket is probably closed ? */
-                D("weird accept() failed on jdwp control socket: %s", strerror(errno));
-                return;
-            }
-        }
-
-        auto proc = std::make_unique<JdwpProcess>(s);
-        if (!proc) {
-            LOG(FATAL) << "failed to allocate JdwpProcess";
-        }
-
-        _jdwp_list.emplace_back(std::move(proc));
-    }
-}
-
 /** "jdwp" local service implementation
  ** this simply returns the list of known JDWP process pids
  **/
@@ -526,7 +417,22 @@
 }
 
 int init_jdwp(void) {
-    return jdwp_control_init(&_jdwp_control, JDWP_CONTROL_NAME, JDWP_CONTROL_NAME_LEN);
+    std::thread([]() {
+        adb_thread_setname("jdwp control");
+        adbconnection_listen([](int fd, pid_t pid) {
+            LOG(INFO) << "jdwp connection from " << pid;
+            fdevent_run_on_main_thread([fd, pid] {
+                unique_fd ufd(fd);
+                auto proc = std::make_unique<JdwpProcess>(std::move(ufd), pid);
+                if (!proc) {
+                    LOG(FATAL) << "failed to allocate JdwpProcess";
+                }
+                _jdwp_list.emplace_back(std::move(proc));
+                jdwp_process_list_updated();
+            });
+        });
+    }).detach();
+    return 0;
 }
 
 #endif /* !ADB_HOST */
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 39abc4a..c436be3 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -389,6 +389,8 @@
             " set_active SLOT            Set the active slot.\n"
             " oem [COMMAND...]           Execute OEM-specific command.\n"
             " gsi wipe|disable           Wipe or disable a GSI installation (fastbootd only).\n"
+            " wipe-super [SUPER_EMPTY]   Wipe the super partition. This will reset it to\n"
+            "                            contain an empty set of default dynamic partitions.\n"
             "\n"
             "boot image:\n"
             " boot KERNEL [RAMDISK [SECOND]]\n"
@@ -1582,6 +1584,76 @@
     return false;
 }
 
+static bool wipe_super(const android::fs_mgr::LpMetadata& metadata, const std::string& slot,
+                       std::string* message) {
+    auto super_device = GetMetadataSuperBlockDevice(metadata);
+    auto block_size = metadata.geometry.logical_block_size;
+    auto super_bdev_name = android::fs_mgr::GetBlockDevicePartitionName(*super_device);
+
+    if (super_bdev_name != "super") {
+        // retrofit devices do not allow flashing to the retrofit partitions,
+        // so enable it if we can.
+        fb->RawCommand("oem allow-flash-super");
+    }
+
+    // Note: do not use die() in here, since we want TemporaryDir's destructor
+    // to be called.
+    TemporaryDir temp_dir;
+
+    bool ok;
+    if (metadata.block_devices.size() > 1) {
+        ok = WriteSplitImageFiles(temp_dir.path, metadata, block_size, {}, true);
+    } else {
+        auto image_path = temp_dir.path + "/"s + super_bdev_name + ".img";
+        ok = WriteToImageFile(image_path, metadata, block_size, {}, true);
+    }
+    if (!ok) {
+        *message = "Could not generate a flashable super image file";
+        return false;
+    }
+
+    for (const auto& block_device : metadata.block_devices) {
+        auto partition = android::fs_mgr::GetBlockDevicePartitionName(block_device);
+        bool force_slot = !!(block_device.flags & LP_BLOCK_DEVICE_SLOT_SUFFIXED);
+
+        std::string image_name;
+        if (metadata.block_devices.size() > 1) {
+            image_name = "super_" + partition + ".img";
+        } else {
+            image_name = partition + ".img";
+        }
+
+        auto image_path = temp_dir.path + "/"s + image_name;
+        auto flash = [&](const std::string& partition_name) {
+            do_flash(partition_name.c_str(), image_path.c_str());
+        };
+        do_for_partitions(partition, slot, flash, force_slot);
+
+        unlink(image_path.c_str());
+    }
+    return true;
+}
+
+static void do_wipe_super(const std::string& image, const std::string& slot_override) {
+    if (access(image.c_str(), R_OK) != 0) {
+        die("Could not read image: %s", image.c_str());
+    }
+    auto metadata = android::fs_mgr::ReadFromImageFile(image);
+    if (!metadata) {
+        die("Could not parse image: %s", image.c_str());
+    }
+
+    auto slot = slot_override;
+    if (slot.empty()) {
+        slot = get_current_slot();
+    }
+
+    std::string message;
+    if (!wipe_super(*metadata.get(), slot, &message)) {
+        die(message);
+    }
+}
+
 int FastBootTool::Main(int argc, char* argv[]) {
     bool wants_wipe = false;
     bool wants_reboot = false;
@@ -1958,6 +2030,14 @@
             } else {
                 syntax_error("expected 'wipe' or 'disable'");
             }
+        } else if (command == "wipe-super") {
+            std::string image;
+            if (args.empty()) {
+                image = find_item_given_name("super_empty.img");
+            } else {
+                image = next_arg(&args);
+            }
+            do_wipe_super(image, slot_override);
         } else {
             syntax_error("unknown command %s", command.c_str());
         }
diff --git a/fastboot/util.cpp b/fastboot/util.cpp
index d02b37f..900d6ea 100644
--- a/fastboot/util.cpp
+++ b/fastboot/util.cpp
@@ -53,6 +53,10 @@
     exit(EXIT_FAILURE);
 }
 
+void die(const std::string& str) {
+    die("%s", str.c_str());
+}
+
 void set_verbose() {
     g_verbose = true;
 }
diff --git a/fastboot/util.h b/fastboot/util.h
index 2535414..c719df2 100644
--- a/fastboot/util.h
+++ b/fastboot/util.h
@@ -15,4 +15,7 @@
 // use the same attribute for compile-time format string checking.
 void die(const char* fmt, ...) __attribute__((__noreturn__))
 __attribute__((__format__(__printf__, 1, 2)));
+
 void verbose(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
+
+void die(const std::string& str) __attribute__((__noreturn__));
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 2a9a9d0..259f800 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -908,7 +908,7 @@
   public:
     CheckpointManager(int needs_checkpoint = -1) : needs_checkpoint_(needs_checkpoint) {}
 
-    bool Update(FstabEntry* entry) {
+    bool Update(FstabEntry* entry, const std::string& block_device = std::string()) {
         if (!entry->fs_mgr_flags.checkpoint_blk && !entry->fs_mgr_flags.checkpoint_fs) {
             return true;
         }
@@ -927,7 +927,7 @@
             return true;
         }
 
-        if (!UpdateCheckpointPartition(entry)) {
+        if (!UpdateCheckpointPartition(entry, block_device)) {
             LERROR << "Could not set up checkpoint partition, skipping!";
             return false;
         }
@@ -957,7 +957,7 @@
     }
 
   private:
-    bool UpdateCheckpointPartition(FstabEntry* entry) {
+    bool UpdateCheckpointPartition(FstabEntry* entry, const std::string& block_device) {
         if (entry->fs_mgr_flags.checkpoint_fs) {
             if (is_f2fs(entry->fs_type)) {
                 entry->fs_options += ",checkpoint=disable";
@@ -965,39 +965,43 @@
                 LERROR << entry->fs_type << " does not implement checkpoints.";
             }
         } else if (entry->fs_mgr_flags.checkpoint_blk) {
-            unique_fd fd(TEMP_FAILURE_RETRY(open(entry->blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
-            if (fd < 0) {
-                PERROR << "Cannot open device " << entry->blk_device;
-                return false;
-            }
+            auto actual_block_device = block_device.empty() ? entry->blk_device : block_device;
+            if (fs_mgr_find_bow_device(actual_block_device).empty()) {
+                unique_fd fd(
+                        TEMP_FAILURE_RETRY(open(entry->blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
+                if (fd < 0) {
+                    PERROR << "Cannot open device " << entry->blk_device;
+                    return false;
+                }
 
-            uint64_t size = get_block_device_size(fd) / 512;
-            if (!size) {
-                PERROR << "Cannot get device size";
-                return false;
-            }
+                uint64_t size = get_block_device_size(fd) / 512;
+                if (!size) {
+                    PERROR << "Cannot get device size";
+                    return false;
+                }
 
-            android::dm::DmTable table;
-            if (!table.AddTarget(
-                        std::make_unique<android::dm::DmTargetBow>(0, size, entry->blk_device))) {
-                LERROR << "Failed to add bow target";
-                return false;
-            }
+                android::dm::DmTable table;
+                if (!table.AddTarget(std::make_unique<android::dm::DmTargetBow>(
+                            0, size, entry->blk_device))) {
+                    LERROR << "Failed to add bow target";
+                    return false;
+                }
 
-            DeviceMapper& dm = DeviceMapper::Instance();
-            if (!dm.CreateDevice("bow", table)) {
-                PERROR << "Failed to create bow device";
-                return false;
-            }
+                DeviceMapper& dm = DeviceMapper::Instance();
+                if (!dm.CreateDevice("bow", table)) {
+                    PERROR << "Failed to create bow device";
+                    return false;
+                }
 
-            std::string name;
-            if (!dm.GetDmDevicePathByName("bow", &name)) {
-                PERROR << "Failed to get bow device name";
-                return false;
-            }
+                std::string name;
+                if (!dm.GetDmDevicePathByName("bow", &name)) {
+                    PERROR << "Failed to get bow device name";
+                    return false;
+                }
 
-            device_map_[name] = entry->blk_device;
-            entry->blk_device = name;
+                device_map_[name] = entry->blk_device;
+                entry->blk_device = name;
+            }
         }
         return true;
     }
@@ -1007,6 +1011,50 @@
     std::map<std::string, std::string> device_map_;
 };
 
+std::string fs_mgr_find_bow_device(const std::string& block_device) {
+    if (block_device.substr(0, 5) != "/dev/") {
+        LOG(ERROR) << "Expected block device, got " << block_device;
+        return std::string();
+    }
+
+    std::string sys_dir = std::string("/sys/") + block_device.substr(5);
+
+    for (;;) {
+        std::string name;
+        if (!android::base::ReadFileToString(sys_dir + "/dm/name", &name)) {
+            PLOG(ERROR) << block_device << " is not dm device";
+            return std::string();
+        }
+
+        if (name == "bow\n") return sys_dir;
+
+        std::string slaves = sys_dir + "/slaves";
+        std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(slaves.c_str()), closedir);
+        if (!directory) {
+            PLOG(ERROR) << "Can't open slave directory " << slaves;
+            return std::string();
+        }
+
+        int count = 0;
+        for (dirent* entry = readdir(directory.get()); entry; entry = readdir(directory.get())) {
+            if (entry->d_type != DT_LNK) continue;
+
+            if (count == 1) {
+                LOG(ERROR) << "Too many slaves in " << slaves;
+                return std::string();
+            }
+
+            ++count;
+            sys_dir = std::string("/sys/block/") + entry->d_name;
+        }
+
+        if (count != 1) {
+            LOG(ERROR) << "No slave in " << slaves;
+            return std::string();
+        }
+    }
+}
+
 static bool IsMountPointMounted(const std::string& mount_point) {
     // Check if this is already mounted.
     Fstab fstab;
@@ -1144,7 +1192,8 @@
                 }
                 encryptable = status;
                 if (status == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
-                    if (!call_vdc({"cryptfs", "encryptFstab", attempted_entry.mount_point})) {
+                    if (!call_vdc({"cryptfs", "encryptFstab", attempted_entry.blk_device,
+                                   attempted_entry.mount_point})) {
                         LERROR << "Encryption failed";
                         return FS_MGR_MNTALL_FAIL;
                     }
@@ -1215,7 +1264,8 @@
             encryptable = FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED;
         } else if (mount_errno != EBUSY && mount_errno != EACCES &&
                    should_use_metadata_encryption(attempted_entry)) {
-            if (!call_vdc({"cryptfs", "mountFstab", attempted_entry.mount_point})) {
+            if (!call_vdc({"cryptfs", "mountFstab", attempted_entry.blk_device,
+                           attempted_entry.mount_point})) {
                 ++error_count;
             }
             encryptable = FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED;
@@ -1345,7 +1395,7 @@
             }
         }
 
-        if (!checkpoint_manager.Update(&fstab_entry)) {
+        if (!checkpoint_manager.Update(&fstab_entry, n_blk_device)) {
             LERROR << "Could not set up checkpoint partition, skipping!";
             continue;
         }
diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h
index 88b2f8f..bdec7be 100644
--- a/fs_mgr/include/fs_mgr.h
+++ b/fs_mgr/include/fs_mgr.h
@@ -104,3 +104,7 @@
 // fs_mgr_umount_all() is the reverse of fs_mgr_mount_all. In particular,
 // it destroys verity devices from device mapper after the device is unmounted.
 int fs_mgr_umount_all(android::fs_mgr::Fstab* fstab);
+
+// Finds the dm_bow device on which this block device is stacked, or returns
+// empty string
+std::string fs_mgr_find_bow_device(const std::string& block_device);
diff --git a/gatekeeperd/Android.bp b/gatekeeperd/Android.bp
index 2b7db79..778e08c 100644
--- a/gatekeeperd/Android.bp
+++ b/gatekeeperd/Android.bp
@@ -23,8 +23,6 @@
         "-Wunused",
     ],
     srcs: [
-        "SoftGateKeeperDevice.cpp",
-        "IGateKeeperService.cpp",
         "gatekeeperd.cpp",
     ],
 
@@ -43,9 +41,44 @@
         "libhidltransport",
         "libhwbinder",
         "android.hardware.gatekeeper@1.0",
+        "libgatekeeper_aidl",
     ],
 
     static_libs: ["libscrypt_static"],
     include_dirs: ["external/scrypt/lib/crypto"],
     init_rc: ["gatekeeperd.rc"],
 }
+
+filegroup {
+    name: "gatekeeper_aidl",
+    srcs: [
+        "binder/android/service/gatekeeper/IGateKeeperService.aidl",
+    ],
+    path: "binder",
+}
+
+cc_library_shared {
+    name: "libgatekeeper_aidl",
+    srcs: [
+        ":gatekeeper_aidl",
+        "GateKeeperResponse.cpp",
+    ],
+    aidl: {
+        export_aidl_headers: true,
+        include_dirs: [
+            "system/core/gatekeeperd/binder",
+            "frameworks/base/core/java/",
+        ],
+    },
+    export_include_dirs: ["include"],
+    shared_libs: [
+        "libbase",
+        "libbinder",
+        "libcutils",
+        "liblog",
+        "libutils",
+    ],
+    export_shared_lib_headers: [
+        "libbinder",
+    ],
+}
diff --git a/gatekeeperd/GateKeeperResponse.cpp b/gatekeeperd/GateKeeperResponse.cpp
new file mode 100644
index 0000000..ca0c98f
--- /dev/null
+++ b/gatekeeperd/GateKeeperResponse.cpp
@@ -0,0 +1,83 @@
+/*
+**
+** Copyright 2019, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#define LOG_TAG "gatekeeperd"
+
+#include <gatekeeper/GateKeeperResponse.h>
+
+#include <binder/Parcel.h>
+
+#include <android-base/logging.h>
+
+namespace android {
+namespace service {
+namespace gatekeeper {
+
+status_t GateKeeperResponse::readFromParcel(const Parcel* in) {
+    if (in == nullptr) {
+        LOG(ERROR) << "readFromParcel got null in parameter";
+        return BAD_VALUE;
+    }
+    timeout_ = 0;
+    should_reenroll_ = false;
+    payload_ = {};
+    response_code_ = ResponseCode(in->readInt32());
+    if (response_code_ == ResponseCode::OK) {
+        should_reenroll_ = in->readInt32();
+        ssize_t length = in->readInt32();
+        if (length > 0) {
+            length = in->readInt32();
+            const uint8_t* buf = reinterpret_cast<const uint8_t*>(in->readInplace(length));
+            if (buf == nullptr) {
+                LOG(ERROR) << "readInplace returned null buffer for length " << length;
+                return BAD_VALUE;
+            }
+            payload_.resize(length);
+            std::copy(buf, buf + length, payload_.data());
+        }
+    } else if (response_code_ == ResponseCode::RETRY) {
+        timeout_ = in->readInt32();
+    }
+    return NO_ERROR;
+}
+status_t GateKeeperResponse::writeToParcel(Parcel* out) const {
+    if (out == nullptr) {
+        LOG(ERROR) << "writeToParcel got null out parameter";
+        return BAD_VALUE;
+    }
+    out->writeInt32(int32_t(response_code_));
+    if (response_code_ == ResponseCode::OK) {
+        out->writeInt32(should_reenroll_);
+        out->writeInt32(payload_.size());
+        if (payload_.size() != 0) {
+            out->writeInt32(payload_.size());
+            uint8_t* buf = reinterpret_cast<uint8_t*>(out->writeInplace(payload_.size()));
+            if (buf == nullptr) {
+                LOG(ERROR) << "writeInplace returned null buffer for length " << payload_.size();
+                return BAD_VALUE;
+            }
+            std::copy(payload_.begin(), payload_.end(), buf);
+        }
+    } else if (response_code_ == ResponseCode::RETRY) {
+        out->writeInt32(timeout_);
+    }
+    return NO_ERROR;
+}
+
+}  // namespace gatekeeper
+}  // namespace service
+}  // namespace android
diff --git a/gatekeeperd/IGateKeeperService.cpp b/gatekeeperd/IGateKeeperService.cpp
deleted file mode 100644
index 43d5708..0000000
--- a/gatekeeperd/IGateKeeperService.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright 2015, The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-*/
-
-#define LOG_TAG "GateKeeperService"
-#include <utils/Log.h>
-
-#include "IGateKeeperService.h"
-
-namespace android {
-
-const android::String16 IGateKeeperService::descriptor("android.service.gatekeeper.IGateKeeperService");
-const android::String16& IGateKeeperService::getInterfaceDescriptor() const {
-    return IGateKeeperService::descriptor;
-}
-
-status_t BnGateKeeperService::onTransact(
-    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
-    switch(code) {
-        case ENROLL: {
-            CHECK_INTERFACE(IGateKeeperService, data, reply);
-            uint32_t uid = data.readInt32();
-
-            ssize_t currentPasswordHandleSize = data.readInt32();
-            const uint8_t *currentPasswordHandle =
-                    static_cast<const uint8_t *>(data.readInplace(currentPasswordHandleSize));
-            if (!currentPasswordHandle) currentPasswordHandleSize = 0;
-
-            ssize_t currentPasswordSize = data.readInt32();
-            const uint8_t *currentPassword =
-                    static_cast<const uint8_t *>(data.readInplace(currentPasswordSize));
-            if (!currentPassword) currentPasswordSize = 0;
-
-            ssize_t desiredPasswordSize = data.readInt32();
-            const uint8_t *desiredPassword =
-                    static_cast<const uint8_t *>(data.readInplace(desiredPasswordSize));
-            if (!desiredPassword) desiredPasswordSize = 0;
-
-            uint8_t *out = NULL;
-            uint32_t outSize = 0;
-            int ret = enroll(uid, currentPasswordHandle, currentPasswordHandleSize,
-                    currentPassword, currentPasswordSize, desiredPassword,
-                    desiredPasswordSize, &out, &outSize);
-
-            reply->writeNoException();
-            reply->writeInt32(1);
-            if (ret == 0 && outSize > 0 && out != NULL) {
-                reply->writeInt32(GATEKEEPER_RESPONSE_OK);
-                reply->writeInt32(0);
-                reply->writeInt32(outSize);
-                reply->writeInt32(outSize);
-                void *buf = reply->writeInplace(outSize);
-                memcpy(buf, out, outSize);
-                delete[] out;
-            } else if (ret > 0) {
-                reply->writeInt32(GATEKEEPER_RESPONSE_RETRY);
-                reply->writeInt32(ret);
-            } else {
-                reply->writeInt32(GATEKEEPER_RESPONSE_ERROR);
-            }
-            return OK;
-        }
-        case VERIFY: {
-            CHECK_INTERFACE(IGateKeeperService, data, reply);
-            uint32_t uid = data.readInt32();
-            ssize_t currentPasswordHandleSize = data.readInt32();
-            const uint8_t *currentPasswordHandle =
-                    static_cast<const uint8_t *>(data.readInplace(currentPasswordHandleSize));
-            if (!currentPasswordHandle) currentPasswordHandleSize = 0;
-
-            ssize_t currentPasswordSize = data.readInt32();
-            const uint8_t *currentPassword =
-                static_cast<const uint8_t *>(data.readInplace(currentPasswordSize));
-            if (!currentPassword) currentPasswordSize = 0;
-
-            bool request_reenroll = false;
-            int ret = verify(uid, (uint8_t *) currentPasswordHandle,
-                    currentPasswordHandleSize, (uint8_t *) currentPassword, currentPasswordSize,
-                    &request_reenroll);
-
-            reply->writeNoException();
-            reply->writeInt32(1);
-            if (ret == 0) {
-                reply->writeInt32(GATEKEEPER_RESPONSE_OK);
-                reply->writeInt32(request_reenroll ? 1 : 0);
-                reply->writeInt32(0); // no payload returned from this call
-            } else if (ret > 0) {
-                reply->writeInt32(GATEKEEPER_RESPONSE_RETRY);
-                reply->writeInt32(ret);
-            } else {
-                reply->writeInt32(GATEKEEPER_RESPONSE_ERROR);
-            }
-            return OK;
-        }
-        case VERIFY_CHALLENGE: {
-            CHECK_INTERFACE(IGateKeeperService, data, reply);
-            uint32_t uid = data.readInt32();
-            uint64_t challenge = data.readInt64();
-            ssize_t currentPasswordHandleSize = data.readInt32();
-            const uint8_t *currentPasswordHandle =
-                    static_cast<const uint8_t *>(data.readInplace(currentPasswordHandleSize));
-            if (!currentPasswordHandle) currentPasswordHandleSize = 0;
-
-            ssize_t currentPasswordSize = data.readInt32();
-            const uint8_t *currentPassword =
-                static_cast<const uint8_t *>(data.readInplace(currentPasswordSize));
-            if (!currentPassword) currentPasswordSize = 0;
-
-
-            uint8_t *out = NULL;
-            uint32_t outSize = 0;
-            bool request_reenroll = false;
-            int ret = verifyChallenge(uid, challenge, (uint8_t *) currentPasswordHandle,
-                    currentPasswordHandleSize, (uint8_t *) currentPassword, currentPasswordSize,
-                    &out, &outSize, &request_reenroll);
-            reply->writeNoException();
-            reply->writeInt32(1);
-            if (ret == 0 && outSize > 0 && out != NULL) {
-                reply->writeInt32(GATEKEEPER_RESPONSE_OK);
-                reply->writeInt32(request_reenroll ? 1 : 0);
-                reply->writeInt32(outSize);
-                reply->writeInt32(outSize);
-                void *buf = reply->writeInplace(outSize);
-                memcpy(buf, out, outSize);
-                delete[] out;
-            } else if (ret > 0) {
-                reply->writeInt32(GATEKEEPER_RESPONSE_RETRY);
-                reply->writeInt32(ret);
-            } else {
-                reply->writeInt32(GATEKEEPER_RESPONSE_ERROR);
-            }
-            return OK;
-        }
-        case GET_SECURE_USER_ID: {
-            CHECK_INTERFACE(IGateKeeperService, data, reply);
-            uint32_t uid = data.readInt32();
-            uint64_t sid = getSecureUserId(uid);
-            reply->writeNoException();
-            reply->writeInt64(sid);
-            return OK;
-        }
-        case CLEAR_SECURE_USER_ID: {
-            CHECK_INTERFACE(IGateKeeperService, data, reply);
-            uint32_t uid = data.readInt32();
-            clearSecureUserId(uid);
-            reply->writeNoException();
-            return OK;
-        }
-        case REPORT_DEVICE_SETUP_COMPLETE: {
-            CHECK_INTERFACE(IGateKeeperService, data, reply);
-            reportDeviceSetupComplete();
-            reply->writeNoException();
-            return OK;
-        }
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
-    }
-};
-
-
-}; // namespace android
diff --git a/gatekeeperd/IGateKeeperService.h b/gatekeeperd/IGateKeeperService.h
deleted file mode 100644
index 2816efc..0000000
--- a/gatekeeperd/IGateKeeperService.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef IGATEKEEPER_SERVICE_H_
-#define IGATEKEEPER_SERVICE_H_
-
-#include <binder/IInterface.h>
-#include <binder/Parcel.h>
-
-namespace android {
-
-/*
- * This must be kept manually in sync with frameworks/base's IGateKeeperService.aidl
- */
-class IGateKeeperService : public IInterface {
-public:
-    enum {
-        ENROLL = IBinder::FIRST_CALL_TRANSACTION + 0,
-        VERIFY = IBinder::FIRST_CALL_TRANSACTION + 1,
-        VERIFY_CHALLENGE = IBinder::FIRST_CALL_TRANSACTION + 2,
-        GET_SECURE_USER_ID = IBinder::FIRST_CALL_TRANSACTION + 3,
-        CLEAR_SECURE_USER_ID = IBinder::FIRST_CALL_TRANSACTION + 4,
-        REPORT_DEVICE_SETUP_COMPLETE = IBinder::FIRST_CALL_TRANSACTION + 5,
-    };
-
-    enum {
-        GATEKEEPER_RESPONSE_OK = 0,
-        GATEKEEPER_RESPONSE_RETRY = 1,
-        GATEKEEPER_RESPONSE_ERROR = -1,
-    };
-
-    // DECLARE_META_INTERFACE - C++ client interface not needed
-    static const android::String16 descriptor;
-    virtual const android::String16& getInterfaceDescriptor() const;
-    IGateKeeperService() {}
-    virtual ~IGateKeeperService() {}
-
-    /**
-     * Enrolls a password with the GateKeeper. Returns 0 on success, negative on failure.
-     * Returns:
-     * - 0 on success
-     * - A timestamp T > 0 if the call has failed due to throttling and should not
-     *   be reattempted until T milliseconds have elapsed
-     * - -1 on failure
-     */
-    virtual int enroll(uint32_t uid,
-            const uint8_t *current_password_handle, uint32_t current_password_handle_length,
-            const uint8_t *current_password, uint32_t current_password_length,
-            const uint8_t *desired_password, uint32_t desired_password_length,
-            uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) = 0;
-
-    /**
-     * Verifies a password previously enrolled with the GateKeeper.
-     * Returns:
-     * - 0 on success
-     * - A timestamp T > 0 if the call has failed due to throttling and should not
-     *   be reattempted until T milliseconds have elapsed
-     * - -1 on failure
-     */
-    virtual int verify(uint32_t uid, const uint8_t *enrolled_password_handle,
-            uint32_t enrolled_password_handle_length,
-            const uint8_t *provided_password, uint32_t provided_password_length,
-            bool *request_reenroll) = 0;
-
-    /**
-     * Verifies a password previously enrolled with the GateKeeper.
-     * Returns:
-     * - 0 on success
-     * - A timestamp T > 0 if the call has failed due to throttling and should not
-     *   be reattempted until T milliseconds have elapsed
-     * - -1 on failure
-     */
-    virtual int verifyChallenge(uint32_t uid, uint64_t challenge,
-            const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
-            const uint8_t *provided_password, uint32_t provided_password_length,
-            uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll) = 0;
-    /**
-     * Returns the secure user ID for the provided android user
-     */
-    virtual uint64_t getSecureUserId(uint32_t uid) = 0;
-
-    /**
-     * Clears the secure user ID associated with the user.
-     */
-    virtual void clearSecureUserId(uint32_t uid) = 0;
-
-    /**
-     * Notifies gatekeeper that device setup has been completed and any potentially still existing
-     * state from before a factory reset can be cleaned up (if it has not been already).
-     */
-    virtual void reportDeviceSetupComplete() = 0;
-};
-
-// ----------------------------------------------------------------------------
-
-class BnGateKeeperService: public BnInterface<IGateKeeperService> {
-public:
-    virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply,
-            uint32_t flags = 0);
-};
-
-} // namespace android
-
-#endif
-
diff --git a/gatekeeperd/SoftGateKeeper.h b/gatekeeperd/SoftGateKeeper.h
deleted file mode 100644
index 2f4f4d7..0000000
--- a/gatekeeperd/SoftGateKeeper.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-#ifndef SOFT_GATEKEEPER_H_
-#define SOFT_GATEKEEPER_H_
-
-extern "C" {
-#include <openssl/rand.h>
-#include <openssl/sha.h>
-
-#include <crypto_scrypt.h>
-}
-
-#include <android-base/memory.h>
-#include <gatekeeper/gatekeeper.h>
-
-#include <iostream>
-#include <unordered_map>
-#include <memory>
-
-namespace gatekeeper {
-
-struct fast_hash_t {
-    uint64_t salt;
-    uint8_t digest[SHA256_DIGEST_LENGTH];
-};
-
-class SoftGateKeeper : public GateKeeper {
-public:
-    static const uint32_t SIGNATURE_LENGTH_BYTES = 32;
-
-    // scrypt params
-    static const uint64_t N = 16384;
-    static const uint32_t r = 8;
-    static const uint32_t p = 1;
-
-    static const int MAX_UINT_32_CHARS = 11;
-
-    SoftGateKeeper() {
-        key_.reset(new uint8_t[SIGNATURE_LENGTH_BYTES]);
-        memset(key_.get(), 0, SIGNATURE_LENGTH_BYTES);
-    }
-
-    virtual ~SoftGateKeeper() {
-    }
-
-    virtual bool GetAuthTokenKey(const uint8_t **auth_token_key,
-            uint32_t *length) const {
-        if (auth_token_key == NULL || length == NULL) return false;
-        uint8_t *auth_token_key_copy = new uint8_t[SIGNATURE_LENGTH_BYTES];
-        memcpy(auth_token_key_copy, key_.get(), SIGNATURE_LENGTH_BYTES);
-
-        *auth_token_key = auth_token_key_copy;
-        *length = SIGNATURE_LENGTH_BYTES;
-        return true;
-    }
-
-    virtual void GetPasswordKey(const uint8_t **password_key, uint32_t *length) {
-        if (password_key == NULL || length == NULL) return;
-        uint8_t *password_key_copy = new uint8_t[SIGNATURE_LENGTH_BYTES];
-        memcpy(password_key_copy, key_.get(), SIGNATURE_LENGTH_BYTES);
-
-        *password_key = password_key_copy;
-        *length = SIGNATURE_LENGTH_BYTES;
-    }
-
-    virtual void ComputePasswordSignature(uint8_t *signature, uint32_t signature_length,
-            const uint8_t *, uint32_t, const uint8_t *password,
-            uint32_t password_length, salt_t salt) const {
-        if (signature == NULL) return;
-        crypto_scrypt(password, password_length, reinterpret_cast<uint8_t *>(&salt),
-                sizeof(salt), N, r, p, signature, signature_length);
-    }
-
-    virtual void GetRandom(void *random, uint32_t requested_length) const {
-        if (random == NULL) return;
-        RAND_pseudo_bytes((uint8_t *) random, requested_length);
-    }
-
-    virtual void ComputeSignature(uint8_t *signature, uint32_t signature_length,
-            const uint8_t *, uint32_t, const uint8_t *, const uint32_t) const {
-        if (signature == NULL) return;
-        memset(signature, 0, signature_length);
-    }
-
-    virtual uint64_t GetMillisecondsSinceBoot() const {
-        struct timespec time;
-        int res = clock_gettime(CLOCK_BOOTTIME, &time);
-        if (res < 0) return 0;
-        return (time.tv_sec * 1000) + (time.tv_nsec / 1000 / 1000);
-    }
-
-    virtual bool IsHardwareBacked() const {
-        return false;
-    }
-
-    virtual bool GetFailureRecord(uint32_t uid, secure_id_t user_id, failure_record_t *record,
-            bool /* secure */) {
-        failure_record_t *stored = &failure_map_[uid];
-        if (user_id != stored->secure_user_id) {
-            stored->secure_user_id = user_id;
-            stored->last_checked_timestamp = 0;
-            stored->failure_counter = 0;
-        }
-        memcpy(record, stored, sizeof(*record));
-        return true;
-    }
-
-    virtual bool ClearFailureRecord(uint32_t uid, secure_id_t user_id, bool /* secure */) {
-        failure_record_t *stored = &failure_map_[uid];
-        stored->secure_user_id = user_id;
-        stored->last_checked_timestamp = 0;
-        stored->failure_counter = 0;
-        return true;
-    }
-
-    virtual bool WriteFailureRecord(uint32_t uid, failure_record_t *record, bool /* secure */) {
-        failure_map_[uid] = *record;
-        return true;
-    }
-
-    fast_hash_t ComputeFastHash(const SizedBuffer &password, uint64_t salt) {
-        fast_hash_t fast_hash;
-        size_t digest_size = password.length + sizeof(salt);
-        std::unique_ptr<uint8_t[]> digest(new uint8_t[digest_size]);
-        memcpy(digest.get(), &salt, sizeof(salt));
-        memcpy(digest.get() + sizeof(salt), password.buffer.get(), password.length);
-
-        SHA256(digest.get(), digest_size, (uint8_t *) &fast_hash.digest);
-
-        fast_hash.salt = salt;
-        return fast_hash;
-    }
-
-    bool VerifyFast(const fast_hash_t &fast_hash, const SizedBuffer &password) {
-        fast_hash_t computed = ComputeFastHash(password, fast_hash.salt);
-        return memcmp(computed.digest, fast_hash.digest, SHA256_DIGEST_LENGTH) == 0;
-    }
-
-    bool DoVerify(const password_handle_t *expected_handle, const SizedBuffer &password) {
-        uint64_t user_id = android::base::get_unaligned<secure_id_t>(&expected_handle->user_id);
-        FastHashMap::const_iterator it = fast_hash_map_.find(user_id);
-        if (it != fast_hash_map_.end() && VerifyFast(it->second, password)) {
-            return true;
-        } else {
-            if (GateKeeper::DoVerify(expected_handle, password)) {
-                uint64_t salt;
-                GetRandom(&salt, sizeof(salt));
-                fast_hash_map_[user_id] = ComputeFastHash(password, salt);
-                return true;
-            }
-        }
-
-        return false;
-    }
-
-private:
-
-    typedef std::unordered_map<uint32_t, failure_record_t> FailureRecordMap;
-    typedef std::unordered_map<uint64_t, fast_hash_t> FastHashMap;
-
-    std::unique_ptr<uint8_t[]> key_;
-    FailureRecordMap failure_map_;
-    FastHashMap fast_hash_map_;
-};
-}
-
-#endif // SOFT_GATEKEEPER_H_
diff --git a/gatekeeperd/SoftGateKeeperDevice.cpp b/gatekeeperd/SoftGateKeeperDevice.cpp
deleted file mode 100644
index f5e2ce6..0000000
--- a/gatekeeperd/SoftGateKeeperDevice.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "SoftGateKeeper.h"
-#include "SoftGateKeeperDevice.h"
-
-namespace android {
-
-int SoftGateKeeperDevice::enroll(uint32_t uid,
-            const uint8_t *current_password_handle, uint32_t current_password_handle_length,
-            const uint8_t *current_password, uint32_t current_password_length,
-            const uint8_t *desired_password, uint32_t desired_password_length,
-            uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) {
-
-    if (enrolled_password_handle == NULL || enrolled_password_handle_length == NULL ||
-            desired_password == NULL || desired_password_length == 0)
-        return -EINVAL;
-
-    // Current password and current password handle go together
-    if (current_password_handle == NULL || current_password_handle_length == 0 ||
-            current_password == NULL || current_password_length == 0) {
-        current_password_handle = NULL;
-        current_password_handle_length = 0;
-        current_password = NULL;
-        current_password_length = 0;
-    }
-
-    SizedBuffer desired_password_buffer(desired_password_length);
-    memcpy(desired_password_buffer.buffer.get(), desired_password, desired_password_length);
-
-    SizedBuffer current_password_handle_buffer(current_password_handle_length);
-    if (current_password_handle) {
-        memcpy(current_password_handle_buffer.buffer.get(), current_password_handle,
-                current_password_handle_length);
-    }
-
-    SizedBuffer current_password_buffer(current_password_length);
-    if (current_password) {
-        memcpy(current_password_buffer.buffer.get(), current_password, current_password_length);
-    }
-
-    EnrollRequest request(uid, &current_password_handle_buffer, &desired_password_buffer,
-            &current_password_buffer);
-    EnrollResponse response;
-
-    impl_->Enroll(request, &response);
-
-    if (response.error == ERROR_RETRY) {
-        return response.retry_timeout;
-    } else if (response.error != ERROR_NONE) {
-        return -EINVAL;
-    }
-
-    *enrolled_password_handle = response.enrolled_password_handle.buffer.release();
-    *enrolled_password_handle_length = response.enrolled_password_handle.length;
-    return 0;
-}
-
-int SoftGateKeeperDevice::verify(uint32_t uid,
-        uint64_t challenge, const uint8_t *enrolled_password_handle,
-        uint32_t enrolled_password_handle_length, const uint8_t *provided_password,
-        uint32_t provided_password_length, uint8_t **auth_token, uint32_t *auth_token_length,
-        bool *request_reenroll) {
-
-    if (enrolled_password_handle == NULL ||
-            provided_password == NULL) {
-        return -EINVAL;
-    }
-
-    SizedBuffer password_handle_buffer(enrolled_password_handle_length);
-    memcpy(password_handle_buffer.buffer.get(), enrolled_password_handle,
-            enrolled_password_handle_length);
-    SizedBuffer provided_password_buffer(provided_password_length);
-    memcpy(provided_password_buffer.buffer.get(), provided_password, provided_password_length);
-
-    VerifyRequest request(uid, challenge, &password_handle_buffer, &provided_password_buffer);
-    VerifyResponse response;
-
-    impl_->Verify(request, &response);
-
-    if (response.error == ERROR_RETRY) {
-        return response.retry_timeout;
-    } else if (response.error != ERROR_NONE) {
-        return -EINVAL;
-    }
-
-    if (auth_token != NULL && auth_token_length != NULL) {
-       *auth_token = response.auth_token.buffer.release();
-       *auth_token_length = response.auth_token.length;
-    }
-
-    if (request_reenroll != NULL) {
-        *request_reenroll = response.request_reenroll;
-    }
-
-    return 0;
-}
-} // namespace android
diff --git a/gatekeeperd/SoftGateKeeperDevice.h b/gatekeeperd/SoftGateKeeperDevice.h
deleted file mode 100644
index e3dc068..0000000
--- a/gatekeeperd/SoftGateKeeperDevice.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef SOFT_GATEKEEPER_DEVICE_H_
-#define SOFT_GATEKEEPER_DEVICE_H_
-
-#include "SoftGateKeeper.h"
-
-#include <memory>
-
-using namespace gatekeeper;
-
-namespace android {
-
-/**
- * Software based GateKeeper implementation
- */
-class SoftGateKeeperDevice {
-public:
-    SoftGateKeeperDevice() {
-        impl_.reset(new SoftGateKeeper());
-    }
-
-   // Wrappers to translate the gatekeeper HAL API to the Kegyuard Messages API.
-
-    /**
-     * Enrolls password_payload, which should be derived from a user selected pin or password,
-     * with the authentication factor private key used only for enrolling authentication
-     * factor data.
-     *
-     * Returns: 0 on success or an error code less than 0 on error.
-     * On error, enrolled_password_handle will not be allocated.
-     */
-    int enroll(uint32_t uid,
-            const uint8_t *current_password_handle, uint32_t current_password_handle_length,
-            const uint8_t *current_password, uint32_t current_password_length,
-            const uint8_t *desired_password, uint32_t desired_password_length,
-            uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length);
-
-    /**
-     * Verifies provided_password matches enrolled_password_handle.
-     *
-     * Implementations of this module may retain the result of this call
-     * to attest to the recency of authentication.
-     *
-     * On success, writes the address of a verification token to auth_token,
-     * usable to attest password verification to other trusted services. Clients
-     * may pass NULL for this value.
-     *
-     * Returns: 0 on success or an error code less than 0 on error
-     * On error, verification token will not be allocated
-     */
-    int verify(uint32_t uid, uint64_t challenge,
-            const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
-            const uint8_t *provided_password, uint32_t provided_password_length,
-            uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll);
-private:
-    std::unique_ptr<SoftGateKeeper> impl_;
-};
-
-} // namespace gatekeeper
-
-#endif //SOFT_GATEKEEPER_DEVICE_H_
diff --git a/logd/LogBufferInterface.cpp b/gatekeeperd/binder/android/service/gatekeeper/GateKeeperResponse.aidl
similarity index 60%
rename from logd/LogBufferInterface.cpp
rename to gatekeeperd/binder/android/service/gatekeeper/GateKeeperResponse.aidl
index 4b6d363..097bb54 100644
--- a/logd/LogBufferInterface.cpp
+++ b/gatekeeperd/binder/android/service/gatekeeper/GateKeeperResponse.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2015 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,16 +14,11 @@
  * limitations under the License.
  */
 
-#include "LogBufferInterface.h"
-#include "LogUtils.h"
+package android.service.gatekeeper;
 
-LogBufferInterface::LogBufferInterface() {
-}
-LogBufferInterface::~LogBufferInterface() {
-}
-uid_t LogBufferInterface::pidToUid(pid_t pid) {
-    return android::pidToUid(pid);
-}
-pid_t LogBufferInterface::tidToPid(pid_t tid) {
-    return android::tidToPid(tid);
-}
+/**
+ * Response object for a GateKeeper verification request.
+ * @hide
+ */
+parcelable GateKeeperResponse cpp_header "gatekeeper/GateKeeperResponse.h";
+
diff --git a/gatekeeperd/binder/android/service/gatekeeper/IGateKeeperService.aidl b/gatekeeperd/binder/android/service/gatekeeper/IGateKeeperService.aidl
new file mode 100644
index 0000000..57adaba
--- /dev/null
+++ b/gatekeeperd/binder/android/service/gatekeeper/IGateKeeperService.aidl
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.service.gatekeeper;
+
+import android.service.gatekeeper.GateKeeperResponse;
+
+/**
+ * Interface for communication with GateKeeper, the
+ * secure password storage daemon.
+ *
+ * This must be kept manually in sync with system/core/gatekeeperd
+ * until AIDL can generate both C++ and Java bindings.
+ *
+ * @hide
+ */
+interface IGateKeeperService {
+    /**
+     * Enrolls a password, returning the handle to the enrollment to be stored locally.
+     * @param uid The Android user ID associated to this enrollment
+     * @param currentPasswordHandle The previously enrolled handle, or null if none
+     * @param currentPassword The previously enrolled plaintext password, or null if none.
+     *                        If provided, must verify against the currentPasswordHandle.
+     * @param desiredPassword The new desired password, for which a handle will be returned
+     *                        upon success.
+     * @return an EnrollResponse or null on failure
+     */
+    GateKeeperResponse enroll(int uid, in @nullable byte[] currentPasswordHandle,
+            in @nullable byte[] currentPassword, in byte[] desiredPassword);
+
+    /**
+     * Verifies an enrolled handle against a provided, plaintext blob.
+     * @param uid The Android user ID associated to this enrollment
+     * @param enrolledPasswordHandle The handle against which the provided password will be
+     *                               verified.
+     * @param The plaintext blob to verify against enrolledPassword.
+     * @return a VerifyResponse, or null on failure.
+     */
+    GateKeeperResponse verify(int uid, in byte[] enrolledPasswordHandle, in byte[] providedPassword);
+
+    /**
+     * Verifies an enrolled handle against a provided, plaintext blob.
+     * @param uid The Android user ID associated to this enrollment
+     * @param challenge a challenge to authenticate agaisnt the device credential. If successful
+     *                  authentication occurs, this value will be written to the returned
+     *                  authentication attestation.
+     * @param enrolledPasswordHandle The handle against which the provided password will be
+     *                               verified.
+     * @param The plaintext blob to verify against enrolledPassword.
+     * @return a VerifyResponse with an attestation, or null on failure.
+     */
+    GateKeeperResponse verifyChallenge(int uid, long challenge, in byte[] enrolledPasswordHandle,
+            in byte[] providedPassword);
+
+    /**
+     * Retrieves the secure identifier for the user with the provided Android ID,
+     * or 0 if none is found.
+     * @param uid the Android user id
+     */
+    long getSecureUserId(int uid);
+
+    /**
+     * Clears secure user id associated with the provided Android ID.
+     * Must be called when password is set to NONE.
+     * @param uid the Android user id.
+     */
+    void clearSecureUserId(int uid);
+
+    /**
+     * Notifies gatekeeper that device setup has been completed and any potentially still existing
+     * state from before a factory reset can be cleaned up (if it has not been already).
+     */
+    void reportDeviceSetupComplete();
+}
diff --git a/gatekeeperd/gatekeeperd.cpp b/gatekeeperd/gatekeeperd.cpp
index 8700c34..1d65b1c 100644
--- a/gatekeeperd/gatekeeperd.cpp
+++ b/gatekeeperd/gatekeeperd.cpp
@@ -16,7 +16,8 @@
 
 #define LOG_TAG "gatekeeperd"
 
-#include "IGateKeeperService.h"
+#include <android/service/gatekeeper/BnGateKeeperService.h>
+#include <gatekeeper/GateKeeperResponse.h>
 
 #include <errno.h>
 #include <fcntl.h>
@@ -41,8 +42,6 @@
 #include <utils/Log.h>
 #include <utils/String16.h>
 
-#include "SoftGateKeeperDevice.h"
-
 #include <hidl/HidlSupport.h>
 #include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
 
@@ -52,6 +51,11 @@
 using android::hardware::gatekeeper::V1_0::GatekeeperResponse;
 using android::hardware::Return;
 
+using ::android::binder::Status;
+using ::android::service::gatekeeper::BnGateKeeperService;
+using GKResponse = ::android::service::gatekeeper::GateKeeperResponse;
+using GKResponseCode = ::android::service::gatekeeper::ResponseCode;
+
 namespace android {
 
 static const String16 KEYGUARD_PERMISSION("android.permission.ACCESS_KEYGUARD_SECURE_STORAGE");
@@ -64,9 +68,8 @@
         hw_device = IGatekeeper::getService();
         is_running_gsi = android::base::GetBoolProperty(android::gsi::kGsiBootedProp, false);
 
-        if (hw_device == nullptr) {
-            ALOGW("falling back to software GateKeeper");
-            soft_device.reset(new SoftGateKeeperDevice());
+        if (!hw_device) {
+            LOG(ERROR) << "Could not find Gatekeeper device, which makes me very sad.";
         }
     }
 
@@ -92,7 +95,7 @@
 
         if (mark_cold_boot() && !is_running_gsi) {
             ALOGI("cold boot: clearing state");
-            if (hw_device != nullptr) {
+            if (hw_device) {
                 hw_device->deleteAllUsers([](const GatekeeperResponse &){});
             }
         }
@@ -154,16 +157,16 @@
         return uid;
     }
 
-    virtual int enroll(uint32_t uid,
-            const uint8_t *current_password_handle, uint32_t current_password_handle_length,
-            const uint8_t *current_password, uint32_t current_password_length,
-            const uint8_t *desired_password, uint32_t desired_password_length,
-            uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) {
+#define GK_ERROR *gkResponse = GKResponse::error(), Status::ok()
+
+    Status enroll(int32_t uid, const std::unique_ptr<std::vector<uint8_t>>& currentPasswordHandle,
+                  const std::unique_ptr<std::vector<uint8_t>>& currentPassword,
+                  const std::vector<uint8_t>& desiredPassword, GKResponse* gkResponse) override {
         IPCThreadState* ipc = IPCThreadState::self();
         const int calling_pid = ipc->getCallingPid();
         const int calling_uid = ipc->getCallingUid();
         if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
-            return PERMISSION_DENIED;
+            return GK_ERROR;
         }
 
         // Make sure to clear any state from before factory reset as soon as a credential is
@@ -171,225 +174,189 @@
         clear_state_if_needed();
 
         // need a desired password to enroll
-        if (desired_password_length == 0) return -EINVAL;
+        if (desiredPassword.size() == 0) return GK_ERROR;
 
-        int ret;
-        if (hw_device != nullptr) {
-            const gatekeeper::password_handle_t *handle =
-                    reinterpret_cast<const gatekeeper::password_handle_t *>(current_password_handle);
+        if (!hw_device) {
+            LOG(ERROR) << "has no HAL to talk to";
+            return GK_ERROR;
+        }
 
-            if (handle != NULL && handle->version != 0 && !handle->hardware_backed) {
-                // handle is being re-enrolled from a software version. HAL probably won't accept
-                // the handle as valid, so we nullify it and enroll from scratch
-                current_password_handle = NULL;
-                current_password_handle_length = 0;
-                current_password = NULL;
-                current_password_length = 0;
+        android::hardware::hidl_vec<uint8_t> curPwdHandle;
+        android::hardware::hidl_vec<uint8_t> curPwd;
+
+        if (currentPasswordHandle && currentPassword) {
+            if (currentPasswordHandle->size() != sizeof(gatekeeper::password_handle_t)) {
+                LOG(INFO) << "Password handle has wrong length";
+                return GK_ERROR;
             }
+            curPwdHandle.setToExternal(const_cast<uint8_t*>(currentPasswordHandle->data()),
+                                       currentPasswordHandle->size());
+            curPwd.setToExternal(const_cast<uint8_t*>(currentPassword->data()),
+                                 currentPassword->size());
+        }
 
-            android::hardware::hidl_vec<uint8_t> curPwdHandle;
-            curPwdHandle.setToExternal(const_cast<uint8_t*>(current_password_handle),
-                                       current_password_handle_length);
-            android::hardware::hidl_vec<uint8_t> curPwd;
-            curPwd.setToExternal(const_cast<uint8_t*>(current_password),
-                                 current_password_length);
-            android::hardware::hidl_vec<uint8_t> newPwd;
-            newPwd.setToExternal(const_cast<uint8_t*>(desired_password),
-                                 desired_password_length);
+        android::hardware::hidl_vec<uint8_t> newPwd;
+        newPwd.setToExternal(const_cast<uint8_t*>(desiredPassword.data()), desiredPassword.size());
 
-            uint32_t hw_uid = adjust_uid(uid);
-            Return<void> hwRes = hw_device->enroll(hw_uid, curPwdHandle, curPwd, newPwd,
-                              [&ret, enrolled_password_handle, enrolled_password_handle_length]
-                                   (const GatekeeperResponse &rsp) {
-                ret = static_cast<int>(rsp.code); // propagate errors
-                if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
-                    if (enrolled_password_handle != nullptr &&
-                        enrolled_password_handle_length != nullptr) {
-                        *enrolled_password_handle = new uint8_t[rsp.data.size()];
-                        *enrolled_password_handle_length = rsp.data.size();
-                        memcpy(*enrolled_password_handle, rsp.data.data(),
-                               *enrolled_password_handle_length);
+        uint32_t hw_uid = adjust_uid(uid);
+        Return<void> hwRes = hw_device->enroll(
+                hw_uid, curPwdHandle, curPwd, newPwd, [&gkResponse](const GatekeeperResponse& rsp) {
+                    if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
+                        *gkResponse = GKResponse::ok({rsp.data.begin(), rsp.data.end()});
+                    } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT &&
+                               rsp.timeout > 0) {
+                        *gkResponse = GKResponse::retry(rsp.timeout);
+                    } else {
+                        *gkResponse = GKResponse::error();
                     }
-                    ret = 0; // all success states are reported as 0
-                } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
-                    ret = rsp.timeout;
-                }
-            });
-            if (!hwRes.isOk()) {
-                ALOGE("enroll transaction failed\n");
-                ret = -1;
+                });
+        if (!hwRes.isOk()) {
+            LOG(ERROR) << "enroll transaction failed";
+            return GK_ERROR;
+        }
+
+        if (gkResponse->response_code() == GKResponseCode::OK && !gkResponse->should_reenroll()) {
+            if (gkResponse->payload().size() != sizeof(gatekeeper::password_handle_t)) {
+                LOG(ERROR) << "HAL returned password handle of invalid length "
+                           << gkResponse->payload().size();
+                return GK_ERROR;
             }
-        } else {
-            ret = soft_device->enroll(uid,
-                    current_password_handle, current_password_handle_length,
-                    current_password, current_password_length,
-                    desired_password, desired_password_length,
-                    enrolled_password_handle, enrolled_password_handle_length);
-        }
 
-        if (ret == GATEKEEPER_RESPONSE_OK && (*enrolled_password_handle == nullptr ||
-            *enrolled_password_handle_length != sizeof(password_handle_t))) {
-            ret = GATEKEEPER_RESPONSE_ERROR;
-            ALOGE("HAL: password_handle=%p size_of_handle=%" PRIu32 "\n",
-                  *enrolled_password_handle, *enrolled_password_handle_length);
-        }
-
-        if (ret == GATEKEEPER_RESPONSE_OK) {
-            gatekeeper::password_handle_t *handle =
-                    reinterpret_cast<gatekeeper::password_handle_t *>(*enrolled_password_handle);
+            const gatekeeper::password_handle_t* handle =
+                    reinterpret_cast<const gatekeeper::password_handle_t*>(
+                            gkResponse->payload().data());
             store_sid(uid, handle->user_id);
-            bool rr;
 
+            GKResponse verifyResponse;
             // immediately verify this password so we don't ask the user to enter it again
             // if they just created it.
-            verify(uid, *enrolled_password_handle, sizeof(password_handle_t), desired_password,
-                    desired_password_length, &rr);
+            auto status = verify(uid, gkResponse->payload(), desiredPassword, &verifyResponse);
+            if (!status.isOk() || verifyResponse.response_code() != GKResponseCode::OK) {
+                LOG(ERROR) << "Failed to verify password after enrolling";
+            }
         }
 
-        return ret;
+        return Status::ok();
     }
 
-    virtual int verify(uint32_t uid,
-            const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
-            const uint8_t *provided_password, uint32_t provided_password_length, bool *request_reenroll) {
-        uint8_t *auth_token = nullptr;
-        uint32_t auth_token_length;
-        int ret = verifyChallenge(uid, 0, enrolled_password_handle, enrolled_password_handle_length,
-                provided_password, provided_password_length,
-                &auth_token, &auth_token_length, request_reenroll);
-        delete [] auth_token;
-        return ret;
+    Status verify(int32_t uid, const ::std::vector<uint8_t>& enrolledPasswordHandle,
+                  const ::std::vector<uint8_t>& providedPassword, GKResponse* gkResponse) override {
+        return verifyChallenge(uid, 0 /* challenge */, enrolledPasswordHandle, providedPassword,
+                               gkResponse);
     }
 
-    virtual int verifyChallenge(uint32_t uid, uint64_t challenge,
-            const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
-            const uint8_t *provided_password, uint32_t provided_password_length,
-            uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll) {
+    Status verifyChallenge(int32_t uid, int64_t challenge,
+                           const std::vector<uint8_t>& enrolledPasswordHandle,
+                           const std::vector<uint8_t>& providedPassword,
+                           GKResponse* gkResponse) override {
         IPCThreadState* ipc = IPCThreadState::self();
         const int calling_pid = ipc->getCallingPid();
         const int calling_uid = ipc->getCallingUid();
         if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
-            return PERMISSION_DENIED;
+            return GK_ERROR;
         }
 
         // can't verify if we're missing either param
-        if ((enrolled_password_handle_length | provided_password_length) == 0)
-            return -EINVAL;
+        if (enrolledPasswordHandle.size() == 0 || providedPassword.size() == 0) return GK_ERROR;
 
-        int ret;
-        if (hw_device != nullptr) {
-            const gatekeeper::password_handle_t *handle =
-                    reinterpret_cast<const gatekeeper::password_handle_t *>(enrolled_password_handle);
-            // handle version 0 does not have hardware backed flag, and thus cannot be upgraded to
-            // a HAL if there was none before
-            if (handle->version == 0 || handle->hardware_backed) {
-                uint32_t hw_uid = adjust_uid(uid);
-                android::hardware::hidl_vec<uint8_t> curPwdHandle;
-                curPwdHandle.setToExternal(const_cast<uint8_t*>(enrolled_password_handle),
-                                           enrolled_password_handle_length);
-                android::hardware::hidl_vec<uint8_t> enteredPwd;
-                enteredPwd.setToExternal(const_cast<uint8_t*>(provided_password),
-                                         provided_password_length);
-                Return<void> hwRes = hw_device->verify(hw_uid, challenge, curPwdHandle, enteredPwd,
-                                        [&ret, request_reenroll, auth_token, auth_token_length]
-                                             (const GatekeeperResponse &rsp) {
-                    ret = static_cast<int>(rsp.code); // propagate errors
-                    if (auth_token != nullptr && auth_token_length != nullptr &&
-                        rsp.code >= GatekeeperStatusCode::STATUS_OK) {
-                        *auth_token = new uint8_t[rsp.data.size()];
-                        *auth_token_length = rsp.data.size();
-                        memcpy(*auth_token, rsp.data.data(), *auth_token_length);
-                        if (request_reenroll != nullptr) {
-                            *request_reenroll = (rsp.code == GatekeeperStatusCode::STATUS_REENROLL);
-                        }
-                        ret = 0; // all success states are reported as 0
-                    } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT &&
-                               rsp.timeout > 0) {
-                        ret = rsp.timeout;
+        if (!hw_device) return GK_ERROR;
+
+        if (enrolledPasswordHandle.size() != sizeof(gatekeeper::password_handle_t)) {
+            LOG(INFO) << "Password handle has wrong length";
+            return GK_ERROR;
+        }
+        const gatekeeper::password_handle_t* handle =
+                reinterpret_cast<const gatekeeper::password_handle_t*>(
+                        enrolledPasswordHandle.data());
+
+        uint32_t hw_uid = adjust_uid(uid);
+        android::hardware::hidl_vec<uint8_t> curPwdHandle;
+        curPwdHandle.setToExternal(const_cast<uint8_t*>(enrolledPasswordHandle.data()),
+                                   enrolledPasswordHandle.size());
+        android::hardware::hidl_vec<uint8_t> enteredPwd;
+        enteredPwd.setToExternal(const_cast<uint8_t*>(providedPassword.data()),
+                                 providedPassword.size());
+
+        Return<void> hwRes = hw_device->verify(
+                hw_uid, challenge, curPwdHandle, enteredPwd,
+                [&gkResponse](const GatekeeperResponse& rsp) {
+                    if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
+                        *gkResponse = GKResponse::ok(
+                                {rsp.data.begin(), rsp.data.end()},
+                                rsp.code == GatekeeperStatusCode::STATUS_REENROLL /* reenroll */);
+                    } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT) {
+                        *gkResponse = GKResponse::retry(rsp.timeout);
+                    } else {
+                        *gkResponse = GKResponse::error();
                     }
                 });
-                if (!hwRes.isOk()) {
-                    ALOGE("verify transaction failed\n");
-                    ret = -1;
-                }
-            } else {
-                // upgrade scenario, a HAL has been added to this device where there was none before
-                SoftGateKeeperDevice soft_dev;
-                ret = soft_dev.verify(uid, challenge,
-                    enrolled_password_handle, enrolled_password_handle_length,
-                    provided_password, provided_password_length, auth_token, auth_token_length,
-                    request_reenroll);
 
-                if (ret == 0) {
-                    // success! re-enroll with HAL
-                    *request_reenroll = true;
+        if (!hwRes.isOk()) {
+            LOG(ERROR) << "verify transaction failed";
+            return GK_ERROR;
+        }
+
+        if (gkResponse->response_code() == GKResponseCode::OK) {
+            if (gkResponse->payload().size() != 0) {
+                sp<IServiceManager> sm = defaultServiceManager();
+                sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
+                sp<security::keystore::IKeystoreService> service =
+                        interface_cast<security::keystore::IKeystoreService>(binder);
+
+                if (service) {
+                    int result = 0;
+                    auto binder_result = service->addAuthToken(gkResponse->payload(), &result);
+                    if (!binder_result.isOk() ||
+                        !keystore::KeyStoreServiceReturnCode(result).isOk()) {
+                        LOG(ERROR) << "Failure sending auth token to KeyStore: " << result;
+                    }
+                } else {
+                    LOG(ERROR) << "Cannot deliver auth token. Unable to communicate with Keystore.";
                 }
             }
-        } else {
-            ret = soft_device->verify(uid, challenge,
-                enrolled_password_handle, enrolled_password_handle_length,
-                provided_password, provided_password_length, auth_token, auth_token_length,
-                request_reenroll);
+
+            maybe_store_sid(uid, handle->user_id);
         }
 
-        if (ret == 0 && *auth_token != NULL && *auth_token_length > 0) {
-            // TODO: cache service?
-            sp<IServiceManager> sm = defaultServiceManager();
-            sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
-            sp<security::keystore::IKeystoreService> service =
-                    interface_cast<security::keystore::IKeystoreService>(binder);
-            if (service != NULL) {
-                std::vector<uint8_t> auth_token_vector(*auth_token,
-                                                       (*auth_token) + *auth_token_length);
-                int result = 0;
-                auto binder_result = service->addAuthToken(auth_token_vector, &result);
-                if (!binder_result.isOk() || !keystore::KeyStoreServiceReturnCode(result).isOk()) {
-                    ALOGE("Failure sending auth token to KeyStore: %" PRId32, result);
-                }
-            } else {
-                ALOGE("Unable to communicate with KeyStore");
-            }
-        }
-
-        if (ret == 0) {
-            maybe_store_sid(uid, reinterpret_cast<const gatekeeper::password_handle_t *>(
-                        enrolled_password_handle)->user_id);
-        }
-
-        return ret;
+        return Status::ok();
     }
 
-    virtual uint64_t getSecureUserId(uint32_t uid) { return read_sid(uid); }
+    Status getSecureUserId(int32_t uid, int64_t* sid) override {
+        *sid = read_sid(uid);
+        return Status::ok();
+    }
 
-    virtual void clearSecureUserId(uint32_t uid) {
+    Status clearSecureUserId(int32_t uid) override {
         IPCThreadState* ipc = IPCThreadState::self();
         const int calling_pid = ipc->getCallingPid();
         const int calling_uid = ipc->getCallingUid();
         if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
             ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
-            return;
+            return Status::ok();
         }
         clear_sid(uid);
 
-        if (hw_device != nullptr) {
+        if (hw_device) {
             uint32_t hw_uid = adjust_uid(uid);
             hw_device->deleteUser(hw_uid, [] (const GatekeeperResponse &){});
         }
+        return Status::ok();
     }
 
-    virtual void reportDeviceSetupComplete() {
+    Status reportDeviceSetupComplete() override {
         IPCThreadState* ipc = IPCThreadState::self();
         const int calling_pid = ipc->getCallingPid();
         const int calling_uid = ipc->getCallingUid();
         if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
             ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
-            return;
+            return Status::ok();
         }
 
         clear_state_if_needed();
+        return Status::ok();
     }
 
-    virtual status_t dump(int fd, const Vector<String16> &) {
+    status_t dump(int fd, const Vector<String16>&) override {
         IPCThreadState* ipc = IPCThreadState::self();
         const int pid = ipc->getCallingPid();
         const int uid = ipc->getCallingUid();
@@ -410,7 +377,6 @@
 
 private:
     sp<IGatekeeper> hw_device;
-    std::unique_ptr<SoftGateKeeperDevice> soft_device;
 
     bool clear_state_if_needed_done;
     bool is_running_gsi;
diff --git a/gatekeeperd/include/gatekeeper/GateKeeperResponse.h b/gatekeeperd/include/gatekeeper/GateKeeperResponse.h
new file mode 100644
index 0000000..99fff02
--- /dev/null
+++ b/gatekeeperd/include/gatekeeper/GateKeeperResponse.h
@@ -0,0 +1,85 @@
+/*
+**
+** Copyright 2019, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#ifndef GATEKEEPERD_INCLUDE_GATEKEEPER_GATEKEEPERRESPONSE_H_
+#define GATEKEEPERD_INCLUDE_GATEKEEPER_GATEKEEPERRESPONSE_H_
+
+#include <binder/Parcelable.h>
+
+namespace android {
+namespace service {
+namespace gatekeeper {
+
+enum class ResponseCode : int32_t {
+    ERROR = -1,
+    OK = 0,
+    RETRY = 1,
+};
+
+class GateKeeperResponse : public ::android::Parcelable {
+    GateKeeperResponse(ResponseCode response_code, int32_t timeout = 0,
+                       std::vector<uint8_t> payload = {}, bool should_reenroll = false)
+        : response_code_(response_code),
+          timeout_(timeout),
+          payload_(std::move(payload)),
+          should_reenroll_(should_reenroll) {}
+
+  public:
+    GateKeeperResponse() = default;
+    GateKeeperResponse(GateKeeperResponse&&) = default;
+    GateKeeperResponse(const GateKeeperResponse&) = default;
+    GateKeeperResponse& operator=(GateKeeperResponse&&) = default;
+
+    static GateKeeperResponse error() { return GateKeeperResponse(ResponseCode::ERROR); }
+    static GateKeeperResponse retry(int32_t timeout) {
+        return GateKeeperResponse(ResponseCode::RETRY, timeout);
+    }
+    static GateKeeperResponse ok(std::vector<uint8_t> payload, bool reenroll = false) {
+        return GateKeeperResponse(ResponseCode::OK, 0, std::move(payload), reenroll);
+    }
+
+    status_t readFromParcel(const Parcel* in) override;
+    status_t writeToParcel(Parcel* out) const override;
+
+    const std::vector<uint8_t>& payload() const { return payload_; }
+
+    void payload(std::vector<uint8_t> payload) { payload_ = payload; }
+
+    ResponseCode response_code() const { return response_code_; }
+
+    void response_code(ResponseCode response_code) { response_code_ = response_code; }
+
+    bool should_reenroll() const { return should_reenroll_; }
+
+    void should_reenroll(bool should_reenroll) { should_reenroll_ = should_reenroll; }
+
+    int32_t timeout() const { return timeout_; }
+
+    void timeout(int32_t timeout) { timeout_ = timeout; }
+
+  private:
+    ResponseCode response_code_;
+    int32_t timeout_;
+    std::vector<uint8_t> payload_;
+    bool should_reenroll_;
+};
+
+}  // namespace gatekeeper
+}  // namespace service
+}  // namespace android
+
+#endif  // GATEKEEPERD_INCLUDE_GATEKEEPER_GATEKEEPERRESPONSE_H_
diff --git a/gatekeeperd/tests/Android.bp b/gatekeeperd/tests/Android.bp
deleted file mode 100644
index d4cf93b..0000000
--- a/gatekeeperd/tests/Android.bp
+++ /dev/null
@@ -1,34 +0,0 @@
-//
-// Copyright (C) 2015 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-cc_test {
-    name: "gatekeeperd-unit-tests",
-
-    cflags: [
-        "-g",
-        "-Wall",
-        "-Werror",
-        "-Wno-missing-field-initializers",
-    ],
-    shared_libs: [
-        "libgatekeeper",
-        "libcrypto",
-        "libbase",
-    ],
-    static_libs: ["libscrypt_static"],
-    include_dirs: ["external/scrypt/lib/crypto"],
-    srcs: ["gatekeeper_test.cpp"],
-}
diff --git a/gatekeeperd/tests/gatekeeper_test.cpp b/gatekeeperd/tests/gatekeeper_test.cpp
deleted file mode 100644
index 100375f..0000000
--- a/gatekeeperd/tests/gatekeeper_test.cpp
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <arpa/inet.h>
-#include <iostream>
-
-#include <gtest/gtest.h>
-#include <hardware/hw_auth_token.h>
-
-#include "../SoftGateKeeper.h"
-
-using ::gatekeeper::SizedBuffer;
-using ::testing::Test;
-using ::gatekeeper::EnrollRequest;
-using ::gatekeeper::EnrollResponse;
-using ::gatekeeper::VerifyRequest;
-using ::gatekeeper::VerifyResponse;
-using ::gatekeeper::SoftGateKeeper;
-using ::gatekeeper::secure_id_t;
-
-static void do_enroll(SoftGateKeeper &gatekeeper, EnrollResponse *response) {
-    SizedBuffer password;
-
-    password.buffer.reset(new uint8_t[16]);
-    password.length = 16;
-    memset(password.buffer.get(), 0, 16);
-    EnrollRequest request(0, NULL, &password, NULL);
-
-    gatekeeper.Enroll(request, response);
-}
-
-TEST(GateKeeperTest, EnrollSuccess) {
-    SoftGateKeeper gatekeeper;
-    EnrollResponse response;
-    do_enroll(gatekeeper, &response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
-}
-
-TEST(GateKeeperTest, EnrollBogusData) {
-    SoftGateKeeper gatekeeper;
-    SizedBuffer password;
-    EnrollResponse response;
-
-    EnrollRequest request(0, NULL, &password, NULL);
-
-    gatekeeper.Enroll(request, &response);
-
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_INVALID, response.error);
-}
-
-TEST(GateKeeperTest, VerifySuccess) {
-    SoftGateKeeper gatekeeper;
-    SizedBuffer provided_password;
-    EnrollResponse enroll_response;
-
-    provided_password.buffer.reset(new uint8_t[16]);
-    provided_password.length = 16;
-    memset(provided_password.buffer.get(), 0, 16);
-
-    do_enroll(gatekeeper, &enroll_response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
-    VerifyRequest request(0, 1, &enroll_response.enrolled_password_handle,
-            &provided_password);
-    VerifyResponse response;
-
-    gatekeeper.Verify(request, &response);
-
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
-
-    hw_auth_token_t *auth_token =
-        reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get());
-
-    ASSERT_EQ((uint32_t) HW_AUTH_PASSWORD, ntohl(auth_token->authenticator_type));
-    ASSERT_EQ((uint64_t) 1, auth_token->challenge);
-    ASSERT_NE(~((uint32_t) 0), auth_token->timestamp);
-    ASSERT_NE((uint64_t) 0, auth_token->user_id);
-    ASSERT_NE((uint64_t) 0, auth_token->authenticator_id);
-}
-
-TEST(GateKeeperTest, TrustedReEnroll) {
-    SoftGateKeeper gatekeeper;
-    SizedBuffer provided_password;
-    EnrollResponse enroll_response;
-    SizedBuffer password_handle;
-
-    // do_enroll enrolls an all 0 password
-    provided_password.buffer.reset(new uint8_t[16]);
-    provided_password.length = 16;
-    memset(provided_password.buffer.get(), 0, 16);
-    do_enroll(gatekeeper, &enroll_response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
-
-    // keep a copy of the handle
-    password_handle.buffer.reset(new uint8_t[enroll_response.enrolled_password_handle.length]);
-    password_handle.length = enroll_response.enrolled_password_handle.length;
-    memcpy(password_handle.buffer.get(), enroll_response.enrolled_password_handle.buffer.get(),
-            password_handle.length);
-
-    // verify first password
-    VerifyRequest request(0, 0, &enroll_response.enrolled_password_handle,
-            &provided_password);
-    VerifyResponse response;
-    gatekeeper.Verify(request, &response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
-    hw_auth_token_t *auth_token =
-        reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get());
-
-    secure_id_t secure_id = auth_token->user_id;
-
-    // enroll new password
-    provided_password.buffer.reset(new uint8_t[16]);
-    provided_password.length = 16;
-    memset(provided_password.buffer.get(), 0, 16);
-    SizedBuffer password;
-    password.buffer.reset(new uint8_t[16]);
-    memset(password.buffer.get(), 1, 16);
-    password.length = 16;
-    EnrollRequest enroll_request(0, &password_handle, &password, &provided_password);
-    gatekeeper.Enroll(enroll_request, &enroll_response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
-
-    // verify new password
-    password.buffer.reset(new uint8_t[16]);
-    memset(password.buffer.get(), 1, 16);
-    password.length = 16;
-    VerifyRequest new_request(0, 0, &enroll_response.enrolled_password_handle,
-            &password);
-    gatekeeper.Verify(new_request, &response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
-    ASSERT_EQ(secure_id,
-        reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get())->user_id);
-}
-
-
-TEST(GateKeeperTest, UntrustedReEnroll) {
-    SoftGateKeeper gatekeeper;
-    SizedBuffer provided_password;
-    EnrollResponse enroll_response;
-
-    // do_enroll enrolls an all 0 password
-    provided_password.buffer.reset(new uint8_t[16]);
-    provided_password.length = 16;
-    memset(provided_password.buffer.get(), 0, 16);
-    do_enroll(gatekeeper, &enroll_response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
-
-    // verify first password
-    VerifyRequest request(0, 0, &enroll_response.enrolled_password_handle,
-            &provided_password);
-    VerifyResponse response;
-    gatekeeper.Verify(request, &response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
-    hw_auth_token_t *auth_token =
-        reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get());
-
-    secure_id_t secure_id = auth_token->user_id;
-
-    // enroll new password
-    SizedBuffer password;
-    password.buffer.reset(new uint8_t[16]);
-    memset(password.buffer.get(), 1, 16);
-    password.length = 16;
-    EnrollRequest enroll_request(0, NULL, &password, NULL);
-    gatekeeper.Enroll(enroll_request, &enroll_response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
-
-    // verify new password
-    password.buffer.reset(new uint8_t[16]);
-    memset(password.buffer.get(), 1, 16);
-    password.length = 16;
-    VerifyRequest new_request(0, 0, &enroll_response.enrolled_password_handle,
-            &password);
-    gatekeeper.Verify(new_request, &response);
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
-    ASSERT_NE(secure_id,
-        reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get())->user_id);
-}
-
-
-TEST(GateKeeperTest, VerifyBogusData) {
-    SoftGateKeeper gatekeeper;
-    SizedBuffer provided_password;
-    SizedBuffer password_handle;
-    VerifyResponse response;
-
-    VerifyRequest request(0, 0, &provided_password, &password_handle);
-
-    gatekeeper.Verify(request, &response);
-
-    ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_INVALID, response.error);
-}
diff --git a/init/host_init_verifier.cpp b/init/host_init_verifier.cpp
index 1b4716f..8aa3509 100644
--- a/init/host_init_verifier.cpp
+++ b/init/host_init_verifier.cpp
@@ -15,11 +15,13 @@
 //
 
 #include <errno.h>
+#include <getopt.h>
 #include <pwd.h>
 #include <stdio.h>
 #include <stdlib.h>
 
 #include <iostream>
+#include <iterator>
 #include <string>
 #include <vector>
 
@@ -48,9 +50,9 @@
 using android::base::ReadFileToString;
 using android::base::Split;
 
-static std::string passwd_file;
+static std::vector<std::string> passwd_files;
 
-static std::vector<std::pair<std::string, int>> GetVendorPasswd() {
+static std::vector<std::pair<std::string, int>> GetVendorPasswd(const std::string& passwd_file) {
     std::string passwd;
     if (!ReadFileToString(passwd_file, &passwd)) {
         return {};
@@ -72,6 +74,16 @@
     return result;
 }
 
+static std::vector<std::pair<std::string, int>> GetVendorPasswd() {
+    std::vector<std::pair<std::string, int>> result;
+    for (const auto& passwd_file : passwd_files) {
+        auto individual_result = GetVendorPasswd(passwd_file);
+        std::move(individual_result.begin(), individual_result.end(),
+                  std::back_insert_iterator(result));
+    }
+    return result;
+}
+
 passwd* getpwnam(const char* login) {  // NOLINT: implementing bad function.
     // This isn't thread safe, but that's okay for our purposes.
     static char static_name[32] = "";
@@ -117,6 +129,23 @@
     return nullptr;
 }
 
+static std::optional<std::set<std::string>> ReadKnownInterfaces(
+        const std::string& known_interfaces_file) {
+    if (known_interfaces_file.empty()) {
+        LOG(WARNING) << "Missing a known interfaces file.";
+        return {};
+    }
+
+    std::string known_interfaces;
+    if (!ReadFileToString(known_interfaces_file, &known_interfaces)) {
+        LOG(ERROR) << "Failed to read known interfaces file '" << known_interfaces_file << "'";
+        return {};
+    }
+
+    auto interfaces = Split(known_interfaces, " ");
+    return std::set<std::string>(interfaces.begin(), interfaces.end());
+}
+
 namespace android {
 namespace init {
 
@@ -126,17 +155,56 @@
 
 #include "generated_stub_builtin_function_map.h"
 
+void PrintUsage() {
+    std::cout << "usage: host_init_verifier [-p FILE] -k FILE <init rc file>\n"
+                 "\n"
+                 "Tests an init script for correctness\n"
+                 "\n"
+                 "-p FILE\tSearch this passwd file for users and groups\n"
+                 "-k FILE\tUse this file as a space-separated list of known interfaces\n"
+              << std::endl;
+}
+
 int main(int argc, char** argv) {
     android::base::InitLogging(argv, &android::base::StdioLogger);
     android::base::SetMinimumLogSeverity(android::base::ERROR);
 
-    if (argc != 2 && argc != 3) {
-        LOG(ERROR) << "Usage: " << argv[0] << " <init rc file> [passwd file]";
-        return EXIT_FAILURE;
+    std::string known_interfaces_file;
+
+    while (true) {
+        static const struct option long_options[] = {
+                {"help", no_argument, nullptr, 'h'},
+                {nullptr, 0, nullptr, 0},
+        };
+
+        int arg = getopt_long(argc, argv, "p:k:", long_options, nullptr);
+
+        if (arg == -1) {
+            break;
+        }
+
+        switch (arg) {
+            case 'h':
+                PrintUsage();
+                return EXIT_FAILURE;
+            case 'p':
+                passwd_files.emplace_back(optarg);
+                break;
+            case 'k':
+                known_interfaces_file = optarg;
+                break;
+            default:
+                std::cerr << "getprop: getopt returned invalid result: " << arg << std::endl;
+                return EXIT_FAILURE;
+        }
     }
 
-    if (argc == 3) {
-        passwd_file = argv[2];
+    argc -= optind;
+    argv += optind;
+
+    if (argc != 1) {
+        PrintUsage();
+        return EXIT_FAILURE;
     }
 
     const BuiltinFunctionMap function_map;
@@ -144,16 +212,18 @@
     ActionManager& am = ActionManager::GetInstance();
     ServiceList& sl = ServiceList::GetInstance();
     Parser parser;
-    parser.AddSectionParser("service", std::make_unique<ServiceParser>(&sl, nullptr));
+    parser.AddSectionParser(
+            "service", std::make_unique<ServiceParser>(&sl, nullptr,
+                                                       ReadKnownInterfaces(known_interfaces_file)));
     parser.AddSectionParser("on", std::make_unique<ActionParser>(&am, nullptr));
     parser.AddSectionParser("import", std::make_unique<HostImportParser>());
 
-    if (!parser.ParseConfigFileInsecure(argv[1])) {
-        LOG(ERROR) << "Failed to open init rc script '" << argv[1] << "'";
+    if (!parser.ParseConfigFileInsecure(*argv)) {
+        LOG(ERROR) << "Failed to open init rc script '" << *argv << "'";
         return EXIT_FAILURE;
     }
     if (parser.parse_error_count() > 0) {
-        LOG(ERROR) << "Failed to parse init script '" << argv[1] << "' with "
+        LOG(ERROR) << "Failed to parse init script '" << *argv << "' with "
                    << parser.parse_error_count() << " errors";
         return EXIT_FAILURE;
     }
diff --git a/init/init.cpp b/init/init.cpp
index b6911e5..675f3e5 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -113,7 +113,8 @@
 Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
     Parser parser;
 
-    parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, subcontexts));
+    parser.AddSectionParser(
+            "service", std::make_unique<ServiceParser>(&service_list, subcontexts, std::nullopt));
     parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, subcontexts));
     parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
 
@@ -124,7 +125,8 @@
 Parser CreateServiceOnlyParser(ServiceList& service_list) {
     Parser parser;
 
-    parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, subcontexts));
+    parser.AddSectionParser(
+            "service", std::make_unique<ServiceParser>(&service_list, subcontexts, std::nullopt));
     return parser;
 }
 
diff --git a/init/init_test.cpp b/init/init_test.cpp
index 1bcc5ef..a09db18 100644
--- a/init/init_test.cpp
+++ b/init/init_test.cpp
@@ -44,7 +44,8 @@
     Action::set_function_map(&test_function_map);
 
     Parser parser;
-    parser.AddSectionParser("service", std::make_unique<ServiceParser>(service_list, nullptr));
+    parser.AddSectionParser("service",
+                            std::make_unique<ServiceParser>(service_list, nullptr, std::nullopt));
     parser.AddSectionParser("on", std::make_unique<ActionParser>(&am, nullptr));
     parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
 
diff --git a/init/service_parser.cpp b/init/service_parser.cpp
index 33ed050..ba35104 100644
--- a/init/service_parser.cpp
+++ b/init/service_parser.cpp
@@ -152,6 +152,12 @@
         return Error() << "Interface name must not be a value name '" << interface_name << "'";
     }
 
+    if (known_interfaces_ && known_interfaces_->count(interface_name) == 0) {
+        return Error() << "Interface is not in the known set of hidl_interfaces: '"
+                       << interface_name << "'. Please ensure the interface is built "
+                       << "by a hidl_interface target.";
+    }
+
     const std::string fullname = interface_name + "/" + instance_name;
 
     for (const auto& svc : *service_list_) {
diff --git a/init/service_parser.h b/init/service_parser.h
index 0a5b291..5a16768 100644
--- a/init/service_parser.h
+++ b/init/service_parser.h
@@ -28,8 +28,12 @@
 
 class ServiceParser : public SectionParser {
   public:
-    ServiceParser(ServiceList* service_list, std::vector<Subcontext>* subcontexts)
-        : service_list_(service_list), subcontexts_(subcontexts), service_(nullptr) {}
+    ServiceParser(ServiceList* service_list, std::vector<Subcontext>* subcontexts,
+                  const std::optional<std::set<std::string>>& known_interfaces)
+        : service_list_(service_list),
+          subcontexts_(subcontexts),
+          known_interfaces_(known_interfaces),
+          service_(nullptr) {}
     Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
                               int line) override;
     Result<void> ParseLineSection(std::vector<std::string>&& args, int line) override;
@@ -81,6 +85,7 @@
 
     ServiceList* service_list_;
     std::vector<Subcontext>* subcontexts_;
+    std::optional<std::set<std::string>> known_interfaces_;
     std::unique_ptr<Service> service_;
     std::string filename_;
 };
diff --git a/libmeminfo/libdmabufinfo/include/dmabufinfo/dmabufinfo.h b/libmeminfo/libdmabufinfo/include/dmabufinfo/dmabufinfo.h
index a16c3fd..a6e7f69 100644
--- a/libmeminfo/libdmabufinfo/include/dmabufinfo/dmabufinfo.h
+++ b/libmeminfo/libdmabufinfo/include/dmabufinfo/dmabufinfo.h
@@ -19,6 +19,7 @@
 #include <sys/types.h>
 #include <unistd.h>
 
+#include <set>
 #include <string>
 #include <vector>
 #include <unordered_map>
@@ -33,6 +34,7 @@
         : inode_(inode), size_(size), count_(count), exporter_(exporter), name_(name) {
         total_refs_ = 0;
     }
+    DmaBuffer() = default;
     ~DmaBuffer() = default;
 
     // Adds one file descriptor reference for the given pid
@@ -54,11 +56,13 @@
     ino_t inode() const { return inode_; }
     uint64_t total_refs() const { return total_refs_; }
     uint64_t count() const { return count_; };
+    const std::set<pid_t>& pids() const { return pids_; }
     const std::string& name() const { return name_; }
     const std::string& exporter() const { return exporter_; }
     void SetName(const std::string& name) { name_ = name; }
     void SetExporter(const std::string& exporter) { exporter_ = exporter; }
     void SetCount(uint64_t count) { count_ = count; }
+    uint64_t Pss() const { return size_ / pids_.size(); }
 
     bool operator==(const DmaBuffer& rhs) {
         return (inode_ == rhs.inode()) && (size_ == rhs.size()) && (name_ == rhs.name()) &&
@@ -70,6 +74,7 @@
     uint64_t size_;
     uint64_t count_;
     uint64_t total_refs_;
+    std::set<pid_t> pids_;
     std::string exporter_;
     std::string name_;
     std::unordered_map<pid_t, int> fdrefs_;
@@ -80,6 +85,7 @@
         auto [it, inserted] = map->insert(std::make_pair(pid, 1));
         if (!inserted)
             it->second++;
+        pids_.insert(pid);
     }
 };
 
diff --git a/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp b/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp
index 9a80c82..48901b1 100644
--- a/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp
+++ b/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp
@@ -16,6 +16,7 @@
 
 #include <dirent.h>
 #include <errno.h>
+#include <getopt.h>
 #include <inttypes.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -36,9 +37,10 @@
 
 [[noreturn]] static void usage(int exit_status) {
     fprintf(stderr,
-            "Usage: %s [PID] \n"
-            "\t If PID is supplied, the dmabuf information for this process is shown.\n"
-            "\t Otherwise, shows the information for all processes.\n",
+            "Usage: %s [-ah] [PID] \n"
+            "-a\t show all dma buffers (ion) in big table, [buffer x process] grid \n"
+            "-h\t show this help\n"
+            "  \t If PID is supplied, the dmabuf information for that process is shown.\n",
             getprogname());
 
     exit(exit_status);
@@ -54,11 +56,7 @@
     return line;
 }
 
-static void AddPidsToSet(const std::unordered_map<pid_t, int>& map, std::set<pid_t>* set) {
-    for (auto it = map.begin(); it != map.end(); ++it) set->insert(it->first);
-}
-
-static void PrintDmaBufInfo(const std::vector<DmaBuffer>& bufs) {
+static void PrintDmaBufTable(const std::vector<DmaBuffer>& bufs) {
     if (bufs.empty()) {
         printf("dmabuf info not found ¯\\_(ツ)_/¯\n");
         return;
@@ -66,9 +64,8 @@
 
     // Find all unique pids in the input vector, create a set
     std::set<pid_t> pid_set;
-    for (int i = 0; i < bufs.size(); i++) {
-        AddPidsToSet(bufs[i].fdrefs(), &pid_set);
-        AddPidsToSet(bufs[i].maprefs(), &pid_set);
+    for (auto& buf : bufs) {
+        pid_set.insert(buf.pids().begin(), buf.pids().end());
     }
 
     // Format the header string spaced and separated with '|'
@@ -126,50 +123,144 @@
     return;
 }
 
-int main(int argc, char* argv[]) {
-    pid_t pid = -1;
-    std::vector<DmaBuffer> bufs;
-    bool show_all = true;
+static void PrintDmaBufPerProcess(const std::vector<DmaBuffer>& bufs) {
+    if (bufs.empty()) {
+        printf("dmabuf info not found ¯\\_(ツ)_/¯\n");
+        return;
+    }
 
-    if (argc > 1) {
-        if (sscanf(argv[1], "%d", &pid) == 1) {
-            show_all = false;
-        } else {
+    // Create a reverse map from pid to dmabufs
+    std::unordered_map<pid_t, std::set<ino_t>> pid_to_inodes = {};
+    uint64_t total_size = 0;  // Total size of dmabufs in the system
+    uint64_t kernel_rss = 0;  // Total size of dmabufs NOT mapped or opened by a process
+    for (auto& buf : bufs) {
+        for (auto pid : buf.pids()) {
+            pid_to_inodes[pid].insert(buf.inode());
+        }
+        total_size += buf.size();
+        if (buf.fdrefs().empty() && buf.maprefs().empty()) {
+            kernel_rss += buf.size();
+        }
+    }
+    // Create an inode to dmabuf map. We know inodes are unique..
+    std::unordered_map<ino_t, DmaBuffer> inode_to_dmabuf;
+    for (auto buf : bufs) {
+        inode_to_dmabuf[buf.inode()] = buf;
+    }
+
+    uint64_t total_rss = 0, total_pss = 0;
+    for (auto& [pid, inodes] : pid_to_inodes) {
+        uint64_t pss = 0;
+        uint64_t rss = 0;
+
+        printf("%16s:%-5d\n", GetProcessComm(pid).c_str(), pid);
+        printf("%22s %16s %16s %16s %16s\n", "Name", "Rss", "Pss", "nr_procs", "Inode");
+        for (auto& inode : inodes) {
+            DmaBuffer& buf = inode_to_dmabuf[inode];
+            printf("%22s %13" PRIu64 " kB %13" PRIu64 " kB %16zu %16" PRIuMAX "\n",
+                   buf.name().empty() ? "<unknown>" : buf.name().c_str(), buf.size() / 1024,
+                   buf.Pss() / 1024, buf.pids().size(), static_cast<uintmax_t>(buf.inode()));
+            rss += buf.size();
+            pss += buf.Pss();
+        }
+        printf("%22s %13" PRIu64 " kB %13" PRIu64 " kB %16s\n", "PROCESS TOTAL", rss / 1024,
+               pss / 1024, "");
+        printf("----------------------\n");
+        total_rss += rss;
+        total_pss += pss;
+    }
+    printf("dmabuf total: %" PRIu64 " kB kernel_rss: %" PRIu64 " kB userspace_rss: %" PRIu64
+           " kB userspace_pss: %" PRIu64 " kB\n ",
+           total_size / 1024, kernel_rss / 1024, total_rss / 1024, total_pss / 1024);
+}
+
+static bool ReadDmaBufs(std::vector<DmaBuffer>* bufs) {
+    bufs->clear();
+
+    if (!ReadDmaBufInfo(bufs)) {
+        fprintf(stderr, "debugfs entry for dmabuf not available, skipping\n");
+        return false;
+    }
+
+    std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir("/proc"), closedir);
+    if (!dir) {
+        fprintf(stderr, "Failed to open /proc directory\n");
+        bufs->clear();
+        return false;
+    }
+
+    struct dirent* dent;
+    while ((dent = readdir(dir.get()))) {
+        if (dent->d_type != DT_DIR) continue;
+
+        int pid = atoi(dent->d_name);
+        if (pid == 0) {
+            continue;
+        }
+
+        if (!AppendDmaBufInfo(pid, bufs)) {
+            fprintf(stderr, "Unable to read dmabuf info for pid %d\n", pid);
+            bufs->clear();
+            return false;
+        }
+    }
+
+    return true;
+}
+
+int main(int argc, char* argv[]) {
+    struct option longopts[] = {{"all", no_argument, nullptr, 'a'},
+                                {"help", no_argument, nullptr, 'h'},
+                                {0, 0, nullptr, 0}};
+
+    int opt;
+    bool show_table = false;
+    while ((opt = getopt_long(argc, argv, "ah", longopts, nullptr)) != -1) {
+        switch (opt) {
+            case 'a':
+                show_table = true;
+                break;
+            case 'h':
+                usage(EXIT_SUCCESS);
+            default:
+                usage(EXIT_FAILURE);
+        }
+    }
+
+    pid_t pid = -1;
+    if (optind < argc) {
+        if (show_table) {
+            fprintf(stderr, "Invalid arguments: -a does not need arguments\n");
+            usage(EXIT_FAILURE);
+        }
+        if (optind != (argc - 1)) {
+            fprintf(stderr, "Invalid arguments - only one [PID] argument is allowed\n");
+            usage(EXIT_FAILURE);
+        }
+        pid = atoi(argv[optind]);
+        if (pid == 0) {
+            fprintf(stderr, "Invalid process id %s\n", argv[optind]);
             usage(EXIT_FAILURE);
         }
     }
 
-    if (show_all) {
-        if (!ReadDmaBufInfo(&bufs)) {
-            std::cerr << "debugfs entry for dmabuf not available, skipping" << std::endl;
-            bufs.clear();
-        }
-        std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir("/proc"), closedir);
-        if (!dir) {
-            std::cerr << "Failed to open /proc directory" << std::endl;
+    std::vector<DmaBuffer> bufs;
+    if (pid != -1) {
+        if (!ReadDmaBufInfo(pid, &bufs)) {
+            fprintf(stderr, "Unable to read dmabuf info for %d\n", pid);
             exit(EXIT_FAILURE);
         }
-        struct dirent* dent;
-        while ((dent = readdir(dir.get()))) {
-            if (dent->d_type != DT_DIR) continue;
-
-            int matched = sscanf(dent->d_name, "%d", &pid);
-            if (matched != 1) {
-                continue;
-            }
-
-            if (!AppendDmaBufInfo(pid, &bufs)) {
-                std::cerr << "Unable to read dmabuf info for pid " << pid << std::endl;
-                exit(EXIT_FAILURE);
-            }
-        }
     } else {
-        if (!ReadDmaBufInfo(pid, &bufs)) {
-            std::cerr << "Unable to read dmabuf info" << std::endl;
-            exit(EXIT_FAILURE);
-        }
+        if (!ReadDmaBufs(&bufs)) exit(EXIT_FAILURE);
     }
 
-    PrintDmaBufInfo(bufs);
+    // Show the old dmabuf table, inode x process
+    if (show_table) {
+        PrintDmaBufTable(bufs);
+        return 0;
+    }
+
+    PrintDmaBufPerProcess(bufs);
+
     return 0;
 }
diff --git a/logd/Android.bp b/logd/Android.bp
index 9b86258..b337b7c 100644
--- a/logd/Android.bp
+++ b/logd/Android.bp
@@ -39,7 +39,6 @@
         "FlushCommand.cpp",
         "LogBuffer.cpp",
         "LogBufferElement.cpp",
-        "LogBufferInterface.cpp",
         "LogTimes.cpp",
         "LogStatistics.cpp",
         "LogWhiteBlackList.cpp",
diff --git a/logd/LogBuffer.h b/logd/LogBuffer.h
index 774d4ab..c2d5b97 100644
--- a/logd/LogBuffer.h
+++ b/logd/LogBuffer.h
@@ -27,7 +27,6 @@
 #include <sysutils/SocketClient.h>
 
 #include "LogBufferElement.h"
-#include "LogBufferInterface.h"
 #include "LogStatistics.h"
 #include "LogTags.h"
 #include "LogTimes.h"
@@ -75,7 +74,7 @@
 
 typedef std::list<LogBufferElement*> LogBufferElementCollection;
 
-class LogBuffer : public LogBufferInterface {
+class LogBuffer {
     LogBufferElementCollection mLogElements;
     pthread_rwlock_t mLogElementsLock;
 
@@ -108,14 +107,14 @@
     LastLogTimes& mTimes;
 
     explicit LogBuffer(LastLogTimes* times);
-    ~LogBuffer() override;
+    ~LogBuffer();
     void init();
     bool isMonotonic() {
         return monotonic;
     }
 
-    int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
-            const char* msg, uint16_t len) override;
+    int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid, const char* msg,
+            uint16_t len);
     // lastTid is an optional context to help detect if the last previous
     // valid message was from the same source so we can differentiate chatty
     // filter types (identical or expired)
@@ -159,12 +158,7 @@
     const char* pidToName(pid_t pid) {
         return stats.pidToName(pid);
     }
-    virtual uid_t pidToUid(pid_t pid) override {
-        return stats.pidToUid(pid);
-    }
-    virtual pid_t tidToPid(pid_t tid) override {
-        return stats.tidToPid(tid);
-    }
+    uid_t pidToUid(pid_t pid) { return stats.pidToUid(pid); }
     const char* uidToName(uid_t uid) {
         return stats.uidToName(uid);
     }
diff --git a/logd/LogBufferInterface.h b/logd/LogBufferInterface.h
deleted file mode 100644
index f31e244..0000000
--- a/logd/LogBufferInterface.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2012-2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _LOGD_LOG_BUFFER_INTERFACE_H__
-#define _LOGD_LOG_BUFFER_INTERFACE_H__
-
-#include <sys/types.h>
-
-#include <android-base/macros.h>
-#include <log/log_id.h>
-#include <log/log_time.h>
-
-// Abstract interface that handles log when log available.
-class LogBufferInterface {
-   public:
-    LogBufferInterface();
-    virtual ~LogBufferInterface();
-    // Handles a log entry when available in LogListener.
-    // Returns the size of the handled log message.
-    virtual int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid,
-                    pid_t tid, const char* msg, uint16_t len) = 0;
-
-    virtual uid_t pidToUid(pid_t pid);
-    virtual pid_t tidToPid(pid_t tid);
-
-   private:
-    DISALLOW_COPY_AND_ASSIGN(LogBufferInterface);
-};
-
-#endif  // _LOGD_LOG_BUFFER_INTERFACE_H__
diff --git a/logd/LogListener.cpp b/logd/LogListener.cpp
index 2f22778..443570f 100644
--- a/logd/LogListener.cpp
+++ b/logd/LogListener.cpp
@@ -14,9 +14,7 @@
  * limitations under the License.
  */
 
-#include <ctype.h>
 #include <limits.h>
-#include <stdio.h>
 #include <sys/cdefs.h>
 #include <sys/prctl.h>
 #include <sys/socket.h>
@@ -32,9 +30,8 @@
 #include "LogListener.h"
 #include "LogUtils.h"
 
-LogListener::LogListener(LogBufferInterface* buf, LogReader* reader)
-    : SocketListener(getLogSocket(), false), logbuf(buf), reader(reader) {
-}
+LogListener::LogListener(LogBuffer* buf, LogReader* reader)
+    : SocketListener(getLogSocket(), false), logbuf(buf), reader(reader) {}
 
 bool LogListener::onDataAvailable(SocketClient* cli) {
     static bool name_set;
@@ -78,11 +75,8 @@
         cmsg = CMSG_NXTHDR(&hdr, cmsg);
     }
 
-    struct ucred fake_cred;
     if (cred == nullptr) {
-        cred = &fake_cred;
-        cred->pid = 0;
-        cred->uid = DEFAULT_OVERFLOWUID;
+        return false;
     }
 
     if (cred->uid == AID_LOGD) {
@@ -106,40 +100,16 @@
         return false;
     }
 
-    // Check credential validity, acquire corrected details if not supplied.
-    if (cred->pid == 0) {
-        cred->pid = logbuf ? logbuf->tidToPid(header->tid)
-                           : android::tidToPid(header->tid);
-        if (cred->pid == getpid()) {
-            // We expect that /proc/<tid>/ is accessible to self even without
-            // readproc group, so that we will always drop messages that come
-            // from any of our logd threads and their library calls.
-            return false;  // ignore self
-        }
-    }
-    if (cred->uid == DEFAULT_OVERFLOWUID) {
-        uid_t uid =
-            logbuf ? logbuf->pidToUid(cred->pid) : android::pidToUid(cred->pid);
-        if (uid == AID_LOGD) {
-            uid = logbuf ? logbuf->pidToUid(header->tid)
-                         : android::pidToUid(cred->pid);
-        }
-        if (uid != AID_LOGD) cred->uid = uid;
-    }
-
     char* msg = ((char*)buffer) + sizeof(android_log_header_t);
     n -= sizeof(android_log_header_t);
 
     // NB: hdr.msg_flags & MSG_TRUNC is not tested, silently passing a
     // truncated message to the logs.
 
-    if (logbuf != nullptr) {
-        int res = logbuf->log(
-            logId, header->realtime, cred->uid, cred->pid, header->tid, msg,
-            ((size_t)n <= UINT16_MAX) ? (uint16_t)n : UINT16_MAX);
-        if (res > 0 && reader != nullptr) {
-            reader->notifyNewLog(static_cast<log_mask_t>(1 << logId));
-        }
+    int res = logbuf->log(logId, header->realtime, cred->uid, cred->pid, header->tid, msg,
+                          ((size_t)n <= UINT16_MAX) ? (uint16_t)n : UINT16_MAX);
+    if (res > 0) {
+        reader->notifyNewLog(static_cast<log_mask_t>(1 << logId));
     }
 
     return true;
diff --git a/logd/LogListener.h b/logd/LogListener.h
index a562a54..8fe3da4 100644
--- a/logd/LogListener.h
+++ b/logd/LogListener.h
@@ -20,22 +20,12 @@
 #include <sysutils/SocketListener.h>
 #include "LogReader.h"
 
-// DEFAULT_OVERFLOWUID is defined in linux/highuid.h, which is not part of
-// the uapi headers for userspace to use.  This value is filled in on the
-// out-of-band socket credentials if the OS fails to find one available.
-// One of the causes of this is if SO_PASSCRED is set, all the packets before
-// that point will have this value.  We also use it in a fake credential if
-// no socket credentials are supplied.
-#ifndef DEFAULT_OVERFLOWUID
-#define DEFAULT_OVERFLOWUID 65534
-#endif
-
 class LogListener : public SocketListener {
-    LogBufferInterface* logbuf;
+    LogBuffer* logbuf;
     LogReader* reader;
 
    public:
-    LogListener(LogBufferInterface* buf, LogReader* reader /* nullable */);
+     LogListener(LogBuffer* buf, LogReader* reader);
 
    protected:
     virtual bool onDataAvailable(SocketClient* cli);
diff --git a/logd/LogStatistics.cpp b/logd/LogStatistics.cpp
index 116e08e..431b778 100644
--- a/logd/LogStatistics.cpp
+++ b/logd/LogStatistics.cpp
@@ -837,35 +837,12 @@
     }
     return AID_LOGD;  // associate this with the logger
 }
-
-pid_t tidToPid(pid_t tid) {
-    char buffer[512];
-    snprintf(buffer, sizeof(buffer), "/proc/%u/status", tid);
-    FILE* fp = fopen(buffer, "r");
-    if (fp) {
-        while (fgets(buffer, sizeof(buffer), fp)) {
-            int pid = tid;
-            char space = 0;
-            if ((sscanf(buffer, "Tgid: %d%c", &pid, &space) == 2) &&
-                isspace(space)) {
-                fclose(fp);
-                return pid;
-            }
-        }
-        fclose(fp);
-    }
-    return tid;
-}
 }
 
 uid_t LogStatistics::pidToUid(pid_t pid) {
     return pidTable.add(pid)->second.getUid();
 }
 
-pid_t LogStatistics::tidToPid(pid_t tid) {
-    return tidTable.add(tid)->second.getPid();
-}
-
 // caller must free character string
 const char* LogStatistics::pidToName(pid_t pid) const {
     // An inconvenient truth ... getName() can alter the object
diff --git a/logd/LogStatistics.h b/logd/LogStatistics.h
index 469f6dc..0782de3 100644
--- a/logd/LogStatistics.h
+++ b/logd/LogStatistics.h
@@ -306,6 +306,10 @@
     std::string format(const LogStatistics& stat, log_id_t id) const;
 };
 
+namespace android {
+uid_t pidToUid(pid_t pid);
+}
+
 struct PidEntry : public EntryBaseDropped {
     const pid_t pid;
     uid_t uid;
@@ -385,13 +389,6 @@
           uid(android::pidToUid(tid)),
           name(android::tidToName(tid)) {
     }
-    TidEntry(pid_t tid)
-        : EntryBaseDropped(),
-          tid(tid),
-          pid(android::tidToPid(tid)),
-          uid(android::pidToUid(tid)),
-          name(android::tidToName(tid)) {
-    }
     explicit TidEntry(const LogBufferElement* element)
         : EntryBaseDropped(element),
           tid(element->getTid()),
@@ -787,7 +784,6 @@
     // helper (must be locked directly or implicitly by mLogElementsLock)
     const char* pidToName(pid_t pid) const;
     uid_t pidToUid(pid_t pid);
-    pid_t tidToPid(pid_t tid);
     const char* uidToName(uid_t uid) const;
 };
 
diff --git a/logd/LogUtils.h b/logd/LogUtils.h
index 4dcd3e7..fa9f398 100644
--- a/logd/LogUtils.h
+++ b/logd/LogUtils.h
@@ -38,8 +38,6 @@
 // Caller must own and free returned value
 char* pidToName(pid_t pid);
 char* tidToName(pid_t tid);
-uid_t pidToUid(pid_t pid);
-pid_t tidToPid(pid_t tid);
 
 // Furnished in LogTags.cpp. Thread safe.
 const char* tagToName(uint32_t tag);
diff --git a/trusty/gatekeeper/Android.bp b/trusty/gatekeeper/Android.bp
index 65b271a..1666cfb 100644
--- a/trusty/gatekeeper/Android.bp
+++ b/trusty/gatekeeper/Android.bp
@@ -1,4 +1,3 @@
-//
 // Copyright (C) 2015 The Android Open-Source Project
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,14 +19,15 @@
 // to only building on ARM if they include assembly. Individual makefiles
 // are responsible for having their own logic, for fine-grained control.
 
-cc_library_shared {
-    name: "gatekeeper.trusty",
+cc_binary {
+    name: "android.hardware.gatekeeper@1.0-service.trusty",
+    defaults: ["hidl_defaults"],
     vendor: true,
-
     relative_install_path: "hw",
+    init_rc: ["android.hardware.gatekeeper@1.0-service.trusty.rc"],
 
     srcs: [
-        "module.cpp",
+        "service.cpp",
         "trusty_gatekeeper_ipc.c",
         "trusty_gatekeeper.cpp",
     ],
@@ -39,10 +39,16 @@
     ],
 
     shared_libs: [
+        "android.hardware.gatekeeper@1.0",
+        "libbase",
+        "libhidlbase",
+        "libhidltransport",
         "libgatekeeper",
+        "libutils",
         "liblog",
         "libcutils",
         "libtrusty",
     ],
-    header_libs: ["libhardware_headers"],
+
+    vintf_fragments: ["android.hardware.gatekeeper@1.0-service.trusty.xml"],
 }
diff --git a/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.rc b/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.rc
new file mode 100644
index 0000000..5413a6c
--- /dev/null
+++ b/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.rc
@@ -0,0 +1,4 @@
+service vendor.gatekeeper-1-0 /vendor/bin/hw/android.hardware.gatekeeper@1.0-service.trusty
+    class hal
+    user system
+    group system
diff --git a/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.xml b/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.xml
new file mode 100644
index 0000000..19714a8
--- /dev/null
+++ b/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.xml
@@ -0,0 +1,11 @@
+<manifest version="1.0" type="device">
+    <hal format="hidl">
+        <name>android.hardware.gatekeeper</name>
+        <transport>hwbinder</transport>
+        <version>1.0</version>
+        <interface>
+        <name>IGatekeeper</name>
+            <instance>default</instance>
+        </interface>
+    </hal>
+</manifest>
diff --git a/trusty/gatekeeper/module.cpp b/trusty/gatekeeper/module.cpp
deleted file mode 100644
index 0ee3c2f..0000000
--- a/trusty/gatekeeper/module.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <hardware/hardware.h>
-
-#include <string.h>
-#include <errno.h>
-#include <stdlib.h>
-
-#include "trusty_gatekeeper.h"
-
-using gatekeeper::TrustyGateKeeperDevice;
-
-static int trusty_gatekeeper_open(const hw_module_t *module, const char *name,
-        hw_device_t **device) {
-
-    if (strcmp(name, HARDWARE_GATEKEEPER) != 0) {
-        return -EINVAL;
-    }
-
-    TrustyGateKeeperDevice *gatekeeper = new TrustyGateKeeperDevice(module);
-    if (gatekeeper == NULL) return -ENOMEM;
-    *device = gatekeeper->hw_device();
-
-    return 0;
-}
-
-static struct hw_module_methods_t gatekeeper_module_methods = {
-    .open = trusty_gatekeeper_open,
-};
-
-struct gatekeeper_module HAL_MODULE_INFO_SYM __attribute__((visibility("default"))) = {
-    .common = {
-        .tag = HARDWARE_MODULE_TAG,
-        .module_api_version = GATEKEEPER_MODULE_API_VERSION_0_1,
-        .hal_api_version = HARDWARE_HAL_API_VERSION,
-        .id = GATEKEEPER_HARDWARE_MODULE_ID,
-        .name = "Trusty GateKeeper HAL",
-        .author = "The Android Open Source Project",
-        .methods = &gatekeeper_module_methods,
-        .dso = 0,
-        .reserved = {}
-    },
-};
diff --git a/trusty/gatekeeper/service.cpp b/trusty/gatekeeper/service.cpp
new file mode 100644
index 0000000..c5ee488
--- /dev/null
+++ b/trusty/gatekeeper/service.cpp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define LOG_TAG "android.hardware.gatekeeper@1.0-service.trusty"
+
+#include <android-base/logging.h>
+#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
+
+#include <hidl/LegacySupport.h>
+
+#include "trusty_gatekeeper.h"
+
+// Generated HIDL files
+using android::hardware::gatekeeper::V1_0::IGatekeeper;
+using gatekeeper::TrustyGateKeeperDevice;
+
+int main() {
+    ::android::hardware::configureRpcThreadpool(1, true /* willJoinThreadpool */);
+    android::sp<TrustyGateKeeperDevice> gatekeeper(new TrustyGateKeeperDevice());
+    auto status = gatekeeper->registerAsService();
+    if (status != android::OK) {
+        LOG(FATAL) << "Could not register service for Gatekeeper 1.0 (trusty) (" << status << ")";
+    }
+
+    android::hardware::joinRpcThreadpool();
+    return -1;  // Should never get here.
+}
diff --git a/trusty/gatekeeper/trusty_gatekeeper.cpp b/trusty/gatekeeper/trusty_gatekeeper.cpp
index b3fbfa9..d149664 100644
--- a/trusty/gatekeeper/trusty_gatekeeper.cpp
+++ b/trusty/gatekeeper/trusty_gatekeeper.cpp
@@ -16,147 +16,131 @@
 
 #define LOG_TAG "TrustyGateKeeper"
 
-#include <assert.h>
-#include <errno.h>
-#include <stdio.h>
-
-#include <type_traits>
-
-#include <log/log.h>
+#include <android-base/logging.h>
+#include <limits>
 
 #include "trusty_gatekeeper.h"
 #include "trusty_gatekeeper_ipc.h"
 #include "gatekeeper_ipc.h"
 
+using ::android::hardware::hidl_vec;
+using ::android::hardware::Return;
+using ::android::hardware::gatekeeper::V1_0::GatekeeperStatusCode;
+using ::gatekeeper::EnrollRequest;
+using ::gatekeeper::EnrollResponse;
+using ::gatekeeper::ERROR_INVALID;
+using ::gatekeeper::ERROR_MEMORY_ALLOCATION_FAILED;
+using ::gatekeeper::ERROR_NONE;
+using ::gatekeeper::ERROR_RETRY;
+using ::gatekeeper::SizedBuffer;
+using ::gatekeeper::VerifyRequest;
+using ::gatekeeper::VerifyResponse;
+
 namespace gatekeeper {
 
-const uint32_t SEND_BUF_SIZE = 8192;
-const uint32_t RECV_BUF_SIZE = 8192;
+constexpr const uint32_t SEND_BUF_SIZE = 8192;
+constexpr const uint32_t RECV_BUF_SIZE = 8192;
 
-TrustyGateKeeperDevice::TrustyGateKeeperDevice(const hw_module_t *module) {
-#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
-    static_assert(std::is_standard_layout<TrustyGateKeeperDevice>::value,
-                  "TrustyGateKeeperDevice must be standard layout");
-    static_assert(offsetof(TrustyGateKeeperDevice, device_) == 0,
-                  "device_ must be the first member of TrustyGateKeeperDevice");
-    static_assert(offsetof(TrustyGateKeeperDevice, device_.common) == 0,
-                  "common must be the first member of gatekeeper_device");
-#else
-    assert(reinterpret_cast<gatekeeper_device_t *>(this) == &device_);
-    assert(reinterpret_cast<hw_device_t *>(this) == &(device_.common));
-#endif
-
-    memset(&device_, 0, sizeof(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_.enroll = enroll;
-    device_.verify = verify;
-    device_.delete_user = nullptr;
-    device_.delete_all_users = nullptr;
-
+TrustyGateKeeperDevice::TrustyGateKeeperDevice() {
     int rc = trusty_gatekeeper_connect();
     if (rc < 0) {
-        ALOGE("Error initializing trusty session: %d", rc);
+        LOG(ERROR) << "Error initializing trusty session: " << rc;
     }
 
     error_ = rc;
-
-}
-
-hw_device_t* TrustyGateKeeperDevice::hw_device() {
-    return &device_.common;
-}
-
-int TrustyGateKeeperDevice::close_device(hw_device_t* dev) {
-    delete reinterpret_cast<TrustyGateKeeperDevice *>(dev);
-    return 0;
 }
 
 TrustyGateKeeperDevice::~TrustyGateKeeperDevice() {
     trusty_gatekeeper_disconnect();
 }
 
-int TrustyGateKeeperDevice::Enroll(uint32_t uid, const uint8_t *current_password_handle,
-        uint32_t current_password_handle_length, const uint8_t *current_password,
-        uint32_t current_password_length, const uint8_t *desired_password,
-        uint32_t desired_password_length, uint8_t **enrolled_password_handle,
-        uint32_t *enrolled_password_handle_length) {
-
-    if (error_ != 0) {
-        return error_;
-    }
-
-    SizedBuffer desired_password_buffer(desired_password_length);
-    memcpy(desired_password_buffer.buffer.get(), desired_password, desired_password_length);
-
-    SizedBuffer current_password_handle_buffer(current_password_handle_length);
-    if (current_password_handle) {
-        memcpy(current_password_handle_buffer.buffer.get(), current_password_handle,
-                current_password_handle_length);
-    }
-
-    SizedBuffer current_password_buffer(current_password_length);
-    if (current_password) {
-        memcpy(current_password_buffer.buffer.get(), current_password, current_password_length);
-    }
-
-    EnrollRequest request(uid, &current_password_handle_buffer, &desired_password_buffer,
-            &current_password_buffer);
-    EnrollResponse response;
-
-    gatekeeper_error_t error = Send(request, &response);
-
-    if (error == ERROR_RETRY) {
-        return response.retry_timeout;
-    } else if (error != ERROR_NONE) {
-        return -EINVAL;
-    }
-
-    *enrolled_password_handle = response.enrolled_password_handle.buffer.release();
-    *enrolled_password_handle_length = response.enrolled_password_handle.length;
-
-
-    return 0;
+SizedBuffer hidl_vec2sized_buffer(const hidl_vec<uint8_t>& vec) {
+    if (vec.size() == 0 || vec.size() > std::numeric_limits<uint32_t>::max()) return {};
+    auto dummy = new uint8_t[vec.size()];
+    std::copy(vec.begin(), vec.end(), dummy);
+    return {dummy, static_cast<uint32_t>(vec.size())};
 }
 
-int TrustyGateKeeperDevice::Verify(uint32_t uid, uint64_t challenge,
-        const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
-        const uint8_t *provided_password, uint32_t provided_password_length,
-        uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll) {
+Return<void> TrustyGateKeeperDevice::enroll(uint32_t uid,
+                                            const hidl_vec<uint8_t>& currentPasswordHandle,
+                                            const hidl_vec<uint8_t>& currentPassword,
+                                            const hidl_vec<uint8_t>& desiredPassword,
+                                            enroll_cb _hidl_cb) {
     if (error_ != 0) {
-        return error_;
+        _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+        return {};
     }
 
-    SizedBuffer password_handle_buffer(enrolled_password_handle_length);
-    memcpy(password_handle_buffer.buffer.get(), enrolled_password_handle,
-            enrolled_password_handle_length);
-    SizedBuffer provided_password_buffer(provided_password_length);
-    memcpy(provided_password_buffer.buffer.get(), provided_password, provided_password_length);
+    if (desiredPassword.size() == 0) {
+        _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+        return {};
+    }
 
-    VerifyRequest request(uid, challenge, &password_handle_buffer, &provided_password_buffer);
+    EnrollRequest request(uid, hidl_vec2sized_buffer(currentPasswordHandle),
+                          hidl_vec2sized_buffer(desiredPassword),
+                          hidl_vec2sized_buffer(currentPassword));
+    EnrollResponse response;
+    auto error = Send(request, &response);
+    if (error != ERROR_NONE) {
+        _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+    } else if (response.error == ERROR_RETRY) {
+        _hidl_cb({GatekeeperStatusCode::ERROR_RETRY_TIMEOUT, response.retry_timeout, {}});
+    } else if (response.error != ERROR_NONE) {
+        _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+    } else {
+        hidl_vec<uint8_t> new_handle(response.enrolled_password_handle.Data<uint8_t>(),
+                                     response.enrolled_password_handle.Data<uint8_t>() +
+                                             response.enrolled_password_handle.size());
+        _hidl_cb({GatekeeperStatusCode::STATUS_OK, response.retry_timeout, new_handle});
+    }
+    return {};
+}
+
+Return<void> TrustyGateKeeperDevice::verify(
+        uint32_t uid, uint64_t challenge,
+        const ::android::hardware::hidl_vec<uint8_t>& enrolledPasswordHandle,
+        const ::android::hardware::hidl_vec<uint8_t>& providedPassword, verify_cb _hidl_cb) {
+    if (error_ != 0) {
+        _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+        return {};
+    }
+
+    if (enrolledPasswordHandle.size() == 0) {
+        _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+        return {};
+    }
+
+    VerifyRequest request(uid, challenge, hidl_vec2sized_buffer(enrolledPasswordHandle),
+                          hidl_vec2sized_buffer(providedPassword));
     VerifyResponse response;
 
-    gatekeeper_error_t error = Send(request, &response);
+    auto error = Send(request, &response);
+    if (error != ERROR_NONE) {
+        _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+    } else if (response.error == ERROR_RETRY) {
+        _hidl_cb({GatekeeperStatusCode::ERROR_RETRY_TIMEOUT, response.retry_timeout, {}});
+    } else if (response.error != ERROR_NONE) {
+        _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+    } else {
+        hidl_vec<uint8_t> auth_token(
+                response.auth_token.Data<uint8_t>(),
+                response.auth_token.Data<uint8_t>() + response.auth_token.size());
 
-    if (error == ERROR_RETRY) {
-        return response.retry_timeout;
-    } else if (error != ERROR_NONE) {
-        return -EINVAL;
+        _hidl_cb({response.request_reenroll ? GatekeeperStatusCode::STATUS_REENROLL
+                                            : GatekeeperStatusCode::STATUS_OK,
+                  response.retry_timeout, auth_token});
     }
+    return {};
+}
 
-    if (auth_token != NULL && auth_token_length != NULL) {
-       *auth_token = response.auth_token.buffer.release();
-       *auth_token_length = response.auth_token.length;
-    }
+Return<void> TrustyGateKeeperDevice::deleteUser(uint32_t /*uid*/, deleteUser_cb _hidl_cb) {
+    _hidl_cb({GatekeeperStatusCode::ERROR_NOT_IMPLEMENTED, 0, {}});
+    return {};
+}
 
-    if (request_reenroll != NULL) {
-        *request_reenroll = response.request_reenroll;
-    }
-
-    return 0;
+Return<void> TrustyGateKeeperDevice::deleteAllUsers(deleteAllUsers_cb _hidl_cb) {
+    _hidl_cb({GatekeeperStatusCode::ERROR_NOT_IMPLEMENTED, 0, {}});
+    return {};
 }
 
 gatekeeper_error_t TrustyGateKeeperDevice::Send(uint32_t command, const GateKeeperMessage& request,
@@ -172,7 +156,7 @@
     uint32_t response_size = RECV_BUF_SIZE;
     int rc = trusty_gatekeeper_call(command, send_buf, request_size, recv_buf, &response_size);
     if (rc < 0) {
-        ALOGE("error (%d) calling gatekeeper TA", rc);
+        LOG(ERROR) << "error (" << rc << ") calling gatekeeper TA";
         return ERROR_INVALID;
     }
 
@@ -182,51 +166,4 @@
     return response->Deserialize(payload, payload + response_size);
 }
 
-static inline TrustyGateKeeperDevice *convert_device(const gatekeeper_device *dev) {
-    return reinterpret_cast<TrustyGateKeeperDevice *>(const_cast<gatekeeper_device *>(dev));
-}
-
-/* static */
-int TrustyGateKeeperDevice::enroll(const struct gatekeeper_device *dev, uint32_t uid,
-            const uint8_t *current_password_handle, uint32_t current_password_handle_length,
-            const uint8_t *current_password, uint32_t current_password_length,
-            const uint8_t *desired_password, uint32_t desired_password_length,
-            uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) {
-
-    if (dev == NULL ||
-            enrolled_password_handle == NULL || enrolled_password_handle_length == NULL ||
-            desired_password == NULL || desired_password_length == 0)
-        return -EINVAL;
-
-    // Current password and current password handle go together
-    if (current_password_handle == NULL || current_password_handle_length == 0 ||
-            current_password == NULL || current_password_length == 0) {
-        current_password_handle = NULL;
-        current_password_handle_length = 0;
-        current_password = NULL;
-        current_password_length = 0;
-    }
-
-    return convert_device(dev)->Enroll(uid, current_password_handle, current_password_handle_length,
-            current_password, current_password_length, desired_password, desired_password_length,
-            enrolled_password_handle, enrolled_password_handle_length);
-
-}
-
-/* static */
-int TrustyGateKeeperDevice::verify(const struct gatekeeper_device *dev, uint32_t uid,
-        uint64_t challenge, const uint8_t *enrolled_password_handle,
-        uint32_t enrolled_password_handle_length, const uint8_t *provided_password,
-        uint32_t provided_password_length, uint8_t **auth_token, uint32_t *auth_token_length,
-        bool *request_reenroll) {
-
-    if (dev == NULL || enrolled_password_handle == NULL ||
-            provided_password == NULL) {
-        return -EINVAL;
-    }
-
-    return convert_device(dev)->Verify(uid, challenge, enrolled_password_handle,
-            enrolled_password_handle_length, provided_password, provided_password_length,
-            auth_token, auth_token_length, request_reenroll);
-}
 };
diff --git a/trusty/gatekeeper/trusty_gatekeeper.h b/trusty/gatekeeper/trusty_gatekeeper.h
index 2becc49..c0713f4 100644
--- a/trusty/gatekeeper/trusty_gatekeeper.h
+++ b/trusty/gatekeeper/trusty_gatekeeper.h
@@ -17,84 +17,34 @@
 #ifndef TRUSTY_GATEKEEPER_H
 #define TRUSTY_GATEKEEPER_H
 
-#include <hardware/gatekeeper.h>
+#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
+#include <hidl/Status.h>
+
+#include <memory>
+
 #include <gatekeeper/gatekeeper_messages.h>
 
 #include "gatekeeper_ipc.h"
 
 namespace gatekeeper {
 
-class TrustyGateKeeperDevice {
-    public:
-
-    explicit TrustyGateKeeperDevice(const hw_module_t* module);
+class TrustyGateKeeperDevice : public ::android::hardware::gatekeeper::V1_0::IGatekeeper {
+  public:
+    explicit TrustyGateKeeperDevice();
     ~TrustyGateKeeperDevice();
-
-    hw_device_t* hw_device();
-
     /**
      * Enrolls password_payload, which should be derived from a user selected pin or password,
      * with the authentication factor private key used only for enrolling authentication
      * factor data.
      *
      * Returns: 0 on success or an error code less than 0 on error.
-     * On error, enrolled_password will not be allocated.
-     */
-    int Enroll(uint32_t uid, const uint8_t *current_password_handle,
-            uint32_t current_password_handle_length, const uint8_t *current_password,
-            uint32_t current_password_length, const uint8_t *desired_password,
-            uint32_t desired_password_length, uint8_t **enrolled_password_handle,
-            uint32_t *enrolled_password_handle_length);
-
-    /**
-     * Verifies provided_password matches expected_password after enrolling
-     * with the authentication factor private key.
-     *
-     * Implementations of this module may retain the result of this call
-     * to attest to the recency of authentication.
-     *
-     * On success, writes the address of a verification token to verification_token,
-     *
-     * Returns: 0 on success or an error code less than 0 on error
-     * On error, verification token will not be allocated
-     */
-    int Verify(uint32_t uid, uint64_t challenge, const uint8_t *enrolled_password_handle,
-            uint32_t enrolled_password_handle_length, const uint8_t *provided_password,
-            uint32_t provided_password_length, uint8_t **auth_token, uint32_t *auth_token_length,
-            bool *request_reenroll);
-
-    private:
-
-    gatekeeper_error_t Send(uint32_t command, const GateKeeperMessage& request,
-                           GateKeeperMessage* response);
-
-    gatekeeper_error_t Send(const EnrollRequest& request, EnrollResponse *response) {
-        return Send(GK_ENROLL, request, response);
-    }
-
-    gatekeeper_error_t Send(const VerifyRequest& request, VerifyResponse *response) {
-        return Send(GK_VERIFY, request, response);
-    }
-
-    // Static methods interfacing the HAL API with the TrustyGateKeeper device
-
-    /**
-     * Enrolls desired_password, which should be derived from a user selected pin or password,
-     * with the authentication factor private key used only for enrolling authentication
-     * factor data.
-     *
-     * If there was already a password enrolled, it should be provided in
-     * current_password_handle, along with the current password in current_password
-     * that should validate against current_password_handle.
-     *
-     * Returns: 0 on success or an error code less than 0 on error.
      * On error, enrolled_password_handle will not be allocated.
      */
-    static int enroll(const struct gatekeeper_device *dev, uint32_t uid,
-            const uint8_t *current_password_handle, uint32_t current_password_handle_length,
-            const uint8_t *current_password, uint32_t current_password_length,
-            const uint8_t *desired_password, uint32_t desired_password_length,
-            uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length);
+    ::android::hardware::Return<void> enroll(
+            uint32_t uid, const ::android::hardware::hidl_vec<uint8_t>& currentPasswordHandle,
+            const ::android::hardware::hidl_vec<uint8_t>& currentPassword,
+            const ::android::hardware::hidl_vec<uint8_t>& desiredPassword,
+            enroll_cb _hidl_cb) override;
 
     /**
      * Verifies provided_password matches enrolled_password_handle.
@@ -109,18 +59,32 @@
      * Returns: 0 on success or an error code less than 0 on error
      * On error, verification token will not be allocated
      */
-    static int verify(const struct gatekeeper_device *dev, uint32_t uid, uint64_t challenge,
-            const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
-            const uint8_t *provided_password, uint32_t provided_password_length,
-            uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll);
+    ::android::hardware::Return<void> verify(
+            uint32_t uid, uint64_t challenge,
+            const ::android::hardware::hidl_vec<uint8_t>& enrolledPasswordHandle,
+            const ::android::hardware::hidl_vec<uint8_t>& providedPassword,
+            verify_cb _hidl_cb) override;
 
-    static int close_device(hw_device_t* dev);
+    ::android::hardware::Return<void> deleteUser(uint32_t uid, deleteUser_cb _hidl_cb) override;
 
-    gatekeeper_device device_;
+    ::android::hardware::Return<void> deleteAllUsers(deleteAllUsers_cb _hidl_cb) override;
+
+  private:
+    gatekeeper_error_t Send(uint32_t command, const GateKeeperMessage& request,
+                           GateKeeperMessage* response);
+
+    gatekeeper_error_t Send(const EnrollRequest& request, EnrollResponse *response) {
+        return Send(GK_ENROLL, request, response);
+    }
+
+    gatekeeper_error_t Send(const VerifyRequest& request, VerifyResponse *response) {
+        return Send(GK_VERIFY, request, response);
+    }
+
     int error_;
-
 };
-}
+
+}  // namespace gatekeeper
 
 #endif
 
diff --git a/trusty/trusty-base.mk b/trusty/trusty-base.mk
index 445d3ce..fd8daa8 100644
--- a/trusty/trusty-base.mk
+++ b/trusty/trusty-base.mk
@@ -24,9 +24,7 @@
 
 PRODUCT_PACKAGES += \
 	android.hardware.keymaster@4.0-service.trusty \
-	android.hardware.gatekeeper@1.0-service \
-	android.hardware.gatekeeper@1.0-impl \
-	gatekeeper.trusty
+	android.hardware.gatekeeper@1.0-service.trusty
 
 PRODUCT_PROPERTY_OVERRIDES += \
 	ro.hardware.keystore=trusty \