Increase EIO retry count
am: c37c5c3410

Change-Id: I163541137bf8c421276383855d36ab127d2ddf95
diff --git a/Android.mk b/Android.mk
index 65d123a..9a064f2 100644
--- a/Android.mk
+++ b/Android.mk
@@ -93,6 +93,10 @@
     LOCAL_STATIC_LIBRARIES += libext4_utils_static libz
 endif
 
+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),)
diff --git a/bootloader.cpp b/bootloader.cpp
index d80c5e7..f6c0e93 100644
--- a/bootloader.cpp
+++ b/bootloader.cpp
@@ -25,6 +25,8 @@
 
 #include <fs_mgr.h>
 
+#include <android-base/file.h>
+
 #include "bootloader.h"
 #include "common.h"
 #include "mtdutils/mtdutils.h"
@@ -33,8 +35,8 @@
 
 static int get_bootloader_message_mtd(bootloader_message* out, const Volume* v);
 static int set_bootloader_message_mtd(const bootloader_message* in, const Volume* v);
-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);
+static bool read_misc_partition(const Volume* v, size_t offset, size_t size, std::string* out);
+static bool write_misc_partition(const Volume* v, size_t offset, const std::string& in);
 
 int get_bootloader_message(bootloader_message* out) {
     Volume* v = volume_for_path("/misc");
@@ -45,12 +47,34 @@
     if (strcmp(v->fs_type, "mtd") == 0) {
         return get_bootloader_message_mtd(out, v);
     } else if (strcmp(v->fs_type, "emmc") == 0) {
-        return get_bootloader_message_block(out, v);
+        std::string s;
+        if (!read_misc_partition(v, BOOTLOADER_MESSAGE_OFFSET_IN_MISC, sizeof(bootloader_message),
+                                 &s)) {
+            return -1;
+        }
+        memcpy(out, s.data(), s.size());
+        return 0;
     }
-    LOGE("unknown misc partition fs_type \"%s\"\n", v->fs_type);
+    LOGE("Unknown misc partition fs_type \"%s\"\n", v->fs_type);
     return -1;
 }
 
+bool read_wipe_package(size_t size, std::string* out) {
+    Volume* v = volume_for_path("/misc");
+    if (v == nullptr) {
+        LOGE("Cannot load volume /misc!\n");
+        return false;
+    }
+    if (strcmp(v->fs_type, "mtd") == 0) {
+        LOGE("Read wipe package on mtd is not supported.\n");
+        return false;
+    } else if (strcmp(v->fs_type, "emmc") == 0) {
+        return read_misc_partition(v, WIPE_PACKAGE_OFFSET_IN_MISC, size, out);
+    }
+    LOGE("Unknown misc partition fs_type \"%s\"\n", v->fs_type);
+    return false;
+}
+
 int set_bootloader_message(const bootloader_message* in) {
     Volume* v = volume_for_path("/misc");
     if (v == nullptr) {
@@ -60,9 +84,11 @@
     if (strcmp(v->fs_type, "mtd") == 0) {
         return set_bootloader_message_mtd(in, v);
     } else if (strcmp(v->fs_type, "emmc") == 0) {
-        return set_bootloader_message_block(in, v);
+        std::string s(reinterpret_cast<const char*>(in), sizeof(*in));
+        bool success = write_misc_partition(v, BOOTLOADER_MESSAGE_OFFSET_IN_MISC, s);
+        return success ? 0 : -1;
     }
-    LOGE("unknown misc partition fs_type \"%s\"\n", v->fs_type);
+    LOGE("Unknown misc partition fs_type \"%s\"\n", v->fs_type);
     return -1;
 }
 
@@ -166,53 +192,44 @@
     }
 }
 
