Import translations. DO NOT MERGE am: 34e2854786  -s ours
am: 93d2e08ef2  -s ours

Change-Id: Icfba2b987aae40dd9f9cebfb7299cc5319d4bc68
diff --git a/Android.mk b/Android.mk
index dcc11c5..43236fe 100644
--- a/Android.mk
+++ b/Android.mk
@@ -41,7 +41,6 @@
 LOCAL_SRC_FILES := \
     adb_install.cpp \
     asn1_decoder.cpp \
-    bootloader.cpp \
     device.cpp \
     fuse_sdcard_provider.cpp \
     install.cpp \
@@ -76,6 +75,7 @@
 
 LOCAL_STATIC_LIBRARIES := \
     libbatterymonitor \
+    libbootloader_message \
     libext4_utils_static \
     libsparse_static \
     libminzip \
@@ -101,6 +101,10 @@
 LOCAL_C_INCLUDES += system/extras/ext4_utils
 LOCAL_STATIC_LIBRARIES += libext4_utils_static libz
 
+ifeq ($(AB_OTA_UPDATER),true)
+    LOCAL_CFLAGS += -DAB_OTA_UPDATER=1
+endif
+
 LOCAL_MODULE_PATH := $(TARGET_RECOVERY_ROOT_OUT)/sbin
 
 ifeq ($(TARGET_RECOVERY_UI_LIB),)
@@ -148,14 +152,16 @@
 LOCAL_STATIC_LIBRARIES := libcrypto_utils_static libcrypto_static
 include $(BUILD_STATIC_LIBRARY)
 
-include $(LOCAL_PATH)/minui/Android.mk \
-    $(LOCAL_PATH)/minzip/Android.mk \
+include \
+    $(LOCAL_PATH)/applypatch/Android.mk \
+    $(LOCAL_PATH)/bootloader_message/Android.mk \
+    $(LOCAL_PATH)/edify/Android.mk \
     $(LOCAL_PATH)/minadbd/Android.mk \
+    $(LOCAL_PATH)/minui/Android.mk \
+    $(LOCAL_PATH)/minzip/Android.mk \
+    $(LOCAL_PATH)/otafault/Android.mk \
     $(LOCAL_PATH)/tests/Android.mk \
     $(LOCAL_PATH)/tools/Android.mk \
-    $(LOCAL_PATH)/edify/Android.mk \
     $(LOCAL_PATH)/uncrypt/Android.mk \
-    $(LOCAL_PATH)/otafault/Android.mk \
     $(LOCAL_PATH)/updater/Android.mk \
     $(LOCAL_PATH)/update_verifier/Android.mk \