-static int get_bootloader_message_block(bootloader_message* out,
-                                        const Volume* v) {
+static bool read_misc_partition(const Volume* v, size_t offset, size_t size, std::string* out) {
     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;
+    unique_fd fd(open(v->blk_device, O_RDONLY));
+    if (fd.get() == -1) {
+        LOGE("Failed to open \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-    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 (lseek(fd.get(), static_cast<off_t>(offset), SEEK_SET) != static_cast<off_t>(offset)) {
+        LOGE("Failed to lseek \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-    if (fclose(f) != 0) {
-        LOGE("failed to close \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
+    out->resize(size);
+    if (!android::base::ReadFully(fd.get(), &(*out)[0], size)) {
+        LOGE("Failed to read \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-    memcpy(out, &temp, sizeof(temp));
-    return 0;
+    return true;
 }
 
-static int set_bootloader_message_block(const bootloader_message* in,
-                                        const Volume* v) {
+static bool write_misc_partition(const Volume* v, size_t offset, const std::string& in) {
     wait_for_device(v->blk_device);
     unique_fd fd(open(v->blk_device, O_WRONLY | O_SYNC));
     if (fd.get() == -1) {
-        LOGE("failed to open \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
+        LOGE("Failed to open \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-
-    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.get(), 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 (lseek(fd.get(), static_cast<off_t>(offset), SEEK_SET) != static_cast<off_t>(offset)) {
+        LOGE("Failed to lseek \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
+    }
+    if (!android::base::WriteFully(fd.get(), in.data(), in.size())) {
+        LOGE("Failed to write \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
 
     if (fsync(fd.get()) == -1) {
-        LOGE("failed to fsync \"%s\": %s\n", v->blk_device, strerror(errno));
-        return -1;
+        LOGE("Failed to fsync \"%s\": %s\n", v->blk_device, strerror(errno));
+        return false;
     }
-    return 0;
+    return true;
 }
diff --git a/bootloader.h b/bootloader.h
index 742a4ab..88d54a5 100644
--- a/bootloader.h
+++ b/bootloader.h
@@ -17,6 +17,17 @@
 #ifndef _RECOVERY_BOOTLOADER_H
 #define _RECOVERY_BOOTLOADER_H
 
+#include <stddef.h>
+
+// Spaces used by misc partition are as below:
+// 0   - 2K     Bootloader Message
+// 2K  - 16K    Used by Vendor's bootloader
+// 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
  *
  * This structure describes the content of a block in flash
@@ -68,4 +79,11 @@
 int get_bootloader_message(struct bootloader_message *out);
 int set_bootloader_message(const struct bootloader_message *in);
 
+#ifdef __cplusplus
+
+#include <string>
+
+bool read_wipe_package(size_t size, std::string* out);
+#endif
+
 #endif
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 5a439a1..518337f 100644
--- a/install.cpp
+++ b/install.cpp
@@ -70,20 +70,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
@@ -300,31 +307,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));
@@ -387,3 +379,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 10f8414..98148af 100644
--- a/recovery.cpp
+++ b/recovery.cpp
@@ -19,7 +19,9 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <getopt.h>
+#include <inttypes.h>
 #include <limits.h>
+#include <linux/fs.h>
 #include <linux/input.h>
 #include <stdarg.h>
 #include <stdio.h>
@@ -33,12 +35,15 @@
 #include <unistd.h>
 
 #include <chrono>
+#include <string>
+#include <vector>
 
 #include <adb.h>
 #include <android/log.h> /* Android Log Priority Tags */
 #include <android-base/file.h>
 #include <android-base/parseint.h>
 #include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 #include <cutils/android_reboot.h>
 #include <cutils/properties.h>
 #include <log/logger.h> /* Android Log packet format */
@@ -56,8 +61,10 @@
 #include "install.h"
 #include "minui/minui.h"
 #include "minzip/DirUtil.h"
+#include "minzip/Zip.h"
 #include "roots.h"
 #include "ui.h"
+#include "unique_fd.h"
 #include "screen_ui.h"
 
 struct selabel_handle *sehandle;
@@ -77,6 +84,8 @@
   { "shutdown_after", no_argument, NULL, 'p' },
   { "reason", required_argument, NULL, 'r' },
   { "security", no_argument, NULL, 'e'},
+  { "wipe_ab", no_argument, NULL, 0 },
+  { "wipe_package_size", required_argument, NULL, 0 },
   { NULL, 0, NULL, 0 },
 };
 
@@ -104,6 +113,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_WIPE = "/etc/recovery.wipe";
 
 RecoveryUI* ui = NULL;
 static const char* locale = "en_US";
@@ -854,6 +864,138 @@
     return success;
 }
 
+// Secure-wipe a given partition. It uses BLKSECDISCARD, if supported.
+// Otherwise, it goes with BLKDISCARD (if device supports BLKDISCARDZEROES) or
+// BLKZEROOUT.
+static bool secure_wipe_partition(const std::string& partition) {
+    unique_fd fd(TEMP_FAILURE_RETRY(open(partition.c_str(), O_WRONLY)));
+    if (fd.get() == -1) {
+        LOGE("failed to open \"%s\": %s\n", partition.c_str(), strerror(errno));
+        return false;
+    }
+
+    uint64_t range[2] = {0, 0};
+    if (ioctl(fd.get(), BLKGETSIZE64, &range[1]) == -1 || range[1] == 0) {
+        LOGE("failed to get partition size: %s\n", strerror(errno));
+        return false;
+    }
+    printf("Secure-wiping \"%s\" from %" PRIu64 " to %" PRIu64 ".\n",
+           partition.c_str(), range[0], range[1]);
+
+    printf("Trying BLKSECDISCARD...\t");
+    if (ioctl(fd.get(), BLKSECDISCARD, &range) == -1) {
+        printf("failed: %s\n", strerror(errno));
+
+        // Use BLKDISCARD if it zeroes out blocks, otherwise use BLKZEROOUT.
+        unsigned int zeroes;
+        if (ioctl(fd.get(), BLKDISCARDZEROES, &zeroes) == 0 && zeroes != 0) {
+            printf("Trying BLKDISCARD...\t");
+            if (ioctl(fd.get(), BLKDISCARD, &range) == -1) {
+                printf("failed: %s\n", strerror(errno));
+                return false;
+            }
+        } else {
+            printf("Trying BLKZEROOUT...\t");
+            if (ioctl(fd.get(), BLKZEROOUT, &range) == -1) {
+                printf("failed: %s\n", strerror(errno));
+                return false;
+            }
+        }
+    }
+
+    printf("done\n");
+    return true;
+}
+
+// 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;
+    if (!read_wipe_package(wipe_package_size, &wipe_package)) {
+        LOGE("Failed to read wipe package.\n");
+        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_WIPE, &partition_list)) {
+        LOGE("failed to read \"%s\".\n", RECOVERY_WIPE);
+        return false;
+    }
+
+    std::vector<std::string> lines = android::base::Split(partition_list, "\n");
+    for (const std::string& line : lines) {
+        std::string partition = android::base::Trim(line);
+        // Ignore '#' comment or empty lines.
+        if (android::base::StartsWith(partition, "#") || partition.empty()) {
+            continue;
+        }
+
+        // Proceed anyway even if it fails to wipe some partition.
+        secure_wipe_partition(partition);
+    }
+    return true;
+}
+
 static void choose_recovery_file(Device* device) {
     if (!has_cache) {
         ui->Print("No /cache partition found.\n");
@@ -1341,6 +1483,8 @@
     const char *update_package = NULL;
     bool should_wipe_data = false;
     bool should_wipe_cache = false;
+    bool should_wipe_ab = false;
+    size_t wipe_package_size = 0;
     bool show_text = false;
     bool sideload = false;
     bool sideload_auto_reboot = false;
@@ -1350,7 +1494,8 @@
     bool security_update = false;
 
     int arg;
-    while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
+    int option_index;
+    while ((arg = getopt_long(argc, argv, "", OPTIONS, &option_index)) != -1) {
         switch (arg) {
         case 'i': send_intent = optarg; break;
         case 'n': android::base::ParseInt(optarg, &retry_count, 0); break;
@@ -1373,6 +1518,16 @@
         case 'p': shutdown_after = true; break;
         case 'r': reason = optarg; break;
         case 'e': security_update = true; break;
+        case 0: {
+            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;
+        }
         case '?':
             LOGE("Invalid command argument\n");
             continue;
@@ -1511,6 +1666,10 @@
         if (!wipe_cache(false, device)) {
             status = INSTALL_ERROR;
         }
+    } else if (should_wipe_ab) {
+        if (!wipe_ab_device(wipe_package_size)) {
+            status = INSTALL_ERROR;
+        }
     } else if (sideload) {
         // 'adb reboot sideload' acts the same as user presses key combinations
         // to enter the sideload mode. When 'sideload-auto-reboot' is used, text
diff --git a/tools/recovery_l10n/res/values-b+sr+Latn/strings.xml b/tools/recovery_l10n/res/values-b+sr+Latn/strings.xml
index c2d8f22..6f433e3 100644
--- a/tools/recovery_l10n/res/values-b+sr+Latn/strings.xml
+++ b/tools/recovery_l10n/res/values-b+sr+Latn/strings.xml
@@ -1,9 +1,9 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="recovery_installing" msgid="2013591905463558223">"Ažuriranje sistema se instalira"</string>
-    <string name="recovery_erasing" msgid="7334826894904037088">"Briše se"</string>
-    <string name="recovery_no_command" msgid="4465476568623024327">"Nema komande"</string>
+    <string name="recovery_installing" msgid="4995089002339765600">"Instaliranje ažuriranja sistema..."</string>
+    <string name="recovery_erasing" msgid="3454811999717520920">"Brisanje..."</string>
+    <string name="recovery_no_command" msgid="3005798864326873414">"Nema komande."</string>
     <string name="recovery_error" msgid="5748178989622716736">"Greška!"</string>
-    <string name="recovery_installing_security" msgid="9184031299717114342">"Instalira se bezbednosno ažuriranje"</string>
+    <string name="recovery_installing_security" msgid="241961948312007086">"Instalira se bezbednosno ažuriranje…"</string>
 </resources>
diff --git a/tools/recovery_l10n/res/values-be-rBY/strings.xml b/tools/recovery_l10n/res/values-be-rBY/strings.xml
index 7c0954d..5decf81 100644
--- a/tools/recovery_l10n/res/values-be-rBY/strings.xml
+++ b/tools/recovery_l10n/res/values-be-rBY/strings.xml
@@ -1,9 +1,9 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="recovery_installing" msgid="2013591905463558223">"Усталёўка абнаўлення сістэмы"</string>
-    <string name="recovery_erasing" msgid="7334826894904037088">"Сціранне"</string>
-    <string name="recovery_no_command" msgid="4465476568623024327">"Няма каманды"</string>
+    <string name="recovery_installing" msgid="4995089002339765600">"Усталёўка абнаўлення сістэмы..."</string>
+    <string name="recovery_erasing" msgid="3454811999717520920">"Выдаленне..."</string>
+    <string name="recovery_no_command" msgid="3005798864326873414">"Няма каманды"</string>
     <string name="recovery_error" msgid="5748178989622716736">"Памылка"</string>
-    <string name="recovery_installing_security" msgid="9184031299717114342">"Усталёўка абнаўлення сістэмы бяспекі"</string>
+    <string name="recovery_installing_security" msgid="241961948312007086">"Усталёўка абнаўлення сістэмы бяспекі..."</string>
 </resources>
diff --git a/tools/recovery_l10n/res/values-bs-rBA/strings.xml b/tools/recovery_l10n/res/values-bs-rBA/strings.xml
index 412cf02..8b6202a 100644
--- a/tools/recovery_l10n/res/values-bs-rBA/strings.xml
+++ b/tools/recovery_l10n/res/values-bs-rBA/strings.xml
@@ -1,9 +1,9 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="recovery_installing" msgid="2013591905463558223">"Ažuriranje sistema…"</string>
-    <string name="recovery_erasing" msgid="7334826894904037088">"Brisanje u toku"</string>
-    <string name="recovery_no_command" msgid="4465476568623024327">"Nema komande"</string>
+    <string name="recovery_installing" msgid="4995089002339765600">"Sistem se ažurira…"</string>
+    <string name="recovery_erasing" msgid="3454811999717520920">"Briše se…"</string>
+    <string name="recovery_no_command" msgid="3005798864326873414">"Nema komande."</string>
     <string name="recovery_error" msgid="5748178989622716736">"Greška!"</string>
-    <string name="recovery_installing_security" msgid="9184031299717114342">"Instaliranje sigurnosnog ažuriranja…"</string>
+    <string name="recovery_installing_security" msgid="241961948312007086">"Instaliranje sigurnosnog ažuriranja…"</string>
 </resources>
diff --git a/uncrypt/bootloader_message_writer.cpp b/uncrypt/bootloader_message_writer.cpp
index 3bb106a..42df31e 100644
--- a/uncrypt/bootloader_message_writer.cpp
+++ b/uncrypt/bootloader_message_writer.cpp
@@ -58,7 +58,7 @@
   return record->blk_device;
 }
 
-static bool write_bootloader_message(const bootloader_message& boot, std::string* err) {
+static bool write_misc_partition(const void* p, size_t size, size_t misc_offset, std::string* err) {
   std::string misc_blk_device = get_misc_blk_device(err);
   if (misc_blk_device.empty()) {
     return false;
@@ -69,11 +69,18 @@
                                        strerror(errno));
     return false;
   }
-  if (!android::base::WriteFully(fd.get(), &boot, sizeof(boot))) {
+  if (lseek(fd.get(), static_cast<off_t>(misc_offset), SEEK_SET) !=
+      static_cast<off_t>(misc_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(),
@@ -83,6 +90,10 @@
   return true;
 }
 
+static 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);
@@ -101,6 +112,11 @@
   return write_bootloader_message(boot, 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/uncrypt/include/bootloader_message_writer.h b/uncrypt/include/bootloader_message_writer.h
index e0ca3f4..1344bc8 100644
--- a/uncrypt/include/bootloader_message_writer.h
+++ b/uncrypt/include/bootloader_message_writer.h
@@ -24,6 +24,7 @@
 bool clear_bootloader_message(std::string* err);
 
 bool write_bootloader_message(const std::vector<std::string>& options, std::string* err);
+bool write_wipe_package(const std::string& package_data, std::string* err);
 
 #else
 #include <stdbool.h>
diff --git a/uncrypt/uncrypt.cpp b/uncrypt/uncrypt.cpp
index d7105a0..f62d132 100644
--- a/uncrypt/uncrypt.cpp
+++ b/uncrypt/uncrypt.cpp
@@ -503,14 +503,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;