-    $(LOCAL_PATH)/applypatch/Android.mk
diff --git a/bootloader.cpp b/bootloader.cpp
deleted file mode 100644
index 783f56e..0000000
--- a/bootloader.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <fs_mgr.h>
-
-#include "bootloader.h"
-#include "common.h"
-#include "roots.h"
-#include <android-base/unique_fd.h>
-
-static int get_bootloader_message_block(bootloader_message* out, const Volume* v);
-static int set_bootloader_message_block(const bootloader_message* in, const Volume* v);
-
-int get_bootloader_message(bootloader_message* out) {
-    Volume* v = volume_for_path("/misc");
-    if (v == nullptr) {
-        LOGE("Cannot load volume /misc!\n");
-        return -1;
-    }
-    if (strcmp(v->fs_type, "emmc") == 0) {
-        return get_bootloader_message_block(out, v);
-    }
-    LOGE("unknown misc partition fs_type \"%s\"\n", v->fs_type);
-    return -1;
-}
-
-int set_bootloader_message(const bootloader_message* in) {
-    Volume* v = volume_for_path("/misc");
-    if (v == nullptr) {
-        LOGE("Cannot load volume /misc!\n");
-        return -1;
-    }
-    if (strcmp(v->fs_type, "emmc") == 0) {
-        return set_bootloader_message_block(in, v);
-    }
-    LOGE("unknown misc partition fs_type \"%s\"\n", v->fs_type);
-    return -1;
-}
-
-// ------------------------------------
-// for misc partitions on block devices
-// ------------------------------------
-
-static void wait_for_device(const char* fn) {
-    int tries = 0;
-    int ret;
-    do {
-        ++tries;
-        struct stat buf;
-        ret = stat(fn, &buf);
-        if (ret == -1) {
-            printf("failed to stat \"%s\" try %d: %s\n", fn, tries, strerror(errno));
-            sleep(1);
-        }
-    } while (ret && tries < 10);
-
-    if (ret) {
-        printf("failed to stat \"%s\"\n", fn);
-    }
-}
-
-static int get_bootloader_message_block(bootloader_message* out,
-                                        const Volume* v) {
-    wait_for_device(v->blk_device);
-    FILE* f = fopen(v->blk_device, "rb");
-    if (f == nullptr) {
-        LOGE("failed to open \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
-    }
-    bootloader_message temp;
-    int count = fread(&temp, sizeof(temp), 1, f);
-    if (count != 1) {
-        LOGE("failed to read \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
-    }
-    if (fclose(f) != 0) {
-        LOGE("failed to close \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
-    }
-    memcpy(out, &temp, sizeof(temp));
-    return 0;
-}
-
-static int set_bootloader_message_block(const bootloader_message* in,
-                                        const Volume* v) {
-    wait_for_device(v->blk_device);
-    android::base::unique_fd fd(open(v->blk_device, O_WRONLY | O_SYNC));
-    if (fd == -1) {
-        LOGE("failed to open \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
-    }
-
-    size_t written = 0;
-    const uint8_t* start = reinterpret_cast<const uint8_t*>(in);
-    size_t total = sizeof(*in);
-    while (written < total) {
-        ssize_t wrote = TEMP_FAILURE_RETRY(write(fd, start + written, total - written));
-        if (wrote == -1) {
-            LOGE("failed to write %" PRId64 " bytes: %s\n",
-                 static_cast<off64_t>(written), strerror(errno));
-            return -1;
-        }
-        written += wrote;
-    }
-
-    if (fsync(fd) == -1) {
-        LOGE("failed to fsync \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
-    }
-    return 0;
-}
diff --git a/bootloader.h b/bootloader.h
index 1801705..9c84a1c 100644
--- a/bootloader.h
+++ b/bootloader.h
@@ -14,158 +14,5 @@
  * limitations under the License.
  */
 
-#ifndef _RECOVERY_BOOTLOADER_H
-#define _RECOVERY_BOOTLOADER_H
-
-#include <assert.h>
-
-/* Bootloader Message (2-KiB)
- *
- * This structure describes the content of a block in flash
- * that is used for recovery and the bootloader to talk to
- * each other.
- *
- * The command field is updated by linux when it wants to
- * reboot into recovery or to update radio or bootloader firmware.
- * It is also updated by the bootloader when firmware update
- * is complete (to boot into recovery for any final cleanup)
- *
- * The status field is written by the bootloader after the
- * completion of an "update-radio" or "update-hboot" command.
- *
- * The recovery field is only written by linux and used
- * for the system to send a message to recovery or the
- * other way around.
- *
- * The stage field is written by packages which restart themselves
- * multiple times, so that the UI can reflect which invocation of the
- * package it is.  If the value is of the format "#/#" (eg, "1/3"),
- * the UI will add a simple indicator of that status.
- *
- * We used to have slot_suffix field for A/B boot control metadata in
- * this struct, which gets unintentionally cleared by recovery or
- * uncrypt. Move it into struct bootloader_message_ab to avoid the
- * issue.
- */
-struct bootloader_message {
-    char command[32];
-    char status[32];
-    char recovery[768];
-
-    // The 'recovery' field used to be 1024 bytes.  It has only ever
-    // been used to store the recovery command line, so 768 bytes
-    // should be plenty.  We carve off the last 256 bytes to store the
-    // stage string (for multistage packages) and possible future
-    // expansion.
-    char stage[32];
-
-    // The 'reserved' field used to be 224 bytes when it was initially
-    // carved off from the 1024-byte recovery field. Bump it up to
-    // 1184-byte so that the entire bootloader_message struct rounds up
-    // to 2048-byte.
-    char reserved[1184];
-};
-
-/**
- * We must be cautious when changing the bootloader_message struct size,
- * because A/B-specific fields may end up with different offsets.
- */
-#if (__STDC_VERSION__ >= 201112L) || defined(__cplusplus)
-static_assert(sizeof(struct bootloader_message) == 2048,
-              "struct bootloader_message size changes, which may break A/B devices");
-#endif
-
-/**
- * The A/B-specific bootloader message structure (4-KiB).
- *
- * We separate A/B boot control metadata from the regular bootloader
- * message struct and keep it here. Everything that's A/B-specific
- * stays after struct bootloader_message, which should be managed by
- * the A/B-bootloader or boot control HAL.
- *
- * The slot_suffix field is used for A/B implementations where the
- * bootloader does not set the androidboot.ro.boot.slot_suffix kernel
- * commandline parameter. This is used by fs_mgr to mount /system and
- * other partitions with the slotselect flag set in fstab. A/B
- * implementations are free to use all 32 bytes and may store private
- * data past the first NUL-byte in this field. It is encouraged, but
- * not mandatory, to use 'struct bootloader_control' described below.
- */
-struct bootloader_message_ab {
-    struct bootloader_message message;
-    char slot_suffix[32];
-
-    // Round up the entire struct to 4096-byte.
-    char reserved[2016];
-};
-
-/**
- * Be cautious about the struct size change, in case we put anything post
- * bootloader_message_ab struct (b/29159185).
- */
-#if (__STDC_VERSION__ >= 201112L) || defined(__cplusplus)
-static_assert(sizeof(struct bootloader_message_ab) == 4096,
-              "struct bootloader_message_ab size changes");
-#endif
-
-#define BOOT_CTRL_MAGIC   0x42414342 /* Bootloader Control AB */
-#define BOOT_CTRL_VERSION 1
-
-struct slot_metadata {
-    // Slot priority with 15 meaning highest priority, 1 lowest
-    // priority and 0 the slot is unbootable.
-    uint8_t priority : 4;
-    // Number of times left attempting to boot this slot.
-    uint8_t tries_remaining : 3;
-    // 1 if this slot has booted successfully, 0 otherwise.
-    uint8_t successful_boot : 1;
-    // 1 if this slot is corrupted from a dm-verity corruption, 0
-    // otherwise.
-    uint8_t verity_corrupted : 1;
-    // Reserved for further use.
-    uint8_t reserved : 7;
-} __attribute__((packed));
-
-/* Bootloader Control AB
- *
- * This struct can be used to manage A/B metadata. It is designed to
- * be put in the 'slot_suffix' field of the 'bootloader_message'
- * structure described above. It is encouraged to use the
- * 'bootloader_control' structure to store the A/B metadata, but not
- * mandatory.
- */
-struct bootloader_control {
-    // NUL terminated active slot suffix.
-    char slot_suffix[4];
-    // Bootloader Control AB magic number (see BOOT_CTRL_MAGIC).
-    uint32_t magic;
-    // Version of struct being used (see BOOT_CTRL_VERSION).
-    uint8_t version;
-    // Number of slots being managed.
-    uint8_t nb_slot : 3;
-    // Number of times left attempting to boot recovery.
-    uint8_t recovery_tries_remaining : 3;
-    // Ensure 4-bytes alignment for slot_info field.
-    uint8_t reserved0[2];
-    // Per-slot information.  Up to 4 slots.
-    struct slot_metadata slot_info[4];
-    // Reserved for further use.
-    uint8_t reserved1[8];
-    // CRC32 of all 28 bytes preceding this field (little endian
-    // format).
-    uint32_t crc32_le;
-} __attribute__((packed));
-
-#if (__STDC_VERSION__ >= 201112L) || defined(__cplusplus)
-static_assert(sizeof(struct bootloader_control) ==
-              sizeof(((struct bootloader_message_ab *)0)->slot_suffix),
-              "struct bootloader_control has wrong size");
-#endif
-
-/* Read and write the bootloader command from the "misc" partition.
- * These return zero on success.
- */
-int get_bootloader_message(struct bootloader_message *out);
-int set_bootloader_message(const struct bootloader_message *in);
-
-#endif
+// TODO: Remove this file once we remove all places that include this file.
+#include "bootloader_message/include/bootloader_message/bootloader_message.h"
diff --git a/bootloader_message/Android.mk b/bootloader_message/Android.mk
new file mode 100644
index 0000000..815ac67
--- /dev/null
+++ b/bootloader_message/Android.mk
@@ -0,0 +1,24 @@
+# Copyright (C) 2016 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_CLANG := true
+LOCAL_SRC_FILES := bootloader_message.cpp
+LOCAL_MODULE := libbootloader_message
+LOCAL_STATIC_LIBRARIES := libbase libfs_mgr
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+include $(BUILD_STATIC_LIBRARY)
diff --git a/bootloader_message/bootloader_message.cpp b/bootloader_message/bootloader_message.cpp
new file mode 100644
index 0000000..e7195ae
--- /dev/null
+++ b/bootloader_message/bootloader_message.cpp
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <bootloader_message/bootloader_message.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/system_properties.h>
+
+#include <string>
+#include <vector>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <android-base/unique_fd.h>
+#include <fs_mgr.h>
+
+static struct fstab* read_fstab(std::string* err) {
+  // The fstab path is always "/fstab.${ro.hardware}".
+  std::string fstab_path = "/fstab.";
+  char value[PROP_VALUE_MAX];
+  if (__system_property_get("ro.hardware", value) == 0) {
+    *err = "failed to get ro.hardware";
+    return nullptr;
+  }
+  fstab_path += value;
+  struct fstab* fstab = fs_mgr_read_fstab(fstab_path.c_str());
+  if (fstab == nullptr) {
+    *err = "failed to read " + fstab_path;
+  }
+  return fstab;
+}
+
+static std::string get_misc_blk_device(std::string* err) {
+  struct fstab* fstab = read_fstab(err);
+  if (fstab == nullptr) {
+    return "";
+  }
+  fstab_rec* record = fs_mgr_get_entry_for_mount_point(fstab, "/misc");
+  if (record == nullptr) {
+    *err = "failed to find /misc partition";
+    return "";
+  }
+  return record->blk_device;
+}
+
+// In recovery mode, recovery can get started and try to access the misc
+// device before the kernel has actually created it.
+static bool wait_for_device(const std::string& blk_device, std::string* err) {
+  int tries = 0;
+  int ret;
+  err->clear();
+  do {
+    ++tries;
+    struct stat buf;
+    ret = stat(blk_device.c_str(), &buf);
+    if (ret == -1) {
+      *err += android::base::StringPrintf("failed to stat %s try %d: %s\n",
+                                          blk_device.c_str(), tries, strerror(errno));
+      sleep(1);
+    }
+  } while (ret && tries < 10);
+
+  if (ret) {
+    *err += android::base::StringPrintf("failed to stat %s\n", blk_device.c_str());
+  }
+  return ret == 0;
+}
+
+static bool read_misc_partition(void* p, size_t size, size_t offset, std::string* err) {
+  std::string misc_blk_device = get_misc_blk_device(err);
+  if (misc_blk_device.empty()) {
+    return false;
+  }
+  if (!wait_for_device(misc_blk_device, err)) {
+    return false;
+  }
+  android::base::unique_fd fd(open(misc_blk_device.c_str(), O_WRONLY | O_SYNC));
+  if (fd.get() == -1) {
+    *err = android::base::StringPrintf("failed to open %s: %s", misc_blk_device.c_str(),
+                                       strerror(errno));
+    return false;
+  }
+  if (lseek(fd.get(), static_cast<off_t>(offset), SEEK_SET) != static_cast<off_t>(offset)) {
+    *err = android::base::StringPrintf("failed to lseek %s: %s", misc_blk_device.c_str(),
+                                       strerror(errno));
+    return false;
+  }
+  if (!android::base::ReadFully(fd.get(), p, size)) {
+    *err = android::base::StringPrintf("failed to read %s: %s", misc_blk_device.c_str(),
+                                       strerror(errno));
+    return false;
+  }
+  return true;
+}
+
+static bool write_misc_partition(const void* p, size_t size, size_t offset, std::string* err) {
+  std::string misc_blk_device = get_misc_blk_device(err);
+  if (misc_blk_device.empty()) {
+    return false;
+  }
+  android::base::unique_fd fd(open(misc_blk_device.c_str(), O_WRONLY | O_SYNC));
+  if (fd.get() == -1) {
+    *err = android::base::StringPrintf("failed to open %s: %s", misc_blk_device.c_str(),
+                                       strerror(errno));
+    return false;
+  }
+  if (lseek(fd.get(), static_cast<off_t>(offset), SEEK_SET) != static_cast<off_t>(offset)) {
+    *err = android::base::StringPrintf("failed to lseek %s: %s", misc_blk_device.c_str(),
+                                       strerror(errno));
+    return false;
+  }
+  if (!android::base::WriteFully(fd.get(), p, size)) {
+    *err = android::base::StringPrintf("failed to write %s: %s", misc_blk_device.c_str(),
+                                       strerror(errno));
+    return false;
+  }
+
+  // TODO: O_SYNC and fsync duplicates each other?
+  if (fsync(fd.get()) == -1) {
+    *err = android::base::StringPrintf("failed to fsync %s: %s", misc_blk_device.c_str(),
+                                       strerror(errno));
+    return false;
+  }
+  return true;
+}
+
+bool read_bootloader_message(bootloader_message* boot, std::string* err) {
+  return read_misc_partition(boot, sizeof(*boot), BOOTLOADER_MESSAGE_OFFSET_IN_MISC, err);
+}
+
+bool write_bootloader_message(const bootloader_message& boot, std::string* err) {
+  return write_misc_partition(&boot, sizeof(boot), BOOTLOADER_MESSAGE_OFFSET_IN_MISC, err);
+}
+
+bool clear_bootloader_message(std::string* err) {
+  bootloader_message boot = {};
+  return write_bootloader_message(boot, err);
+}
+
+bool write_bootloader_message(const std::vector<std::string>& options, std::string* err) {
+  bootloader_message boot = {};
+  strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
+  strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
+  for (const auto& s : options) {
+    strlcat(boot.recovery, s.c_str(), sizeof(boot.recovery));
+    if (s.back() != '\n') {
+      strlcat(boot.recovery, "\n", sizeof(boot.recovery));
+    }
+  }
+  return write_bootloader_message(boot, err);
+}
+
+bool read_wipe_package(std::string* package_data, size_t size, std::string* err) {
+  package_data->resize(size);
+  return read_misc_partition(&(*package_data)[0], size, WIPE_PACKAGE_OFFSET_IN_MISC, err);
+}
+
+bool write_wipe_package(const std::string& package_data, std::string* err) {
+  return write_misc_partition(package_data.data(), package_data.size(),
+                              WIPE_PACKAGE_OFFSET_IN_MISC, err);
+}
+
+extern "C" bool write_bootloader_message(const char* options) {
+  std::string err;
+  return write_bootloader_message({options}, &err);
+}
diff --git a/bootloader_message/include/bootloader_message/bootloader_message.h b/bootloader_message/include/bootloader_message/bootloader_message.h
new file mode 100644
index 0000000..f343c64
--- /dev/null
+++ b/bootloader_message/include/bootloader_message/bootloader_message.h
@@ -0,0 +1,199 @@
+/*
+ * Copyright (C) 2008 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 _BOOTLOADER_MESSAGE_H
+#define _BOOTLOADER_MESSAGE_H
+
+#include <assert.h>
+#include <stddef.h>
+#include <stdint.h>
+
+// Spaces used by misc partition are as below:
+// 0   - 2K     For bootloader_message
+// 2K  - 16K    Used by Vendor's bootloader (the 2K - 4K range may be optionally used
+//              as bootloader_message_ab struct)
+// 16K - 64K    Used by uncrypt and recovery to store wipe_package for A/B devices
+// Note that these offsets are admitted by bootloader,recovery and uncrypt, so they
+// are not configurable without changing all of them.
+static const size_t BOOTLOADER_MESSAGE_OFFSET_IN_MISC = 0;
+static const size_t WIPE_PACKAGE_OFFSET_IN_MISC = 16 * 1024;
+
+/* Bootloader Message (2-KiB)
+ *
+ * This structure describes the content of a block in flash
+ * that is used for recovery and the bootloader to talk to
+ * each other.
+ *
+ * The command field is updated by linux when it wants to
+ * reboot into recovery or to update radio or bootloader firmware.
+ * It is also updated by the bootloader when firmware update
+ * is complete (to boot into recovery for any final cleanup)
+ *
+ * The status field is written by the bootloader after the
+ * completion of an "update-radio" or "update-hboot" command.
+ *
+ * The recovery field is only written by linux and used
+ * for the system to send a message to recovery or the
+ * other way around.
+ *
+ * The stage field is written by packages which restart themselves
+ * multiple times, so that the UI can reflect which invocation of the
+ * package it is.  If the value is of the format "#/#" (eg, "1/3"),
+ * the UI will add a simple indicator of that status.
+ *
+ * We used to have slot_suffix field for A/B boot control metadata in
+ * this struct, which gets unintentionally cleared by recovery or
+ * uncrypt. Move it into struct bootloader_message_ab to avoid the
+ * issue.
+ */
+struct bootloader_message {
+    char command[32];
+    char status[32];
+    char recovery[768];
+
+    // The 'recovery' field used to be 1024 bytes.  It has only ever
+    // been used to store the recovery command line, so 768 bytes
+    // should be plenty.  We carve off the last 256 bytes to store the
+    // stage string (for multistage packages) and possible future
+    // expansion.
+    char stage[32];
+
+    // The 'reserved' field used to be 224 bytes when it was initially
+    // carved off from the 1024-byte recovery field. Bump it up to
+    // 1184-byte so that the entire bootloader_message struct rounds up
+    // to 2048-byte.
+    char reserved[1184];
+};
+
+/**
+ * We must be cautious when changing the bootloader_message struct size,
+ * because A/B-specific fields may end up with different offsets.
+ */
+#if (__STDC_VERSION__ >= 201112L) || defined(__cplusplus)
+static_assert(sizeof(struct bootloader_message) == 2048,
+              "struct bootloader_message size changes, which may break A/B devices");
+#endif
+
+/**
+ * The A/B-specific bootloader message structure (4-KiB).
+ *
+ * We separate A/B boot control metadata from the regular bootloader
+ * message struct and keep it here. Everything that's A/B-specific
+ * stays after struct bootloader_message, which should be managed by
+ * the A/B-bootloader or boot control HAL.
+ *
+ * The slot_suffix field is used for A/B implementations where the
+ * bootloader does not set the androidboot.ro.boot.slot_suffix kernel
+ * commandline parameter. This is used by fs_mgr to mount /system and
+ * other partitions with the slotselect flag set in fstab. A/B
+ * implementations are free to use all 32 bytes and may store private
+ * data past the first NUL-byte in this field. It is encouraged, but
+ * not mandatory, to use 'struct bootloader_control' described below.
+ */
+struct bootloader_message_ab {
+    struct bootloader_message message;
+    char slot_suffix[32];
+
+    // Round up the entire struct to 4096-byte.
+    char reserved[2016];
+};
+
+/**
+ * Be cautious about the struct size change, in case we put anything post
+ * bootloader_message_ab struct (b/29159185).
+ */
+#if (__STDC_VERSION__ >= 201112L) || defined(__cplusplus)
+static_assert(sizeof(struct bootloader_message_ab) == 4096,
+              "struct bootloader_message_ab size changes");
+#endif
+
+#define BOOT_CTRL_MAGIC   0x42414342 /* Bootloader Control AB */
+#define BOOT_CTRL_VERSION 1
+
+struct slot_metadata {
+    // Slot priority with 15 meaning highest priority, 1 lowest
+    // priority and 0 the slot is unbootable.
+    uint8_t priority : 4;
+    // Number of times left attempting to boot this slot.
+    uint8_t tries_remaining : 3;
+    // 1 if this slot has booted successfully, 0 otherwise.
+    uint8_t successful_boot : 1;
+    // 1 if this slot is corrupted from a dm-verity corruption, 0
+    // otherwise.
+    uint8_t verity_corrupted : 1;
+    // Reserved for further use.
+    uint8_t reserved : 7;
+} __attribute__((packed));
+
+/* Bootloader Control AB
+ *
+ * This struct can be used to manage A/B metadata. It is designed to
+ * be put in the 'slot_suffix' field of the 'bootloader_message'
+ * structure described above. It is encouraged to use the
+ * 'bootloader_control' structure to store the A/B metadata, but not
+ * mandatory.
+ */
+struct bootloader_control {
+    // NUL terminated active slot suffix.
+    char slot_suffix[4];
+    // Bootloader Control AB magic number (see BOOT_CTRL_MAGIC).
+    uint32_t magic;
+    // Version of struct being used (see BOOT_CTRL_VERSION).
+    uint8_t version;
+    // Number of slots being managed.
+    uint8_t nb_slot : 3;
+    // Number of times left attempting to boot recovery.
+    uint8_t recovery_tries_remaining : 3;
+    // Ensure 4-bytes alignment for slot_info field.
+    uint8_t reserved0[2];
+    // Per-slot information.  Up to 4 slots.
+    struct slot_metadata slot_info[4];
+    // Reserved for further use.
+    uint8_t reserved1[8];
+    // CRC32 of all 28 bytes preceding this field (little endian
+    // format).
+    uint32_t crc32_le;
+} __attribute__((packed));
+
+#if (__STDC_VERSION__ >= 201112L) || defined(__cplusplus)
+static_assert(sizeof(struct bootloader_control) ==
+              sizeof(((struct bootloader_message_ab *)0)->slot_suffix),
+              "struct bootloader_control has wrong size");
+#endif
+
+#ifdef __cplusplus
+
+#include <string>
+#include <vector>
+
+bool read_bootloader_message(bootloader_message* boot, std::string* err);
+bool write_bootloader_message(const bootloader_message& boot, std::string* err);
+bool write_bootloader_message(const std::vector<std::string>& options, std::string* err);
+bool clear_bootloader_message(std::string* err);
+
+bool read_wipe_package(std::string* package_data, size_t size, std::string* err);
+bool write_wipe_package(const std::string& package_data, std::string* err);
+
+#else
+
+#include <stdbool.h>
+
+// C Interface.
+bool write_bootloader_message(const char* options);
+
+#endif  // ifdef __cplusplus
+
+#endif  // _BOOTLOADER_MESSAGE_H
diff --git a/device.cpp b/device.cpp
index 2465b07..f8fbb8a 100644
--- a/device.cpp
+++ b/device.cpp
@@ -16,6 +16,29 @@
 
 #include "device.h"
 
+#if defined(AB_OTA_UPDATER)
+
+static const char* MENU_ITEMS[] = {
+    "Reboot system now",
+    "Reboot to bootloader",
+    "Wipe data/factory reset",
+    "Mount /system",
+    "Run graphics test",
+    "Power off",
+    NULL,
+};
+
+static const Device::BuiltinAction MENU_ACTIONS[] = {
+    Device::REBOOT,
+    Device::REBOOT_BOOTLOADER,
+    Device::WIPE_DATA,
+    Device::MOUNT_SYSTEM,
+    Device::RUN_GRAPHICS_TEST,
+    Device::SHUTDOWN,
+};
+
+#else
+
 static const char* MENU_ITEMS[] = {
     "Reboot system now",
     "Reboot to bootloader",
@@ -27,27 +50,30 @@
     "View recovery logs",
     "Run graphics test",
     "Power off",
-    NULL
+    NULL,
 };
 
+static const Device::BuiltinAction MENU_ACTIONS[] = {
+    Device::REBOOT,
+    Device::REBOOT_BOOTLOADER,
+    Device::APPLY_ADB_SIDELOAD,
+    Device::APPLY_SDCARD,
+    Device::WIPE_DATA,
+    Device::WIPE_CACHE,
+    Device::MOUNT_SYSTEM,
+    Device::VIEW_RECOVERY_LOGS,
+    Device::RUN_GRAPHICS_TEST,
+    Device::SHUTDOWN,
+};
+
+#endif
+
 const char* const* Device::GetMenuItems() {
   return MENU_ITEMS;
 }
 
 Device::BuiltinAction Device::InvokeMenuItem(int menu_position) {
-  switch (menu_position) {
-    case 0: return REBOOT;
-    case 1: return REBOOT_BOOTLOADER;
-    case 2: return APPLY_ADB_SIDELOAD;
-    case 3: return APPLY_SDCARD;
-    case 4: return WIPE_DATA;
-    case 5: return WIPE_CACHE;
-    case 6: return MOUNT_SYSTEM;
-    case 7: return VIEW_RECOVERY_LOGS;
-    case 8: return RUN_GRAPHICS_TEST;
-    case 9: return SHUTDOWN;
-    default: return NO_ACTION;
-  }
+  return menu_position < 0 ? NO_ACTION : MENU_ACTIONS[menu_position];
 }
 
 int Device::HandleMenuKey(int key, int visible) {
diff --git a/install.cpp b/install.cpp
index 3d07290..015f8f6 100644
--- a/install.cpp
+++ b/install.cpp
@@ -68,20 +68,27 @@
     return -1;
 }
 
-// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
-static void read_source_target_build(ZipArchive* zip, std::vector<std::string>& log_buffer) {
+bool read_metadata_from_package(ZipArchive* zip, std::string* meta_data) {
     const ZipEntry* meta_entry = mzFindZipEntry(zip, METADATA_PATH);
     if (meta_entry == nullptr) {
         LOGE("Failed to find %s in update package.\n", METADATA_PATH);
-        return;
+        return false;
     }
 
-    std::string meta_data(meta_entry->uncompLen, '\0');
-    if (!mzReadZipEntry(zip, meta_entry, &meta_data[0], meta_entry->uncompLen)) {
+    meta_data->resize(meta_entry->uncompLen, '\0');
+    if (!mzReadZipEntry(zip, meta_entry, &(*meta_data)[0], meta_entry->uncompLen)) {
         LOGE("Failed to read metadata in update package.\n");
+        return false;
+    }
+    return true;
+}
+
+// Read the build.version.incremental of src/tgt from the metadata and log it to last_install.
+static void read_source_target_build(ZipArchive* zip, std::vector<std::string>& log_buffer) {
+    std::string meta_data;
+    if (!read_metadata_from_package(zip, &meta_data)) {
         return;
     }
-
     // Examples of the pre-build and post-build strings in metadata:
     // pre-build-incremental=2943039
     // post-build-incremental=2951741
@@ -298,31 +305,16 @@
         return INSTALL_CORRUPT;
     }
 
-    // Load keys.
-    std::vector<Certificate> loadedKeys;
-    if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
-        LOGE("Failed to load keys\n");
-        return INSTALL_CORRUPT;
-    }
-    LOGI("%zu key(s) loaded from %s\n", loadedKeys.size(), PUBLIC_KEYS_FILE);
-
     // Verify package.
-    ui->Print("Verifying update package...\n");
-    auto t0 = std::chrono::system_clock::now();
-    int err = verify_file(map.addr, map.length, loadedKeys);
-    std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
-    ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
-    if (err != VERIFY_SUCCESS) {
-        LOGE("signature verification failed\n");
+    if (!verify_package(map.addr, map.length)) {
         log_buffer.push_back(android::base::StringPrintf("error: %d", kZipVerificationFailure));
-
         sysReleaseMap(&map);
         return INSTALL_CORRUPT;
     }
 
     // Try to open the package.
     ZipArchive zip;
-    err = mzOpenZipArchive(map.addr, map.length, &zip);
+    int err = mzOpenZipArchive(map.addr, map.length, &zip);
     if (err != 0) {
         LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
         log_buffer.push_back(android::base::StringPrintf("error: %d", kZipOpenFailure));
@@ -385,3 +377,25 @@
     }
     return result;
 }
+
+bool verify_package(const unsigned char* package_data, size_t package_size) {
+    std::vector<Certificate> loadedKeys;
+    if (!load_keys(PUBLIC_KEYS_FILE, loadedKeys)) {
+        LOGE("Failed to load keys\n");
+        return false;
+    }
+    LOGI("%zu key(s) loaded from %s\n", loadedKeys.size(), PUBLIC_KEYS_FILE);
+
+    // Verify package.
+    ui->Print("Verifying update package...\n");
+    auto t0 = std::chrono::system_clock::now();
+    int err = verify_file(const_cast<unsigned char*>(package_data), package_size, loadedKeys);
+    std::chrono::duration<double> duration = std::chrono::system_clock::now() - t0;
+    ui->Print("Update package verification took %.1f s (result %d).\n", duration.count(), err);
+    if (err != VERIFY_SUCCESS) {
+        LOGE("Signature verification failed\n");
+        LOGE("error: %d\n", kZipVerificationFailure);
+        return false;
+    }
+    return true;
+}
diff --git a/install.h b/install.h
index 66764f5..14de225 100644
--- a/install.h
+++ b/install.h
@@ -17,11 +17,10 @@
 #ifndef RECOVERY_INSTALL_H_
 #define RECOVERY_INSTALL_H_
 
-#include "common.h"
+#include <string>
 
-#ifdef __cplusplus
-extern "C" {
-#endif
+#include "common.h"
+#include "minzip/Zip.h"
 
 enum { INSTALL_SUCCESS, INSTALL_ERROR, INSTALL_CORRUPT, INSTALL_NONE, INSTALL_SKIPPED,
         INSTALL_RETRY };
@@ -31,8 +30,12 @@
 int install_package(const char* root_path, bool* wipe_cache, const char* install_file,
                     bool needs_mount, int retry_count);
 
-#ifdef __cplusplus
-}
-#endif
+// Verify the package by ota keys. Return true if the package is verified successfully,
+// otherwise return false.
+bool verify_package(const unsigned char* package_data, size_t package_size);
+
+// Read meta data file of the package, write its content in the string pointed by meta_data.
+// Return true if succeed, otherwise return false.
+bool read_metadata_from_package(ZipArchive* zip, std::string* meta_data);
 
 #endif  // RECOVERY_INSTALL_H_
diff --git a/recovery.cpp b/recovery.cpp
index 467b335..c0f5a38 100644
--- a/recovery.cpp
+++ b/recovery.cpp
@@ -45,6 +45,7 @@
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
+#include <bootloader_message/bootloader_message.h>
 #include <cutils/android_reboot.h>
 #include <cutils/properties.h>
 #include <healthd/BatteryMonitor.h>
@@ -54,7 +55,6 @@
 #include <selinux/selinux.h>
 
 #include "adb_install.h"
-#include "bootloader.h"
 #include "common.h"
 #include "device.h"
 #include "error_code.h"
@@ -63,6 +63,7 @@
 #include "install.h"
 #include "minui/minui.h"
 #include "minzip/DirUtil.h"
+#include "minzip/Zip.h"
 #include "roots.h"
 #include "ui.h"
 #include "screen_ui.h"
@@ -83,7 +84,8 @@
   { "shutdown_after", no_argument, NULL, 'p' },
   { "reason", required_argument, NULL, 'r' },
   { "security", no_argument, NULL, 'e'},
-  { "brick", no_argument, NULL, 0 },
+  { "wipe_ab", no_argument, NULL, 0 },
+  { "wipe_package_size", required_argument, NULL, 0 },
   { NULL, 0, NULL, 0 },
 };
 
@@ -110,7 +112,7 @@
 // So we should check battery with a slightly lower limitation.
 static const int BATTERY_OK_PERCENTAGE = 20;
 static const int BATTERY_WITH_CHARGER_OK_PERCENTAGE = 15;
-constexpr const char* RECOVERY_BRICK = "/etc/recovery.brick";
+constexpr const char* RECOVERY_WIPE = "/etc/recovery.wipe";
 
 RecoveryUI* ui = NULL;
 static const char* locale = "en_US";
@@ -298,9 +300,13 @@
 //   - the contents of COMMAND_FILE (one per line)
 static void
 get_args(int *argc, char ***argv) {
-    struct bootloader_message boot;
-    memset(&boot, 0, sizeof(boot));
-    get_bootloader_message(&boot);  // this may fail, leaving a zeroed structure
+    bootloader_message boot = {};
+    std::string err;
+    if (!read_bootloader_message(&boot, &err)) {
+        LOGE("%s\n", err.c_str());
+        // If fails, leave a zeroed bootloader_message.
+        memset(&boot, 0, sizeof(boot));
+    }
     stage = strndup(boot.stage, sizeof(boot.stage));
 
     if (boot.command[0] != 0 && boot.command[0] != 255) {
@@ -362,16 +368,20 @@
         strlcat(boot.recovery, (*argv)[i], sizeof(boot.recovery));
         strlcat(boot.recovery, "\n", sizeof(boot.recovery));
     }
-    set_bootloader_message(&boot);
+    if (!write_bootloader_message(boot, &err)) {
+        LOGE("%s\n", err.c_str());
+    }
 }
 
 static void
 set_sdcard_update_bootloader_message() {
-    struct bootloader_message boot;
-    memset(&boot, 0, sizeof(boot));
+    bootloader_message boot = {};
     strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
     strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
-    set_bootloader_message(&boot);
+    std::string err;
+    if (!write_bootloader_message(boot, &err)) {
+        LOGE("%s\n", err.c_str());
+    }
 }
 
 // Read from kernel log into buffer and write out to file.
@@ -520,9 +530,11 @@
     copy_logs();
 
     // Reset to normal system boot so recovery won't cycle indefinitely.
-    struct bootloader_message boot;
-    memset(&boot, 0, sizeof(boot));
-    set_bootloader_message(&boot);
+    bootloader_message boot = {};
+    std::string err;
+    if (!write_bootloader_message(boot, &err)) {
+        LOGE("%s\n", err.c_str());
+    }
 
     // Remove the command file, so recovery won't repeat indefinitely.
     if (has_cache) {
@@ -890,15 +902,79 @@
     return true;
 }
 
-// Brick the current device, with a secure wipe of all the partitions in
-// RECOVERY_BRICK.
-static bool brick_device() {
+// Check if the wipe package matches expectation:
+// 1. verify the package.
+// 2. check metadata (ota-type, pre-device and serial number if having one).
+static bool check_wipe_package(size_t wipe_package_size) {
+    if (wipe_package_size == 0) {
+        LOGE("wipe_package_size is zero.\n");
+        return false;
+    }
+    std::string wipe_package;
+    std::string err_str;
+    if (!read_wipe_package(&wipe_package, wipe_package_size, &err_str)) {
+        LOGE("Failed to read wipe package: %s\n", err_str.c_str());
+        return false;
+    }
+    if (!verify_package(reinterpret_cast<const unsigned char*>(wipe_package.data()),
+                        wipe_package.size())) {
+        LOGE("Failed to verify package.\n");
+        return false;
+    }
+
+    // Extract metadata
+    ZipArchive zip;
+    int err = mzOpenZipArchive(reinterpret_cast<unsigned char*>(&wipe_package[0]),
+                               wipe_package.size(), &zip);
+    if (err != 0) {
+        LOGE("Can't open wipe package: %s\n", err != -1 ? strerror(err) : "bad");
+        return false;
+    }
+    std::string metadata;
+    if (!read_metadata_from_package(&zip, &metadata)) {
+        mzCloseZipArchive(&zip);
+        return false;
+    }
+    mzCloseZipArchive(&zip);
+
+    // Check metadata
+    std::vector<std::string> lines = android::base::Split(metadata, "\n");
+    bool ota_type_matched = false;
+    bool device_type_matched = false;
+    bool has_serial_number = false;
+    bool serial_number_matched = false;
+    for (const auto& line : lines) {
+        if (line == "ota-type=BRICK") {
+            ota_type_matched = true;
+        } else if (android::base::StartsWith(line, "pre-device=")) {
+            std::string device_type = line.substr(strlen("pre-device="));
+            char real_device_type[PROPERTY_VALUE_MAX];
+            property_get("ro.build.product", real_device_type, "");
+            device_type_matched = (device_type == real_device_type);
+        } else if (android::base::StartsWith(line, "serialno=")) {
+            std::string serial_no = line.substr(strlen("serialno="));
+            char real_serial_no[PROPERTY_VALUE_MAX];
+            property_get("ro.serialno", real_serial_no, "");
+            has_serial_number = true;
+            serial_number_matched = (serial_no == real_serial_no);
+        }
+    }
+    return ota_type_matched && device_type_matched && (!has_serial_number || serial_number_matched);
+}
+
+// Wipe the current A/B device, with a secure wipe of all the partitions in
+// RECOVERY_WIPE.
+static bool wipe_ab_device(size_t wipe_package_size) {
     ui->SetBackground(RecoveryUI::ERASING);
     ui->SetProgressType(RecoveryUI::INDETERMINATE);
 
+    if (!check_wipe_package(wipe_package_size)) {
+        LOGE("Failed to verify wipe package\n");
+        return false;
+    }
     std::string partition_list;
-    if (!android::base::ReadFileToString(RECOVERY_BRICK, &partition_list)) {
-        LOGE("failed to read \"%s\".\n", RECOVERY_BRICK);
+    if (!android::base::ReadFileToString(RECOVERY_WIPE, &partition_list)) {
+        LOGE("failed to read \"%s\".\n", RECOVERY_WIPE);
         return false;
     }
 
@@ -1289,7 +1365,7 @@
 }
 
 static void set_retry_bootloader_message(int retry_count, int argc, char** argv) {
-    struct bootloader_message boot {};
+    bootloader_message boot = {};
     strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
     strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
 
@@ -1308,7 +1384,10 @@
         snprintf(buffer, sizeof(buffer), "--retry_count=%d\n", retry_count+1);
         strlcat(boot.recovery, buffer, sizeof(boot.recovery));
     }
-    set_bootloader_message(&boot);
+    std::string err;
+    if (!write_bootloader_message(boot, &err)) {
+        LOGE("%s\n", err.c_str());
+    }
 }
 
 static ssize_t logbasename(
@@ -1402,7 +1481,8 @@
     const char *update_package = NULL;
     bool should_wipe_data = false;
     bool should_wipe_cache = false;
-    bool should_brick = false;
+    bool should_wipe_ab = false;
+    size_t wipe_package_size = 0;
     bool show_text = false;
     bool sideload = false;
     bool sideload_auto_reboot = false;
@@ -1436,8 +1516,11 @@
         case 'r': reason = optarg; break;
         case 'e': security_update = true; break;
         case 0: {
-            if (strcmp(OPTIONS[option_index].name, "brick") == 0) {
-                should_brick = true;
+            if (strcmp(OPTIONS[option_index].name, "wipe_ab") == 0) {
+                should_wipe_ab = true;
+                break;
+            } else if (strcmp(OPTIONS[option_index].name, "wipe_package_size") == 0) {
+                android::base::ParseUint(optarg, &wipe_package_size);
                 break;
             }
             break;
@@ -1580,8 +1663,8 @@
         if (!wipe_cache(false, device)) {
             status = INSTALL_ERROR;
         }
-    } else if (should_brick) {
-        if (!brick_device()) {
+    } else if (should_wipe_ab) {
+        if (!wipe_ab_device(wipe_package_size)) {
             status = INSTALL_ERROR;
         }
     } else if (sideload) {
diff --git a/uncrypt/Android.mk b/uncrypt/Android.mk
index 09cfdfc..bb276ed 100644
--- a/uncrypt/Android.mk
+++ b/uncrypt/Android.mk
@@ -15,15 +15,6 @@
 LOCAL_PATH := $(call my-dir)
 
 include $(CLEAR_VARS)
-LOCAL_CLANG := true
-LOCAL_SRC_FILES := bootloader_message_writer.cpp
-LOCAL_MODULE := libbootloader_message_writer
-LOCAL_STATIC_LIBRARIES := libbase libfs_mgr
-LOCAL_C_INCLUDES := $(LOCAL_PATH)/..
-LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
-include $(BUILD_STATIC_LIBRARY)
-
-include $(CLEAR_VARS)
 
 LOCAL_CLANG := true
 
@@ -33,7 +24,7 @@
 
 LOCAL_MODULE := uncrypt
 
-LOCAL_STATIC_LIBRARIES := libbootloader_message_writer libbase \
+LOCAL_STATIC_LIBRARIES := libbootloader_message libbase \
                           liblog libfs_mgr libcutils \
 
 LOCAL_INIT_RC := uncrypt.rc
diff --git a/uncrypt/bootloader_message_writer.cpp b/uncrypt/bootloader_message_writer.cpp
deleted file mode 100644
index 3bb106a..0000000
--- a/uncrypt/bootloader_message_writer.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <string.h>
-#include <sys/system_properties.h>
-
-#include <string>
-#include <vector>
-
-#include <android-base/file.h>
-#include <android-base/stringprintf.h>
-#include <android-base/unique_fd.h>
-#include <fs_mgr.h>
-
-#include "bootloader.h"
-
-static struct fstab* read_fstab(std::string* err) {
-  // The fstab path is always "/fstab.${ro.hardware}".
-  std::string fstab_path = "/fstab.";
-  char value[PROP_VALUE_MAX];
-  if (__system_property_get("ro.hardware", value) == 0) {
-    *err = "failed to get ro.hardware";
-    return nullptr;
-  }
-  fstab_path += value;
-  struct fstab* fstab = fs_mgr_read_fstab(fstab_path.c_str());
-  if (fstab == nullptr) {
-    *err = "failed to read " + fstab_path;
-  }
-  return fstab;
-}
-
-static std::string get_misc_blk_device(std::string* err) {
-  struct fstab* fstab = read_fstab(err);
-  if (fstab == nullptr) {
-    return "";
-  }
-  fstab_rec* record = fs_mgr_get_entry_for_mount_point(fstab, "/misc");
-  if (record == nullptr) {
-    *err = "failed to find /misc partition";
-    return "";
-  }
-  return record->blk_device;
-}
-
-static bool write_bootloader_message(const bootloader_message& boot, std::string* err) {
-  std::string misc_blk_device = get_misc_blk_device(err);
-  if (misc_blk_device.empty()) {
-    return false;
-  }
-  android::base::unique_fd fd(open(misc_blk_device.c_str(), O_WRONLY | O_SYNC));
-  if (fd.get() == -1) {
-    *err = android::base::StringPrintf("failed to open %s: %s", misc_blk_device.c_str(),
-                                       strerror(errno));
-    return false;
-  }
-  if (!android::base::WriteFully(fd.get(), &boot, sizeof(boot))) {
-    *err = android::base::StringPrintf("failed to write %s: %s", misc_blk_device.c_str(),
-                                       strerror(errno));
-    return false;
-  }
-  // TODO: O_SYNC and fsync duplicates each other?
-  if (fsync(fd.get()) == -1) {
-    *err = android::base::StringPrintf("failed to fsync %s: %s", misc_blk_device.c_str(),
-                                       strerror(errno));
-    return false;
-  }
-  return true;
-}
-
-bool clear_bootloader_message(std::string* err) {
-  bootloader_message boot = {};
-  return write_bootloader_message(boot, err);
-}
-
-bool write_bootloader_message(const std::vector<std::string>& options, std::string* err) {
-  bootloader_message boot = {};
-  strlcpy(boot.command, "boot-recovery", sizeof(boot.command));
-  strlcpy(boot.recovery, "recovery\n", sizeof(boot.recovery));
-  for (const auto& s : options) {
-    strlcat(boot.recovery, s.c_str(), sizeof(boot.recovery));
-    if (s.back() != '\n') {
-      strlcat(boot.recovery, "\n", sizeof(boot.recovery));
-    }
-  }
-  return write_bootloader_message(boot, err);
-}
-
-extern "C" bool write_bootloader_message(const char* options) {
-  std::string err;
-  return write_bootloader_message({options}, &err);
-}
diff --git a/uncrypt/include/bootloader_message_writer.h b/uncrypt/include/bootloader_message_writer.h
deleted file mode 100644
index e0ca3f4..0000000
--- a/uncrypt/include/bootloader_message_writer.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef BOOTLOADER_MESSAGE_WRITER_H
-#define BOOTLOADER_MESSAGE_WRITER_H
-
-#ifdef __cplusplus
-#include <string>
-#include <vector>
-
-bool clear_bootloader_message(std::string* err);
-
-bool write_bootloader_message(const std::vector<std::string>& options, std::string* err);
-
-#else
-#include <stdbool.h>
-
-// C Interface.
-bool write_bootloader_message(const char* options);
-#endif
-
-#endif  // BOOTLOADER_MESSAGE_WRITER_H
diff --git a/uncrypt/uncrypt.cpp b/uncrypt/uncrypt.cpp
index 5697712..c19943f 100644
--- a/uncrypt/uncrypt.cpp
+++ b/uncrypt/uncrypt.cpp
@@ -110,7 +110,7 @@
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
 #include <android-base/unique_fd.h>
-#include <bootloader_message_writer.h>
+#include <bootloader_message/bootloader_message.h>
 #include <cutils/android_reboot.h>
 #include <cutils/properties.h>
 #include <cutils/sockets.h>
@@ -501,14 +501,31 @@
         return false;
     }
     ALOGI("  received command: [%s] (%zu)", content.c_str(), content.size());
+    std::vector<std::string> options = android::base::Split(content, "\n");
+    std::string wipe_package;
+    for (auto& option : options) {
+        if (android::base::StartsWith(option, "--wipe_package=")) {
+            std::string path = option.substr(strlen("--wipe_package="));
+            if (!android::base::ReadFileToString(path, &wipe_package)) {
+                ALOGE("failed to read %s: %s", path.c_str(), strerror(errno));
+                return false;
+            }
+            option = android::base::StringPrintf("--wipe_package_size=%zu", wipe_package.size());
+        }
+    }
 
     // c8. setup the bcb command
     std::string err;
-    if (!write_bootloader_message({content}, &err)) {
+    if (!write_bootloader_message(options, &err)) {
         ALOGE("failed to set bootloader message: %s", err.c_str());
         write_status_to_socket(-1, socket);
         return false;
     }
+    if (!wipe_package.empty() && !write_wipe_package(wipe_package, &err)) {
+        ALOGE("failed to set wipe package: %s", err.c_str());
+        write_status_to_socket(-1, socket);
+        return false;
+    }
     // c10. send "100" status
     write_status_to_socket(100, socket);
     return true;