Home | History | Annotate | Download | only in fastboot
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  *  * Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  *  * Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in
     12  *    the documentation and/or other materials provided with the
     13  *    distribution.
     14  *
     15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
     19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
     22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  */
     28 
     29 #include <ctype.h>
     30 #include <errno.h>
     31 #include <fcntl.h>
     32 #include <getopt.h>
     33 #include <inttypes.h>
     34 #include <limits.h>
     35 #include <stdint.h>
     36 #include <stdio.h>
     37 #include <stdlib.h>
     38 #include <string.h>
     39 #include <sys/stat.h>
     40 #include <sys/time.h>
     41 #include <sys/types.h>
     42 #include <unistd.h>
     43 
     44 #include <chrono>
     45 #include <functional>
     46 #include <thread>
     47 #include <utility>
     48 #include <vector>
     49 
     50 #include <android-base/file.h>
     51 #include <android-base/macros.h>
     52 #include <android-base/parseint.h>
     53 #include <android-base/parsenetaddress.h>
     54 #include <android-base/stringprintf.h>
     55 #include <android-base/strings.h>
     56 #include <android-base/test_utils.h>
     57 #include <android-base/unique_fd.h>
     58 #include <sparse/sparse.h>
     59 #include <ziparchive/zip_archive.h>
     60 
     61 #include "bootimg_utils.h"
     62 #include "diagnose_usb.h"
     63 #include "fastboot.h"
     64 #include "fs.h"
     65 #include "tcp.h"
     66 #include "transport.h"
     67 #include "udp.h"
     68 #include "usb.h"
     69 
     70 using android::base::unique_fd;
     71 
     72 #ifndef O_BINARY
     73 #define O_BINARY 0
     74 #endif
     75 
     76 char cur_product[FB_RESPONSE_SZ + 1];
     77 
     78 static const char* serial = nullptr;
     79 static const char* cmdline = nullptr;
     80 static unsigned short vendor_id = 0;
     81 static int long_listing = 0;
     82 // Don't resparse files in too-big chunks.
     83 // libsparse will support INT_MAX, but this results in large allocations, so
     84 // let's keep it at 1GB to avoid memory pressure on the host.
     85 static constexpr int64_t RESPARSE_LIMIT = 1 * 1024 * 1024 * 1024;
     86 static int64_t sparse_limit = -1;
     87 static int64_t target_sparse_limit = -1;
     88 
     89 static unsigned page_size = 2048;
     90 static unsigned base_addr      = 0x10000000;
     91 static unsigned kernel_offset  = 0x00008000;
     92 static unsigned ramdisk_offset = 0x01000000;
     93 static unsigned second_offset  = 0x00f00000;
     94 static unsigned tags_offset    = 0x00000100;
     95 
     96 static bool g_disable_verity = false;
     97 static bool g_disable_verification = false;
     98 
     99 static const std::string convert_fbe_marker_filename("convert_fbe");
    100 
    101 enum fb_buffer_type {
    102     FB_BUFFER_FD,
    103     FB_BUFFER_SPARSE,
    104 };
    105 
    106 struct fastboot_buffer {
    107     enum fb_buffer_type type;
    108     void* data;
    109     int64_t sz;
    110     int fd;
    111 };
    112 
    113 static struct {
    114     const char* nickname;
    115     const char* img_name;
    116     const char* sig_name;
    117     const char* part_name;
    118     bool is_optional;
    119     bool is_secondary;
    120 } images[] = {
    121     // clang-format off
    122     { "boot",     "boot.img",         "boot.sig",     "boot",     false, false },
    123     { nullptr,    "boot_other.img",   "boot.sig",     "boot",     true,  true  },
    124     { "dtbo",     "dtbo.img",         "dtbo.sig",     "dtbo",     true,  false },
    125     { "dts",      "dt.img",           "dt.sig",       "dts",      true,  false },
    126     { "recovery", "recovery.img",     "recovery.sig", "recovery", true,  false },
    127     { "system",   "system.img",       "system.sig",   "system",   false, false },
    128     { nullptr,    "system_other.img", "system.sig",   "system",   true,  true  },
    129     { "vbmeta",   "vbmeta.img",       "vbmeta.sig",   "vbmeta",   true,  false },
    130     { "vendor",   "vendor.img",       "vendor.sig",   "vendor",   true,  false },
    131     { nullptr,    "vendor_other.img", "vendor.sig",   "vendor",   true,  true  },
    132     // clang-format on
    133 };
    134 
    135 static std::string find_item_given_name(const char* img_name) {
    136     char* dir = getenv("ANDROID_PRODUCT_OUT");
    137     if (dir == nullptr || dir[0] == '\0') {
    138         die("ANDROID_PRODUCT_OUT not set");
    139     }
    140     return android::base::StringPrintf("%s/%s", dir, img_name);
    141 }
    142 
    143 static std::string find_item(const std::string& item) {
    144     for (size_t i = 0; i < arraysize(images); ++i) {
    145         if (images[i].nickname && item == images[i].nickname) {
    146             return find_item_given_name(images[i].img_name);
    147         }
    148     }
    149 
    150     if (item == "userdata") return find_item_given_name("userdata.img");
    151     if (item == "cache") return find_item_given_name("cache.img");
    152 
    153     fprintf(stderr, "unknown partition '%s'\n", item.c_str());
    154     return "";
    155 }
    156 
    157 static int64_t get_file_size(int fd) {
    158     struct stat sb;
    159     return fstat(fd, &sb) == -1 ? -1 : sb.st_size;
    160 }
    161 
    162 static void* load_fd(int fd, int64_t* sz) {
    163     int errno_tmp;
    164     char* data = nullptr;
    165 
    166     *sz = get_file_size(fd);
    167     if (*sz < 0) {
    168         goto oops;
    169     }
    170 
    171     data = (char*) malloc(*sz);
    172     if (data == nullptr) goto oops;
    173 
    174     if(read(fd, data, *sz) != *sz) goto oops;
    175     close(fd);
    176 
    177     return data;
    178 
    179 oops:
    180     errno_tmp = errno;
    181     close(fd);
    182     if(data != 0) free(data);
    183     errno = errno_tmp;
    184     return 0;
    185 }
    186 
    187 static void* load_file(const std::string& path, int64_t* sz) {
    188     int fd = open(path.c_str(), O_RDONLY | O_BINARY);
    189     if (fd == -1) return nullptr;
    190     return load_fd(fd, sz);
    191 }
    192 
    193 static int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
    194     // Require a matching vendor id if the user specified one with -i.
    195     if (vendor_id != 0 && info->dev_vendor != vendor_id) {
    196         return -1;
    197     }
    198 
    199     if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
    200         return -1;
    201     }
    202 
    203     // require matching serial number or device path if requested
    204     // at the command line with the -s option.
    205     if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
    206                    strcmp(local_serial, info->device_path) != 0)) return -1;
    207     return 0;
    208 }
    209 
    210 static int match_fastboot(usb_ifc_info* info) {
    211     return match_fastboot_with_serial(info, serial);
    212 }
    213 
    214 static int list_devices_callback(usb_ifc_info* info) {
    215     if (match_fastboot_with_serial(info, nullptr) == 0) {
    216         std::string serial = info->serial_number;
    217         if (!info->writable) {
    218             serial = UsbNoPermissionsShortHelpText();
    219         }
    220         if (!serial[0]) {
    221             serial = "????????????";
    222         }
    223         // output compatible with "adb devices"
    224         if (!long_listing) {
    225             printf("%s\tfastboot", serial.c_str());
    226         } else {
    227             printf("%-22s fastboot", serial.c_str());
    228             if (strlen(info->device_path) > 0) printf(" %s", info->device_path);
    229         }
    230         putchar('\n');
    231     }
    232 
    233     return -1;
    234 }
    235 
    236 // Opens a new Transport connected to a device. If |serial| is non-null it will be used to identify
    237 // a specific device, otherwise the first USB device found will be used.
    238 //
    239 // If |serial| is non-null but invalid, this prints an error message to stderr and returns nullptr.
    240 // Otherwise it blocks until the target is available.
    241 //
    242 // The returned Transport is a singleton, so multiple calls to this function will return the same
    243 // object, and the caller should not attempt to delete the returned Transport.
    244 static Transport* open_device() {
    245     static Transport* transport = nullptr;
    246     bool announce = true;
    247 
    248     if (transport != nullptr) {
    249         return transport;
    250     }
    251 
    252     Socket::Protocol protocol = Socket::Protocol::kTcp;
    253     std::string host;
    254     int port = 0;
    255     if (serial != nullptr) {
    256         const char* net_address = nullptr;
    257 
    258         if (android::base::StartsWith(serial, "tcp:")) {
    259             protocol = Socket::Protocol::kTcp;
    260             port = tcp::kDefaultPort;
    261             net_address = serial + strlen("tcp:");
    262         } else if (android::base::StartsWith(serial, "udp:")) {
    263             protocol = Socket::Protocol::kUdp;
    264             port = udp::kDefaultPort;
    265             net_address = serial + strlen("udp:");
    266         }
    267 
    268         if (net_address != nullptr) {
    269             std::string error;
    270             if (!android::base::ParseNetAddress(net_address, &host, &port, nullptr, &error)) {
    271                 fprintf(stderr, "error: Invalid network address '%s': %s\n", net_address,
    272                         error.c_str());
    273                 return nullptr;
    274             }
    275         }
    276     }
    277 
    278     while (true) {
    279         if (!host.empty()) {
    280             std::string error;
    281             if (protocol == Socket::Protocol::kTcp) {
    282                 transport = tcp::Connect(host, port, &error).release();
    283             } else if (protocol == Socket::Protocol::kUdp) {
    284                 transport = udp::Connect(host, port, &error).release();
    285             }
    286 
    287             if (transport == nullptr && announce) {
    288                 fprintf(stderr, "error: %s\n", error.c_str());
    289             }
    290         } else {
    291             transport = usb_open(match_fastboot);
    292         }
    293 
    294         if (transport != nullptr) {
    295             return transport;
    296         }
    297 
    298         if (announce) {
    299             announce = false;
    300             fprintf(stderr, "< waiting for %s >\n", serial ? serial : "any device");
    301         }
    302         std::this_thread::sleep_for(std::chrono::milliseconds(1));
    303     }
    304 }
    305 
    306 static void list_devices() {
    307     // We don't actually open a USB device here,
    308     // just getting our callback called so we can
    309     // list all the connected devices.
    310     usb_open(list_devices_callback);
    311 }
    312 
    313 static void syntax_error(const char* fmt, ...) {
    314     fprintf(stderr, "fastboot: usage: ");
    315 
    316     va_list ap;
    317     va_start(ap, fmt);
    318     vfprintf(stderr, fmt, ap);
    319     va_end(ap);
    320 
    321     fprintf(stderr, "\n");
    322     exit(1);
    323 }
    324 
    325 static int show_help() {
    326     // clang-format off
    327     fprintf(stdout,
    328 /*           1234567890123456789012345678901234567890123456789012345678901234567890123456 */
    329             "usage: fastboot [ <option> ] <command>\n"
    330             "\n"
    331             "commands:\n"
    332             "  update <filename>                        Reflash device from update.zip.\n"
    333             "                                           Sets the flashed slot as active.\n"
    334             "  flashall                                 Flash boot, system, vendor, and --\n"
    335             "                                           if found -- recovery. If the device\n"
    336             "                                           supports slots, the slot that has\n"
    337             "                                           been flashed to is set as active.\n"
    338             "                                           Secondary images may be flashed to\n"
    339             "                                           an inactive slot.\n"
    340             "  flash <partition> [ <filename> ]         Write a file to a flash partition.\n"
    341             "  flashing lock                            Locks the device. Prevents flashing.\n"
    342             "  flashing unlock                          Unlocks the device. Allows flashing\n"
    343             "                                           any partition except\n"
    344             "                                           bootloader-related partitions.\n"
    345             "  flashing lock_critical                   Prevents flashing bootloader-related\n"
    346             "                                           partitions.\n"
    347             "  flashing unlock_critical                 Enables flashing bootloader-related\n"
    348             "                                           partitions.\n"
    349             "  flashing get_unlock_ability              Queries bootloader to see if the\n"
    350             "                                           device is unlocked.\n"
    351             "  flashing get_unlock_bootloader_nonce     Queries the bootloader to get the\n"
    352             "                                           unlock nonce.\n"
    353             "  flashing unlock_bootloader <request>     Issue unlock bootloader using request.\n"
    354             "  flashing lock_bootloader                 Locks the bootloader to prevent\n"
    355             "                                           bootloader version rollback.\n"
    356             "  erase <partition>                        Erase a flash partition.\n"
    357             "  format[:[<fs type>][:[<size>]] <partition>\n"
    358             "                                           Format a flash partition. Can\n"
    359             "                                           override the fs type and/or size\n"
    360             "                                           the bootloader reports.\n"
    361             "  getvar <variable>                        Display a bootloader variable.\n"
    362             "  set_active <slot>                        Sets the active slot. If slots are\n"
    363             "                                           not supported, this does nothing.\n"
    364             "  boot <kernel> [ <ramdisk> [ <second> ] ] Download and boot kernel.\n"
    365             "  flash:raw <bootable-partition> <kernel> [ <ramdisk> [ <second> ] ]\n"
    366             "                                           Create bootimage and flash it.\n"
    367             "  devices [-l]                             List all connected devices [with\n"
    368             "                                           device paths].\n"
    369             "  continue                                 Continue with autoboot.\n"
    370             "  reboot [bootloader|emergency]            Reboot device [into bootloader or emergency mode].\n"
    371             "  reboot-bootloader                        Reboot device into bootloader.\n"
    372             "  oem <parameter1> ... <parameterN>        Executes oem specific command.\n"
    373             "  stage <infile>                           Sends contents of <infile> to stage for\n"
    374             "                                           the next command. Supported only on\n"
    375             "                                           Android Things devices.\n"
    376             "  get_staged <outfile>                     Receives data to <outfile> staged by the\n"
    377             "                                           last command. Supported only on Android\n"
    378             "                                           Things devices.\n"
    379             "  help                                     Show this help message.\n"
    380             "\n"
    381             "options:\n"
    382             "  -w                                       Erase userdata and cache (and format\n"
    383             "                                           if supported by partition type).\n"
    384             "  -u                                       Do not erase partition before\n"
    385             "                                           formatting.\n"
    386             "  -s <specific device>                     Specify a device. For USB, provide either\n"
    387             "                                           a serial number or path to device port.\n"
    388             "                                           For ethernet, provide an address in the\n"
    389             "                                           form <protocol>:<hostname>[:port] where\n"
    390             "                                           <protocol> is either tcp or udp.\n"
    391             "  -c <cmdline>                             Override kernel commandline.\n"
    392             "  -i <vendor id>                           Specify a custom USB vendor id.\n"
    393             "  -b, --base <base_addr>                   Specify a custom kernel base\n"
    394             "                                           address (default: 0x10000000).\n"
    395             "  --kernel-offset                          Specify a custom kernel offset.\n"
    396             "                                           (default: 0x00008000)\n"
    397             "  --ramdisk-offset                         Specify a custom ramdisk offset.\n"
    398             "                                           (default: 0x01000000)\n"
    399             "  --tags-offset                            Specify a custom tags offset.\n"
    400             "                                           (default: 0x00000100)\n"
    401             "  -n, --page-size <page size>              Specify the nand page size\n"
    402             "                                           (default: 2048).\n"
    403             "  -S <size>[K|M|G]                         Automatically sparse files greater\n"
    404             "                                           than 'size'. 0 to disable.\n"
    405             "  --slot <slot>                            Specify slot name to be used if the\n"
    406             "                                           device supports slots. All operations\n"
    407             "                                           on partitions that support slots will\n"
    408             "                                           be done on the slot specified.\n"
    409             "                                           'all' can be given to refer to all slots.\n"
    410             "                                           'other' can be given to refer to a\n"
    411             "                                           non-current slot. If this flag is not\n"
    412             "                                           used, slotted partitions will default\n"
    413             "                                           to the current active slot.\n"
    414             "  -a, --set-active[=<slot>]                Sets the active slot. If no slot is\n"
    415             "                                           provided, this will default to the value\n"
    416             "                                           given by --slot. If slots are not\n"
    417             "                                           supported, this does nothing. This will\n"
    418             "                                           run after all non-reboot commands.\n"
    419             "  --skip-secondary                         Will not flash secondary slots when\n"
    420             "                                           performing a flashall or update. This\n"
    421             "                                           will preserve data on other slots.\n"
    422             "  --skip-reboot                            Will not reboot the device when\n"
    423             "                                           performing commands that normally\n"
    424             "                                           trigger a reboot.\n"
    425             "  --disable-verity                         Set the disable-verity flag in the\n"
    426             "                                           the vbmeta image being flashed.\n"
    427             "  --disable-verification                   Set the disable-verification flag in"
    428             "                                           the vbmeta image being flashed.\n"
    429 #if !defined(_WIN32)
    430             "  --wipe-and-use-fbe                       On devices which support it,\n"
    431             "                                           erase userdata and cache, and\n"
    432             "                                           enable file-based encryption\n"
    433 #endif
    434             "  --unbuffered                             Do not buffer input or output.\n"
    435             "  --version                                Display version.\n"
    436             "  -h, --help                               show this message.\n"
    437         );
    438     // clang-format off
    439     return 0;
    440 }
    441 
    442 static void* load_bootable_image(const std::string& kernel, const std::string& ramdisk,
    443                                  const std::string& second_stage, int64_t* sz,
    444                                  const char* cmdline) {
    445     int64_t ksize;
    446     void* kdata = load_file(kernel.c_str(), &ksize);
    447     if (kdata == nullptr) die("cannot load '%s': %s\n", kernel.c_str(), strerror(errno));
    448 
    449     // Is this actually a boot image?
    450     if (!memcmp(kdata, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
    451         if (cmdline) bootimg_set_cmdline((boot_img_hdr*) kdata, cmdline);
    452 
    453         if (!ramdisk.empty()) die("cannot boot a boot.img *and* ramdisk\n");
    454 
    455         *sz = ksize;
    456         return kdata;
    457     }
    458 
    459     void* rdata = nullptr;
    460     int64_t rsize = 0;
    461     if (!ramdisk.empty()) {
    462         rdata = load_file(ramdisk.c_str(), &rsize);
    463         if (rdata == nullptr) die("cannot load '%s': %s\n", ramdisk.c_str(), strerror(errno));
    464     }
    465 
    466     void* sdata = nullptr;
    467     int64_t ssize = 0;
    468     if (!second_stage.empty()) {
    469         sdata = load_file(second_stage.c_str(), &ssize);
    470         if (sdata == nullptr) die("cannot load '%s': %s\n", second_stage.c_str(), strerror(errno));
    471     }
    472 
    473     fprintf(stderr,"creating boot image...\n");
    474     int64_t bsize = 0;
    475     void* bdata = mkbootimg(kdata, ksize, kernel_offset,
    476                       rdata, rsize, ramdisk_offset,
    477                       sdata, ssize, second_offset,
    478                       page_size, base_addr, tags_offset, &bsize);
    479     if (bdata == nullptr) die("failed to create boot.img\n");
    480 
    481     if (cmdline) bootimg_set_cmdline((boot_img_hdr*) bdata, cmdline);
    482     fprintf(stderr, "creating boot image - %" PRId64 " bytes\n", bsize);
    483     *sz = bsize;
    484 
    485     return bdata;
    486 }
    487 
    488 static void* unzip_file(ZipArchiveHandle zip, const char* entry_name, int64_t* sz) {
    489     ZipString zip_entry_name(entry_name);
    490     ZipEntry zip_entry;
    491     if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
    492         fprintf(stderr, "archive does not contain '%s'\n", entry_name);
    493         return 0;
    494     }
    495 
    496     *sz = zip_entry.uncompressed_length;
    497 
    498     fprintf(stderr, "extracting %s (%" PRId64 " MB)...\n", entry_name, *sz / 1024 / 1024);
    499     uint8_t* data = reinterpret_cast<uint8_t*>(malloc(zip_entry.uncompressed_length));
    500     if (data == nullptr) {
    501         fprintf(stderr, "failed to allocate %" PRId64 " bytes for '%s'\n", *sz, entry_name);
    502         return 0;
    503     }
    504 
    505     int error = ExtractToMemory(zip, &zip_entry, data, zip_entry.uncompressed_length);
    506     if (error != 0) {
    507         fprintf(stderr, "failed to extract '%s': %s\n", entry_name, ErrorCodeString(error));
    508         free(data);
    509         return 0;
    510     }
    511 
    512     return data;
    513 }
    514 
    515 #if defined(_WIN32)
    516 
    517 // TODO: move this to somewhere it can be shared.
    518 
    519 #include <windows.h>
    520 
    521 // Windows' tmpfile(3) requires administrator rights because
    522 // it creates temporary files in the root directory.
    523 static FILE* win32_tmpfile() {
    524     char temp_path[PATH_MAX];
    525     DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
    526     if (nchars == 0 || nchars >= sizeof(temp_path)) {
    527         fprintf(stderr, "GetTempPath failed, error %ld\n", GetLastError());
    528         return nullptr;
    529     }
    530 
    531     char filename[PATH_MAX];
    532     if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
    533         fprintf(stderr, "GetTempFileName failed, error %ld\n", GetLastError());
    534         return nullptr;
    535     }
    536 
    537     return fopen(filename, "w+bTD");
    538 }
    539 
    540 #define tmpfile win32_tmpfile
    541 
    542 static std::string make_temporary_directory() {
    543     fprintf(stderr, "make_temporary_directory not supported under Windows, sorry!");
    544     return "";
    545 }
    546 
    547 static int make_temporary_fd() {
    548     // TODO: reimplement to avoid leaking a FILE*.
    549     return fileno(tmpfile());
    550 }
    551 
    552 #else
    553 
    554 static std::string make_temporary_template() {
    555     const char* tmpdir = getenv("TMPDIR");
    556     if (tmpdir == nullptr) tmpdir = P_tmpdir;
    557     return std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
    558 }
    559 
    560 static std::string make_temporary_directory() {
    561     std::string result(make_temporary_template());
    562     if (mkdtemp(&result[0]) == nullptr) {
    563         fprintf(stderr, "Unable to create temporary directory: %s\n", strerror(errno));
    564         return "";
    565     }
    566     return result;
    567 }
    568 
    569 static int make_temporary_fd() {
    570     std::string path_template(make_temporary_template());
    571     int fd = mkstemp(&path_template[0]);
    572     if (fd == -1) {
    573         fprintf(stderr, "Unable to create temporary file: %s\n", strerror(errno));
    574         return -1;
    575     }
    576     unlink(path_template.c_str());
    577     return fd;
    578 }
    579 
    580 #endif
    581 
    582 static std::string create_fbemarker_tmpdir() {
    583     std::string dir = make_temporary_directory();
    584     if (dir.empty()) {
    585         fprintf(stderr, "Unable to create local temp directory for FBE marker\n");
    586         return "";
    587     }
    588     std::string marker_file = dir + "/" + convert_fbe_marker_filename;
    589     int fd = open(marker_file.c_str(), O_CREAT | O_WRONLY | O_CLOEXEC, 0666);
    590     if (fd == -1) {
    591         fprintf(stderr, "Unable to create FBE marker file %s locally: %d, %s\n",
    592             marker_file.c_str(), errno, strerror(errno));
    593         return "";
    594     }
    595     close(fd);
    596     return dir;
    597 }
    598 
    599 static void delete_fbemarker_tmpdir(const std::string& dir) {
    600     std::string marker_file = dir + "/" + convert_fbe_marker_filename;
    601     if (unlink(marker_file.c_str()) == -1) {
    602         fprintf(stderr, "Unable to delete FBE marker file %s locally: %d, %s\n",
    603             marker_file.c_str(), errno, strerror(errno));
    604         return;
    605     }
    606     if (rmdir(dir.c_str()) == -1) {
    607         fprintf(stderr, "Unable to delete FBE marker directory %s locally: %d, %s\n",
    608             dir.c_str(), errno, strerror(errno));
    609         return;
    610     }
    611 }
    612 
    613 static int unzip_to_file(ZipArchiveHandle zip, const char* entry_name) {
    614     unique_fd fd(make_temporary_fd());
    615     if (fd == -1) {
    616         fprintf(stderr, "failed to create temporary file for '%s': %s\n",
    617                 entry_name, strerror(errno));
    618         return -1;
    619     }
    620 
    621     ZipString zip_entry_name(entry_name);
    622     ZipEntry zip_entry;
    623     if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
    624         fprintf(stderr, "archive does not contain '%s'\n", entry_name);
    625         return -1;
    626     }
    627 
    628     fprintf(stderr, "extracting %s (%" PRIu32 " MB)...\n", entry_name,
    629             zip_entry.uncompressed_length / 1024 / 1024);
    630     int error = ExtractEntryToFile(zip, &zip_entry, fd);
    631     if (error != 0) {
    632         fprintf(stderr, "failed to extract '%s': %s\n", entry_name, ErrorCodeString(error));
    633         return -1;
    634     }
    635 
    636     lseek(fd, 0, SEEK_SET);
    637     // TODO: We're leaking 'fp' here.
    638     return fd.release();
    639 }
    640 
    641 static char *strip(char *s)
    642 {
    643     int n;
    644     while(*s && isspace(*s)) s++;
    645     n = strlen(s);
    646     while(n-- > 0) {
    647         if(!isspace(s[n])) break;
    648         s[n] = 0;
    649     }
    650     return s;
    651 }
    652 
    653 #define MAX_OPTIONS 32
    654 static int setup_requirement_line(char *name)
    655 {
    656     char *val[MAX_OPTIONS];
    657     char *prod = nullptr;
    658     unsigned n, count;
    659     char *x;
    660     int invert = 0;
    661 
    662     if (!strncmp(name, "reject ", 7)) {
    663         name += 7;
    664         invert = 1;
    665     } else if (!strncmp(name, "require ", 8)) {
    666         name += 8;
    667         invert = 0;
    668     } else if (!strncmp(name, "require-for-product:", 20)) {
    669         // Get the product and point name past it
    670         prod = name + 20;
    671         name = strchr(name, ' ');
    672         if (!name) return -1;
    673         *name = 0;
    674         name += 1;
    675         invert = 0;
    676     }
    677 
    678     x = strchr(name, '=');
    679     if (x == 0) return 0;
    680     *x = 0;
    681     val[0] = x + 1;
    682 
    683     for(count = 1; count < MAX_OPTIONS; count++) {
    684         x = strchr(val[count - 1],'|');
    685         if (x == 0) break;
    686         *x = 0;
    687         val[count] = x + 1;
    688     }
    689 
    690     name = strip(name);
    691     for(n = 0; n < count; n++) val[n] = strip(val[n]);
    692 
    693     name = strip(name);
    694     if (name == 0) return -1;
    695 
    696     const char* var = name;
    697     // Work around an unfortunate name mismatch.
    698     if (!strcmp(name,"board")) var = "product";
    699 
    700     const char** out = reinterpret_cast<const char**>(malloc(sizeof(char*) * count));
    701     if (out == 0) return -1;
    702 
    703     for(n = 0; n < count; n++) {
    704         out[n] = strdup(strip(val[n]));
    705         if (out[n] == 0) {
    706             for(size_t i = 0; i < n; ++i) {
    707                 free((char*) out[i]);
    708             }
    709             free(out);
    710             return -1;
    711         }
    712     }
    713 
    714     fb_queue_require(prod, var, invert, n, out);
    715     return 0;
    716 }
    717 
    718 static void setup_requirements(char* data, int64_t sz) {
    719     char* s = data;
    720     while (sz-- > 0) {
    721         if (*s == '\n') {
    722             *s++ = 0;
    723             if (setup_requirement_line(data)) {
    724                 die("out of memory");
    725             }
    726             data = s;
    727         } else {
    728             s++;
    729         }
    730     }
    731 }
    732 
    733 static void queue_info_dump() {
    734     fb_queue_notice("--------------------------------------------");
    735     fb_queue_display("version-bootloader", "Bootloader Version...");
    736     fb_queue_display("version-baseband",   "Baseband Version.....");
    737     fb_queue_display("serialno",           "Serial Number........");
    738     fb_queue_notice("--------------------------------------------");
    739 }
    740 
    741 static struct sparse_file **load_sparse_files(int fd, int max_size)
    742 {
    743     struct sparse_file* s = sparse_file_import_auto(fd, false, true);
    744     if (!s) {
    745         die("cannot sparse read file\n");
    746     }
    747 
    748     int files = sparse_file_resparse(s, max_size, nullptr, 0);
    749     if (files < 0) {
    750         die("Failed to resparse\n");
    751     }
    752 
    753     sparse_file** out_s = reinterpret_cast<sparse_file**>(calloc(sizeof(struct sparse_file *), files + 1));
    754     if (!out_s) {
    755         die("Failed to allocate sparse file array\n");
    756     }
    757 
    758     files = sparse_file_resparse(s, max_size, out_s, files);
    759     if (files < 0) {
    760         die("Failed to resparse\n");
    761     }
    762 
    763     return out_s;
    764 }
    765 
    766 static int64_t get_target_sparse_limit(Transport* transport) {
    767     std::string max_download_size;
    768     if (!fb_getvar(transport, "max-download-size", &max_download_size) ||
    769             max_download_size.empty()) {
    770         fprintf(stderr, "target didn't report max-download-size\n");
    771         return 0;
    772     }
    773 
    774     // Some bootloaders (angler, for example) send spurious whitespace too.
    775     max_download_size = android::base::Trim(max_download_size);
    776 
    777     uint64_t limit;
    778     if (!android::base::ParseUint(max_download_size, &limit)) {
    779         fprintf(stderr, "couldn't parse max-download-size '%s'\n", max_download_size.c_str());
    780         return 0;
    781     }
    782     if (limit > 0) {
    783         fprintf(stderr, "target reported max download size of %" PRId64 " bytes\n", limit);
    784     }
    785     return limit;
    786 }
    787 
    788 static int64_t get_sparse_limit(Transport* transport, int64_t size) {
    789     int64_t limit;
    790 
    791     if (sparse_limit == 0) {
    792         return 0;
    793     } else if (sparse_limit > 0) {
    794         limit = sparse_limit;
    795     } else {
    796         if (target_sparse_limit == -1) {
    797             target_sparse_limit = get_target_sparse_limit(transport);
    798         }
    799         if (target_sparse_limit > 0) {
    800             limit = target_sparse_limit;
    801         } else {
    802             return 0;
    803         }
    804     }
    805 
    806     if (size > limit) {
    807         return std::min(limit, RESPARSE_LIMIT);
    808     }
    809 
    810     return 0;
    811 }
    812 
    813 // Until we get lazy inode table init working in make_ext4fs, we need to
    814 // erase partitions of type ext4 before flashing a filesystem so no stale
    815 // inodes are left lying around.  Otherwise, e2fsck gets very upset.
    816 static bool needs_erase(Transport* transport, const char* partition) {
    817     std::string partition_type;
    818     if (!fb_getvar(transport, std::string("partition-type:") + partition, &partition_type)) {
    819         return false;
    820     }
    821     return partition_type == "ext4";
    822 }
    823 
    824 static bool load_buf_fd(Transport* transport, int fd, struct fastboot_buffer* buf) {
    825     int64_t sz = get_file_size(fd);
    826     if (sz == -1) {
    827         return false;
    828     }
    829 
    830     lseek64(fd, 0, SEEK_SET);
    831     int64_t limit = get_sparse_limit(transport, sz);
    832     if (limit) {
    833         sparse_file** s = load_sparse_files(fd, limit);
    834         if (s == nullptr) {
    835             return false;
    836         }
    837         buf->type = FB_BUFFER_SPARSE;
    838         buf->data = s;
    839     } else {
    840         buf->type = FB_BUFFER_FD;
    841         buf->data = nullptr;
    842         buf->fd = fd;
    843         buf->sz = sz;
    844     }
    845 
    846     return true;
    847 }
    848 
    849 static bool load_buf(Transport* transport, const char* fname, struct fastboot_buffer* buf) {
    850     unique_fd fd(TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_BINARY)));
    851 
    852     if (fd == -1) {
    853         return false;
    854     }
    855 
    856     struct stat s;
    857     if (fstat(fd, &s)) {
    858         return false;
    859     }
    860     if (!S_ISREG(s.st_mode)) {
    861         errno = S_ISDIR(s.st_mode) ? EISDIR : EINVAL;
    862         return false;
    863     }
    864 
    865     return load_buf_fd(transport, fd.release(), buf);
    866 }
    867 
    868 static void rewrite_vbmeta_buffer(struct fastboot_buffer* buf) {
    869     // Buffer needs to be at least the size of the VBMeta struct which
    870     // is 256 bytes.
    871     if (buf->sz < 256) {
    872         return;
    873     }
    874 
    875     int fd = make_temporary_fd();
    876     if (fd == -1) {
    877         die("Failed to create temporary file for vbmeta rewriting");
    878     }
    879 
    880     std::string data;
    881     if (!android::base::ReadFdToString(buf->fd, &data)) {
    882         die("Failed reading from vbmeta");
    883     }
    884 
    885     // There's a 32-bit big endian |flags| field at offset 120 where
    886     // bit 0 corresponds to disable-verity and bit 1 corresponds to
    887     // disable-verification.
    888     //
    889     // See external/avb/libavb/avb_vbmeta_image.h for the layout of
    890     // the VBMeta struct.
    891     if (g_disable_verity) {
    892         data[123] |= 0x01;
    893     }
    894     if (g_disable_verification) {
    895         data[123] |= 0x02;
    896     }
    897 
    898     if (!android::base::WriteStringToFd(data, fd)) {
    899         die("Failed writing to modified vbmeta");
    900     }
    901     close(buf->fd);
    902     buf->fd = fd;
    903     lseek(fd, 0, SEEK_SET);
    904 }
    905 
    906 static void flash_buf(const char *pname, struct fastboot_buffer *buf)
    907 {
    908     sparse_file** s;
    909 
    910     // Rewrite vbmeta if that's what we're flashing and modification has been requested.
    911     if ((g_disable_verity || g_disable_verification) &&
    912         (strcmp(pname, "vbmeta") == 0 || strcmp(pname, "vbmeta_a") == 0 ||
    913          strcmp(pname, "vbmeta_b") == 0)) {
    914         rewrite_vbmeta_buffer(buf);
    915     }
    916 
    917     switch (buf->type) {
    918         case FB_BUFFER_SPARSE: {
    919             std::vector<std::pair<sparse_file*, int64_t>> sparse_files;
    920             s = reinterpret_cast<sparse_file**>(buf->data);
    921             while (*s) {
    922                 int64_t sz = sparse_file_len(*s, true, false);
    923                 sparse_files.emplace_back(*s, sz);
    924                 ++s;
    925             }
    926 
    927             for (size_t i = 0; i < sparse_files.size(); ++i) {
    928                 const auto& pair = sparse_files[i];
    929                 fb_queue_flash_sparse(pname, pair.first, pair.second, i + 1, sparse_files.size());
    930             }
    931             break;
    932         }
    933         case FB_BUFFER_FD:
    934             fb_queue_flash_fd(pname, buf->fd, buf->sz);
    935             break;
    936         default:
    937             die("unknown buffer type: %d", buf->type);
    938     }
    939 }
    940 
    941 static std::string get_current_slot(Transport* transport)
    942 {
    943     std::string current_slot;
    944     if (fb_getvar(transport, "current-slot", &current_slot)) {
    945         if (current_slot == "_a") return "a"; // Legacy support
    946         if (current_slot == "_b") return "b"; // Legacy support
    947         return current_slot;
    948     }
    949     return "";
    950 }
    951 
    952 // Legacy support
    953 static std::vector<std::string> get_suffixes_obsolete(Transport* transport) {
    954     std::vector<std::string> suffixes;
    955     std::string suffix_list;
    956     if (!fb_getvar(transport, "slot-suffixes", &suffix_list)) {
    957         return suffixes;
    958     }
    959     suffixes = android::base::Split(suffix_list, ",");
    960     // Unfortunately some devices will return an error message in the
    961     // guise of a valid value. If we only see only one suffix, it's probably
    962     // not real.
    963     if (suffixes.size() == 1) {
    964         suffixes.clear();
    965     }
    966     return suffixes;
    967 }
    968 
    969 // Legacy support
    970 static bool supports_AB_obsolete(Transport* transport) {
    971   return !get_suffixes_obsolete(transport).empty();
    972 }
    973 
    974 static int get_slot_count(Transport* transport) {
    975     std::string var;
    976     int count;
    977     if (!fb_getvar(transport, "slot-count", &var)) {
    978         if (supports_AB_obsolete(transport)) return 2; // Legacy support
    979     }
    980     if (!android::base::ParseInt(var, &count)) return 0;
    981     return count;
    982 }
    983 
    984 static bool supports_AB(Transport* transport) {
    985   return get_slot_count(transport) >= 2;
    986 }
    987 
    988 // Given a current slot, this returns what the 'other' slot is.
    989 static std::string get_other_slot(const std::string& current_slot, int count) {
    990     if (count == 0) return "";
    991 
    992     char next = (current_slot[0] - 'a' + 1)%count + 'a';
    993     return std::string(1, next);
    994 }
    995 
    996 static std::string get_other_slot(Transport* transport, const std::string& current_slot) {
    997     return get_other_slot(current_slot, get_slot_count(transport));
    998 }
    999 
   1000 static std::string get_other_slot(Transport* transport, int count) {
   1001     return get_other_slot(get_current_slot(transport), count);
   1002 }
   1003 
   1004 static std::string get_other_slot(Transport* transport) {
   1005     return get_other_slot(get_current_slot(transport), get_slot_count(transport));
   1006 }
   1007 
   1008 static std::string verify_slot(Transport* transport, const std::string& slot_name, bool allow_all) {
   1009     std::string slot = slot_name;
   1010     if (slot == "_a") slot = "a"; // Legacy support
   1011     if (slot == "_b") slot = "b"; // Legacy support
   1012     if (slot == "all") {
   1013         if (allow_all) {
   1014             return "all";
   1015         } else {
   1016             int count = get_slot_count(transport);
   1017             if (count > 0) {
   1018                 return "a";
   1019             } else {
   1020                 die("No known slots.");
   1021             }
   1022         }
   1023     }
   1024 
   1025     int count = get_slot_count(transport);
   1026     if (count == 0) die("Device does not support slots.\n");
   1027 
   1028     if (slot == "other") {
   1029         std::string other = get_other_slot(transport, count);
   1030         if (other == "") {
   1031            die("No known slots.");
   1032         }
   1033         return other;
   1034     }
   1035 
   1036     if (slot.size() == 1 && (slot[0]-'a' >= 0 && slot[0]-'a' < count)) return slot;
   1037 
   1038     fprintf(stderr, "Slot %s does not exist. supported slots are:\n", slot.c_str());
   1039     for (int i=0; i<count; i++) {
   1040         fprintf(stderr, "%c\n", (char)(i + 'a'));
   1041     }
   1042 
   1043     exit(1);
   1044 }
   1045 
   1046 static std::string verify_slot(Transport* transport, const std::string& slot) {
   1047    return verify_slot(transport, slot, true);
   1048 }
   1049 
   1050 static void do_for_partition(Transport* transport, const std::string& part, const std::string& slot,
   1051                              const std::function<void(const std::string&)>& func, bool force_slot) {
   1052     std::string has_slot;
   1053     std::string current_slot;
   1054 
   1055     if (!fb_getvar(transport, "has-slot:" + part, &has_slot)) {
   1056         /* If has-slot is not supported, the answer is no. */
   1057         has_slot = "no";
   1058     }
   1059     if (has_slot == "yes") {
   1060         if (slot == "") {
   1061             current_slot = get_current_slot(transport);
   1062             if (current_slot == "") {
   1063                 die("Failed to identify current slot.\n");
   1064             }
   1065             func(part + "_" + current_slot);
   1066         } else {
   1067             func(part + '_' + slot);
   1068         }
   1069     } else {
   1070         if (force_slot && slot != "") {
   1071              fprintf(stderr, "Warning: %s does not support slots, and slot %s was requested.\n",
   1072                      part.c_str(), slot.c_str());
   1073         }
   1074         func(part);
   1075     }
   1076 }
   1077 
   1078 /* This function will find the real partition name given a base name, and a slot. If slot is NULL or
   1079  * empty, it will use the current slot. If slot is "all", it will return a list of all possible
   1080  * partition names. If force_slot is true, it will fail if a slot is specified, and the given
   1081  * partition does not support slots.
   1082  */
   1083 static void do_for_partitions(Transport* transport, const std::string& part, const std::string& slot,
   1084                               const std::function<void(const std::string&)>& func, bool force_slot) {
   1085     std::string has_slot;
   1086 
   1087     if (slot == "all") {
   1088         if (!fb_getvar(transport, "has-slot:" + part, &has_slot)) {
   1089             die("Could not check if partition %s has slot.", part.c_str());
   1090         }
   1091         if (has_slot == "yes") {
   1092             for (int i=0; i < get_slot_count(transport); i++) {
   1093                 do_for_partition(transport, part, std::string(1, (char)(i + 'a')), func, force_slot);
   1094             }
   1095         } else {
   1096             do_for_partition(transport, part, "", func, force_slot);
   1097         }
   1098     } else {
   1099         do_for_partition(transport, part, slot, func, force_slot);
   1100     }
   1101 }
   1102 
   1103 static void do_flash(Transport* transport, const char* pname, const char* fname) {
   1104     struct fastboot_buffer buf;
   1105 
   1106     if (!load_buf(transport, fname, &buf)) {
   1107         die("cannot load '%s': %s", fname, strerror(errno));
   1108     }
   1109     flash_buf(pname, &buf);
   1110 }
   1111 
   1112 static void do_update_signature(ZipArchiveHandle zip, const char* filename) {
   1113     int64_t sz;
   1114     void* data = unzip_file(zip, filename, &sz);
   1115     if (data == nullptr) return;
   1116     fb_queue_download("signature", data, sz);
   1117     fb_queue_command("signature", "installing signature");
   1118 }
   1119 
   1120 // Sets slot_override as the active slot. If slot_override is blank,
   1121 // set current slot as active instead. This clears slot-unbootable.
   1122 static void set_active(Transport* transport, const std::string& slot_override) {
   1123     std::string separator = "";
   1124     if (!supports_AB(transport)) {
   1125         if (supports_AB_obsolete(transport)) {
   1126             separator = "_"; // Legacy support
   1127         } else {
   1128             return;
   1129         }
   1130     }
   1131     if (slot_override != "") {
   1132         fb_set_active((separator + slot_override).c_str());
   1133     } else {
   1134         std::string current_slot = get_current_slot(transport);
   1135         if (current_slot != "") {
   1136             fb_set_active((separator + current_slot).c_str());
   1137         }
   1138     }
   1139 }
   1140 
   1141 static void do_update(Transport* transport, const char* filename, const std::string& slot_override, bool erase_first, bool skip_secondary) {
   1142     queue_info_dump();
   1143 
   1144     fb_queue_query_save("product", cur_product, sizeof(cur_product));
   1145 
   1146     ZipArchiveHandle zip;
   1147     int error = OpenArchive(filename, &zip);
   1148     if (error != 0) {
   1149         CloseArchive(zip);
   1150         die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
   1151     }
   1152 
   1153     int64_t sz;
   1154     void* data = unzip_file(zip, "android-info.txt", &sz);
   1155     if (data == nullptr) {
   1156         CloseArchive(zip);
   1157         die("update package '%s' has no android-info.txt", filename);
   1158     }
   1159 
   1160     setup_requirements(reinterpret_cast<char*>(data), sz);
   1161 
   1162     std::string secondary;
   1163     if (!skip_secondary) {
   1164         if (slot_override != "") {
   1165             secondary = get_other_slot(transport, slot_override);
   1166         } else {
   1167             secondary = get_other_slot(transport);
   1168         }
   1169         if (secondary == "") {
   1170             if (supports_AB(transport)) {
   1171                 fprintf(stderr, "Warning: Could not determine slot for secondary images. Ignoring.\n");
   1172             }
   1173             skip_secondary = true;
   1174         }
   1175     }
   1176     for (size_t i = 0; i < arraysize(images); ++i) {
   1177         const char* slot = slot_override.c_str();
   1178         if (images[i].is_secondary) {
   1179             if (!skip_secondary) {
   1180                 slot = secondary.c_str();
   1181             } else {
   1182                 continue;
   1183             }
   1184         }
   1185 
   1186         int fd = unzip_to_file(zip, images[i].img_name);
   1187         if (fd == -1) {
   1188             if (images[i].is_optional) {
   1189                 continue;
   1190             }
   1191             CloseArchive(zip);
   1192             exit(1); // unzip_to_file already explained why.
   1193         }
   1194         fastboot_buffer buf;
   1195         if (!load_buf_fd(transport, fd, &buf)) {
   1196             die("cannot load %s from flash: %s", images[i].img_name, strerror(errno));
   1197         }
   1198 
   1199         auto update = [&](const std::string &partition) {
   1200             do_update_signature(zip, images[i].sig_name);
   1201             if (erase_first && needs_erase(transport, partition.c_str())) {
   1202                 fb_queue_erase(partition.c_str());
   1203             }
   1204             flash_buf(partition.c_str(), &buf);
   1205             /* not closing the fd here since the sparse code keeps the fd around
   1206              * but hasn't mmaped data yet. The temporary file will get cleaned up when the
   1207              * program exits.
   1208              */
   1209         };
   1210         do_for_partitions(transport, images[i].part_name, slot, update, false);
   1211     }
   1212 
   1213     CloseArchive(zip);
   1214     if (slot_override == "all") {
   1215         set_active(transport, "a");
   1216     } else {
   1217         set_active(transport, slot_override);
   1218     }
   1219 }
   1220 
   1221 static void do_send_signature(const std::string& fn) {
   1222     std::size_t extension_loc = fn.find(".img");
   1223     if (extension_loc == std::string::npos) return;
   1224 
   1225     std::string fs_sig = fn.substr(0, extension_loc) + ".sig";
   1226 
   1227     int64_t sz;
   1228     void* data = load_file(fs_sig.c_str(), &sz);
   1229     if (data == nullptr) return;
   1230 
   1231     fb_queue_download("signature", data, sz);
   1232     fb_queue_command("signature", "installing signature");
   1233 }
   1234 
   1235 static void do_flashall(Transport* transport, const std::string& slot_override, int erase_first, bool skip_secondary) {
   1236     std::string fname;
   1237     queue_info_dump();
   1238 
   1239     fb_queue_query_save("product", cur_product, sizeof(cur_product));
   1240 
   1241     fname = find_item_given_name("android-info.txt");
   1242     if (fname.empty()) die("cannot find android-info.txt");
   1243 
   1244     int64_t sz;
   1245     void* data = load_file(fname.c_str(), &sz);
   1246     if (data == nullptr) die("could not load android-info.txt: %s", strerror(errno));
   1247 
   1248     setup_requirements(reinterpret_cast<char*>(data), sz);
   1249 
   1250     std::string secondary;
   1251     if (!skip_secondary) {
   1252         if (slot_override != "") {
   1253             secondary = get_other_slot(transport, slot_override);
   1254         } else {
   1255             secondary = get_other_slot(transport);
   1256         }
   1257         if (secondary == "") {
   1258             if (supports_AB(transport)) {
   1259                 fprintf(stderr, "Warning: Could not determine slot for secondary images. Ignoring.\n");
   1260             }
   1261             skip_secondary = true;
   1262         }
   1263     }
   1264 
   1265     for (size_t i = 0; i < arraysize(images); i++) {
   1266         const char* slot = NULL;
   1267         if (images[i].is_secondary) {
   1268             if (!skip_secondary) slot = secondary.c_str();
   1269         } else {
   1270             slot = slot_override.c_str();
   1271         }
   1272         if (!slot) continue;
   1273         fname = find_item_given_name(images[i].img_name);
   1274         fastboot_buffer buf;
   1275         if (!load_buf(transport, fname.c_str(), &buf)) {
   1276             if (images[i].is_optional) continue;
   1277             die("could not load '%s': %s\n", images[i].img_name, strerror(errno));
   1278         }
   1279 
   1280         auto flashall = [&](const std::string &partition) {
   1281             do_send_signature(fname.c_str());
   1282             if (erase_first && needs_erase(transport, partition.c_str())) {
   1283                 fb_queue_erase(partition.c_str());
   1284             }
   1285             flash_buf(partition.c_str(), &buf);
   1286         };
   1287         do_for_partitions(transport, images[i].part_name, slot, flashall, false);
   1288     }
   1289 
   1290     if (slot_override == "all") {
   1291         set_active(transport, "a");
   1292     } else {
   1293         set_active(transport, slot_override);
   1294     }
   1295 }
   1296 
   1297 static std::string next_arg(std::vector<std::string>* args) {
   1298     if (args->empty()) syntax_error("expected argument");
   1299     std::string result = args->front();
   1300     args->erase(args->begin());
   1301     return result;
   1302 }
   1303 
   1304 static void do_bypass_unlock_command(std::vector<std::string>* args) {
   1305     if (args->empty()) syntax_error("missing unlock_bootloader request");
   1306 
   1307     std::string filename = next_arg(args);
   1308 
   1309     int64_t sz;
   1310     void* data = load_file(filename.c_str(), &sz);
   1311     if (data == nullptr) die("could not load '%s': %s", filename.c_str(), strerror(errno));
   1312     fb_queue_download("unlock_message", data, sz);
   1313     fb_queue_command("flashing unlock_bootloader", "unlocking bootloader");
   1314 }
   1315 
   1316 static void do_oem_command(const std::string& cmd, std::vector<std::string>* args) {
   1317     if (args->empty()) syntax_error("empty oem command");
   1318 
   1319     std::string command(cmd);
   1320     while (!args->empty()) {
   1321         command += " " + next_arg(args);
   1322     }
   1323     fb_queue_command(command.c_str(), "");
   1324 }
   1325 
   1326 static int64_t parse_num(const char *arg)
   1327 {
   1328     char *endptr;
   1329     unsigned long long num;
   1330 
   1331     num = strtoull(arg, &endptr, 0);
   1332     if (endptr == arg) {
   1333         return -1;
   1334     }
   1335 
   1336     if (*endptr == 'k' || *endptr == 'K') {
   1337         if (num >= (-1ULL) / 1024) {
   1338             return -1;
   1339         }
   1340         num *= 1024LL;
   1341         endptr++;
   1342     } else if (*endptr == 'm' || *endptr == 'M') {
   1343         if (num >= (-1ULL) / (1024 * 1024)) {
   1344             return -1;
   1345         }
   1346         num *= 1024LL * 1024LL;
   1347         endptr++;
   1348     } else if (*endptr == 'g' || *endptr == 'G') {
   1349         if (num >= (-1ULL) / (1024 * 1024 * 1024)) {
   1350             return -1;
   1351         }
   1352         num *= 1024LL * 1024LL * 1024LL;
   1353         endptr++;
   1354     }
   1355 
   1356     if (*endptr != '\0') {
   1357         return -1;
   1358     }
   1359 
   1360     if (num > INT64_MAX) {
   1361         return -1;
   1362     }
   1363 
   1364     return num;
   1365 }
   1366 
   1367 static std::string fb_fix_numeric_var(std::string var) {
   1368     // Some bootloaders (angler, for example), send spurious leading whitespace.
   1369     var = android::base::Trim(var);
   1370     // Some bootloaders (hammerhead, for example) use implicit hex.
   1371     // This code used to use strtol with base 16.
   1372     if (!android::base::StartsWith(var, "0x")) var = "0x" + var;
   1373     return var;
   1374 }
   1375 
   1376 static unsigned fb_get_flash_block_size(Transport* transport, std::string name) {
   1377     std::string sizeString;
   1378     if (!fb_getvar(transport, name.c_str(), &sizeString)) {
   1379         /* This device does not report flash block sizes, so return 0 */
   1380         return 0;
   1381     }
   1382     sizeString = fb_fix_numeric_var(sizeString);
   1383 
   1384     unsigned size;
   1385     if (!android::base::ParseUint(sizeString, &size)) {
   1386         fprintf(stderr, "Couldn't parse %s '%s'.\n", name.c_str(), sizeString.c_str());
   1387         return 0;
   1388     }
   1389     if (size < 4096 || (size & (size - 1)) != 0) {
   1390         fprintf(stderr, "Invalid %s %u: must be a power of 2 and at least 4096.\n",
   1391                 name.c_str(), size);
   1392         return 0;
   1393     }
   1394     return size;
   1395 }
   1396 
   1397 static void fb_perform_format(Transport* transport,
   1398                               const char* partition, int skip_if_not_supported,
   1399                               const std::string& type_override, const std::string& size_override,
   1400                               const std::string& initial_dir) {
   1401     std::string partition_type, partition_size;
   1402 
   1403     struct fastboot_buffer buf;
   1404     const char* errMsg = nullptr;
   1405     const struct fs_generator* gen = nullptr;
   1406     TemporaryFile output;
   1407     unique_fd fd;
   1408 
   1409     unsigned int limit = INT_MAX;
   1410     if (target_sparse_limit > 0 && target_sparse_limit < limit) {
   1411         limit = target_sparse_limit;
   1412     }
   1413     if (sparse_limit > 0 && sparse_limit < limit) {
   1414         limit = sparse_limit;
   1415     }
   1416 
   1417     if (!fb_getvar(transport, std::string("partition-type:") + partition, &partition_type)) {
   1418         errMsg = "Can't determine partition type.\n";
   1419         goto failed;
   1420     }
   1421     if (!type_override.empty()) {
   1422         if (partition_type != type_override) {
   1423             fprintf(stderr, "Warning: %s type is %s, but %s was requested for formatting.\n",
   1424                     partition, partition_type.c_str(), type_override.c_str());
   1425         }
   1426         partition_type = type_override;
   1427     }
   1428 
   1429     if (!fb_getvar(transport, std::string("partition-size:") + partition, &partition_size)) {
   1430         errMsg = "Unable to get partition size\n";
   1431         goto failed;
   1432     }
   1433     if (!size_override.empty()) {
   1434         if (partition_size != size_override) {
   1435             fprintf(stderr, "Warning: %s size is %s, but %s was requested for formatting.\n",
   1436                     partition, partition_size.c_str(), size_override.c_str());
   1437         }
   1438         partition_size = size_override;
   1439     }
   1440     partition_size = fb_fix_numeric_var(partition_size);
   1441 
   1442     gen = fs_get_generator(partition_type);
   1443     if (!gen) {
   1444         if (skip_if_not_supported) {
   1445             fprintf(stderr, "Erase successful, but not automatically formatting.\n");
   1446             fprintf(stderr, "File system type %s not supported.\n", partition_type.c_str());
   1447             return;
   1448         }
   1449         fprintf(stderr, "Formatting is not supported for file system with type '%s'.\n",
   1450                 partition_type.c_str());
   1451         return;
   1452     }
   1453 
   1454     int64_t size;
   1455     if (!android::base::ParseInt(partition_size, &size)) {
   1456         fprintf(stderr, "Couldn't parse partition size '%s'.\n", partition_size.c_str());
   1457         return;
   1458     }
   1459 
   1460     unsigned eraseBlkSize, logicalBlkSize;
   1461     eraseBlkSize = fb_get_flash_block_size(transport, "erase-block-size");
   1462     logicalBlkSize = fb_get_flash_block_size(transport, "logical-block-size");
   1463 
   1464     if (fs_generator_generate(gen, output.path, size, initial_dir,
   1465             eraseBlkSize, logicalBlkSize)) {
   1466         die("Cannot generate image for %s\n", partition);
   1467         return;
   1468     }
   1469 
   1470     fd.reset(open(output.path, O_RDONLY));
   1471     if (fd == -1) {
   1472         fprintf(stderr, "Cannot open generated image: %s\n", strerror(errno));
   1473         return;
   1474     }
   1475     if (!load_buf_fd(transport, fd.release(), &buf)) {
   1476         fprintf(stderr, "Cannot read image: %s\n", strerror(errno));
   1477         return;
   1478     }
   1479     flash_buf(partition, &buf);
   1480     return;
   1481 
   1482 failed:
   1483     if (skip_if_not_supported) {
   1484         fprintf(stderr, "Erase successful, but not automatically formatting.\n");
   1485         if (errMsg) fprintf(stderr, "%s", errMsg);
   1486     }
   1487     fprintf(stderr, "FAILED (%s)\n", fb_get_error().c_str());
   1488 }
   1489 
   1490 int main(int argc, char **argv)
   1491 {
   1492     bool wants_wipe = false;
   1493     bool wants_reboot = false;
   1494     bool wants_reboot_bootloader = false;
   1495     bool wants_reboot_emergency = false;
   1496     bool skip_reboot = false;
   1497     bool wants_set_active = false;
   1498     bool skip_secondary = false;
   1499     bool erase_first = true;
   1500     bool set_fbe_marker = false;
   1501     void *data;
   1502     int64_t sz;
   1503     int longindex;
   1504     std::string slot_override;
   1505     std::string next_active;
   1506 
   1507     const struct option longopts[] = {
   1508         {"base", required_argument, 0, 'b'},
   1509         {"kernel_offset", required_argument, 0, 'k'},
   1510         {"kernel-offset", required_argument, 0, 'k'},
   1511         {"page_size", required_argument, 0, 'n'},
   1512         {"page-size", required_argument, 0, 'n'},
   1513         {"ramdisk_offset", required_argument, 0, 'r'},
   1514         {"ramdisk-offset", required_argument, 0, 'r'},
   1515         {"tags_offset", required_argument, 0, 't'},
   1516         {"tags-offset", required_argument, 0, 't'},
   1517         {"help", no_argument, 0, 'h'},
   1518         {"unbuffered", no_argument, 0, 0},
   1519         {"version", no_argument, 0, 0},
   1520         {"slot", required_argument, 0, 0},
   1521         {"set_active", optional_argument, 0, 'a'},
   1522         {"set-active", optional_argument, 0, 'a'},
   1523         {"skip-secondary", no_argument, 0, 0},
   1524         {"skip-reboot", no_argument, 0, 0},
   1525         {"disable-verity", no_argument, 0, 0},
   1526         {"disable-verification", no_argument, 0, 0},
   1527 #if !defined(_WIN32)
   1528         {"wipe-and-use-fbe", no_argument, 0, 0},
   1529 #endif
   1530         {0, 0, 0, 0}
   1531     };
   1532 
   1533     serial = getenv("ANDROID_SERIAL");
   1534 
   1535     while (1) {
   1536         int c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lc:i:m:ha::", longopts, &longindex);
   1537         if (c < 0) {
   1538             break;
   1539         }
   1540         /* Alphabetical cases */
   1541         switch (c) {
   1542         case 'a':
   1543             wants_set_active = true;
   1544             if (optarg)
   1545                 next_active = optarg;
   1546             break;
   1547         case 'b':
   1548             base_addr = strtoul(optarg, 0, 16);
   1549             break;
   1550         case 'c':
   1551             cmdline = optarg;
   1552             break;
   1553         case 'h':
   1554             return show_help();
   1555         case 'i': {
   1556                 char *endptr = nullptr;
   1557                 unsigned long val;
   1558 
   1559                 val = strtoul(optarg, &endptr, 0);
   1560                 if (!endptr || *endptr != '\0' || (val & ~0xffff))
   1561                     die("invalid vendor id '%s'", optarg);
   1562                 vendor_id = (unsigned short)val;
   1563                 break;
   1564             }
   1565         case 'k':
   1566             kernel_offset = strtoul(optarg, 0, 16);
   1567             break;
   1568         case 'l':
   1569             long_listing = 1;
   1570             break;
   1571         case 'n':
   1572             page_size = (unsigned)strtoul(optarg, nullptr, 0);
   1573             if (!page_size) die("invalid page size");
   1574             break;
   1575         case 'r':
   1576             ramdisk_offset = strtoul(optarg, 0, 16);
   1577             break;
   1578         case 't':
   1579             tags_offset = strtoul(optarg, 0, 16);
   1580             break;
   1581         case 's':
   1582             serial = optarg;
   1583             break;
   1584         case 'S':
   1585             sparse_limit = parse_num(optarg);
   1586             if (sparse_limit < 0) {
   1587                     die("invalid sparse limit");
   1588             }
   1589             break;
   1590         case 'u':
   1591             erase_first = false;
   1592             break;
   1593         case 'w':
   1594             wants_wipe = true;
   1595             break;
   1596         case '?':
   1597             return 1;
   1598         case 0:
   1599             if (strcmp("unbuffered", longopts[longindex].name) == 0) {
   1600                 setvbuf(stdout, nullptr, _IONBF, 0);
   1601                 setvbuf(stderr, nullptr, _IONBF, 0);
   1602             } else if (strcmp("version", longopts[longindex].name) == 0) {
   1603                 fprintf(stdout, "fastboot version %s\n", FASTBOOT_VERSION);
   1604                 fprintf(stdout, "Installed as %s\n", android::base::GetExecutablePath().c_str());
   1605                 return 0;
   1606             } else if (strcmp("slot", longopts[longindex].name) == 0) {
   1607                 slot_override = std::string(optarg);
   1608             } else if (strcmp("skip-secondary", longopts[longindex].name) == 0 ) {
   1609                 skip_secondary = true;
   1610             } else if (strcmp("skip-reboot", longopts[longindex].name) == 0 ) {
   1611                 skip_reboot = true;
   1612             } else if (strcmp("disable-verity", longopts[longindex].name) == 0 ) {
   1613                 g_disable_verity = true;
   1614             } else if (strcmp("disable-verification", longopts[longindex].name) == 0 ) {
   1615                 g_disable_verification = true;
   1616 #if !defined(_WIN32)
   1617             } else if (strcmp("wipe-and-use-fbe", longopts[longindex].name) == 0) {
   1618                 wants_wipe = true;
   1619                 set_fbe_marker = true;
   1620 #endif
   1621             } else {
   1622                 fprintf(stderr, "Internal error in options processing for %s\n",
   1623                     longopts[longindex].name);
   1624                 return 1;
   1625             }
   1626             break;
   1627         default:
   1628             abort();
   1629         }
   1630     }
   1631 
   1632     argc -= optind;
   1633     argv += optind;
   1634 
   1635     if (argc == 0 && !wants_wipe && !wants_set_active) syntax_error("no command");
   1636 
   1637     if (argc > 0 && !strcmp(*argv, "devices")) {
   1638         list_devices();
   1639         return 0;
   1640     }
   1641 
   1642     if (argc > 0 && !strcmp(*argv, "help")) {
   1643         return show_help();
   1644     }
   1645 
   1646     Transport* transport = open_device();
   1647     if (transport == nullptr) {
   1648         return 1;
   1649     }
   1650 
   1651     if (!supports_AB(transport) && supports_AB_obsolete(transport)) {
   1652         fprintf(stderr, "Warning: Device A/B support is outdated. Bootloader update required.\n");
   1653     }
   1654     if (slot_override != "") slot_override = verify_slot(transport, slot_override);
   1655     if (next_active != "") next_active = verify_slot(transport, next_active, false);
   1656 
   1657     if (wants_set_active) {
   1658         if (next_active == "") {
   1659             if (slot_override == "") {
   1660                 std::string current_slot;
   1661                 if (fb_getvar(transport, "current-slot", &current_slot)) {
   1662                     next_active = verify_slot(transport, current_slot, false);
   1663                 } else {
   1664                     wants_set_active = false;
   1665                 }
   1666             } else {
   1667                 next_active = verify_slot(transport, slot_override, false);
   1668             }
   1669         }
   1670     }
   1671 
   1672     std::vector<std::string> args(argv, argv + argc);
   1673     while (!args.empty()) {
   1674         std::string command = next_arg(&args);
   1675 
   1676         if (command == "getvar") {
   1677             std::string variable = next_arg(&args);
   1678             fb_queue_display(variable.c_str(), variable.c_str());
   1679         } else if (command == "erase") {
   1680             std::string partition = next_arg(&args);
   1681             auto erase = [&](const std::string& partition) {
   1682                 std::string partition_type;
   1683                 if (fb_getvar(transport, std::string("partition-type:") + partition,
   1684                               &partition_type) &&
   1685                     fs_get_generator(partition_type) != nullptr) {
   1686                     fprintf(stderr, "******** Did you mean to fastboot format this %s partition?\n",
   1687                             partition_type.c_str());
   1688                 }
   1689 
   1690                 fb_queue_erase(partition.c_str());
   1691             };
   1692             do_for_partitions(transport, partition, slot_override, erase, true);
   1693         } else if (android::base::StartsWith(command, "format")) {
   1694             // Parsing for: "format[:[type][:[size]]]"
   1695             // Some valid things:
   1696             //  - select only the size, and leave default fs type:
   1697             //    format::0x4000000 userdata
   1698             //  - default fs type and size:
   1699             //    format userdata
   1700             //    format:: userdata
   1701             std::vector<std::string> pieces = android::base::Split(command, ":");
   1702             std::string type_override;
   1703             if (pieces.size() > 1) type_override = pieces[1].c_str();
   1704             std::string size_override;
   1705             if (pieces.size() > 2) size_override = pieces[2].c_str();
   1706 
   1707             std::string partition = next_arg(&args);
   1708 
   1709             auto format = [&](const std::string& partition) {
   1710                 if (erase_first && needs_erase(transport, partition.c_str())) {
   1711                     fb_queue_erase(partition.c_str());
   1712                 }
   1713                 fb_perform_format(transport, partition.c_str(), 0, type_override, size_override,
   1714                                   "");
   1715             };
   1716             do_for_partitions(transport, partition.c_str(), slot_override, format, true);
   1717         } else if (command == "signature") {
   1718             std::string filename = next_arg(&args);
   1719             data = load_file(filename.c_str(), &sz);
   1720             if (data == nullptr) die("could not load '%s': %s", filename.c_str(), strerror(errno));
   1721             if (sz != 256) die("signature must be 256 bytes");
   1722             fb_queue_download("signature", data, sz);
   1723             fb_queue_command("signature", "installing signature");
   1724         } else if (command == "reboot") {
   1725             wants_reboot = true;
   1726 
   1727             if (args.size() == 1) {
   1728                 std::string what = next_arg(&args);
   1729                 if (what == "bootloader") {
   1730                     wants_reboot = false;
   1731                     wants_reboot_bootloader = true;
   1732                 } else if (what == "emergency") {
   1733                     wants_reboot = false;
   1734                     wants_reboot_emergency = true;
   1735                 } else {
   1736                     syntax_error("unknown reboot target %s", what.c_str());
   1737                 }
   1738 
   1739             }
   1740             if (!args.empty()) syntax_error("junk after reboot command");
   1741         } else if (command == "reboot-bootloader") {
   1742             wants_reboot_bootloader = true;
   1743         } else if (command == "continue") {
   1744             fb_queue_command("continue", "resuming boot");
   1745         } else if (command == "boot") {
   1746             std::string kernel = next_arg(&args);
   1747             std::string ramdisk;
   1748             if (!args.empty()) ramdisk = next_arg(&args);
   1749             std::string second_stage;
   1750             if (!args.empty()) second_stage = next_arg(&args);
   1751 
   1752             data = load_bootable_image(kernel, ramdisk, second_stage, &sz, cmdline);
   1753             fb_queue_download("boot.img", data, sz);
   1754             fb_queue_command("boot", "booting");
   1755         } else if (command == "flash") {
   1756             std::string pname = next_arg(&args);
   1757 
   1758             std::string fname;
   1759             if (!args.empty()) {
   1760                 fname = next_arg(&args);
   1761             } else {
   1762                 fname = find_item(pname);
   1763             }
   1764             if (fname.empty()) die("cannot determine image filename for '%s'", pname.c_str());
   1765 
   1766             auto flash = [&](const std::string &partition) {
   1767                 if (erase_first && needs_erase(transport, partition.c_str())) {
   1768                     fb_queue_erase(partition.c_str());
   1769                 }
   1770                 do_flash(transport, partition.c_str(), fname.c_str());
   1771             };
   1772             do_for_partitions(transport, pname.c_str(), slot_override, flash, true);
   1773         } else if (command == "flash:raw") {
   1774             std::string partition = next_arg(&args);
   1775             std::string kernel = next_arg(&args);
   1776             std::string ramdisk;
   1777             if (!args.empty()) ramdisk = next_arg(&args);
   1778             std::string second_stage;
   1779             if (!args.empty()) second_stage = next_arg(&args);
   1780 
   1781             data = load_bootable_image(kernel, ramdisk, second_stage, &sz, cmdline);
   1782             auto flashraw = [&](const std::string& partition) {
   1783                 fb_queue_flash(partition.c_str(), data, sz);
   1784             };
   1785             do_for_partitions(transport, partition, slot_override, flashraw, true);
   1786         } else if (command == "flashall") {
   1787             if (slot_override == "all") {
   1788                 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
   1789                 do_flashall(transport, slot_override, erase_first, true);
   1790             } else {
   1791                 do_flashall(transport, slot_override, erase_first, skip_secondary);
   1792             }
   1793             wants_reboot = true;
   1794         } else if (command == "update") {
   1795             bool slot_all = (slot_override == "all");
   1796             if (slot_all) {
   1797                 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
   1798             }
   1799             std::string filename = "update.zip";
   1800             if (!args.empty()) {
   1801                 filename = next_arg(&args);
   1802             }
   1803             do_update(transport, filename.c_str(), slot_override, erase_first,
   1804                       skip_secondary || slot_all);
   1805             wants_reboot = true;
   1806         } else if (command == "set_active") {
   1807             std::string slot = verify_slot(transport, next_arg(&args), false);
   1808 
   1809             // Legacy support: verify_slot() removes leading underscores, we need to put them back
   1810             // in for old bootloaders. Legacy bootloaders do not have the slot-count variable but
   1811             // do have slot-suffixes.
   1812             std::string var;
   1813             if (!fb_getvar(transport, "slot-count", &var) &&
   1814                     fb_getvar(transport, "slot-suffixes", &var)) {
   1815                 slot = "_" + slot;
   1816             }
   1817             fb_set_active(slot.c_str());
   1818         } else if (command == "stage") {
   1819             std::string filename = next_arg(&args);
   1820 
   1821             struct fastboot_buffer buf;
   1822             if (!load_buf(transport, filename.c_str(), &buf) || buf.type != FB_BUFFER_FD) {
   1823                 die("cannot load '%s'", filename.c_str());
   1824             }
   1825             fb_queue_download_fd(filename.c_str(), buf.fd, buf.sz);
   1826         } else if (command == "get_staged") {
   1827             std::string filename = next_arg(&args);
   1828             fb_queue_upload(filename.c_str());
   1829         } else if (command == "oem") {
   1830             do_oem_command("oem", &args);
   1831         } else if (command == "flashing") {
   1832             if (args.empty()) {
   1833                 syntax_error("missing 'flashing' command");
   1834             } else if (args.size() == 1 && (args[0] == "unlock" || args[0] == "lock" ||
   1835                                             args[0] == "unlock_critical" ||
   1836                                             args[0] == "lock_critical" ||
   1837                                             args[0] == "get_unlock_ability" ||
   1838                                             args[0] == "get_unlock_bootloader_nonce" ||
   1839                                             args[0] == "lock_bootloader")) {
   1840                 do_oem_command("flashing", &args);
   1841             } else if (args.size() == 2 && args[0] == "unlock_bootloader") {
   1842                 do_bypass_unlock_command(&args);
   1843             } else {
   1844                 syntax_error("unknown 'flashing' command %s", args[0].c_str());
   1845             }
   1846         } else {
   1847             syntax_error("unknown command %s", command.c_str());
   1848         }
   1849     }
   1850 
   1851     if (wants_wipe) {
   1852         fprintf(stderr, "wiping userdata...\n");
   1853         fb_queue_erase("userdata");
   1854         if (set_fbe_marker) {
   1855             fprintf(stderr, "setting FBE marker...\n");
   1856             std::string initial_userdata_dir = create_fbemarker_tmpdir();
   1857             if (initial_userdata_dir.empty()) {
   1858                 return 1;
   1859             }
   1860             fb_perform_format(transport, "userdata", 1, "", "", initial_userdata_dir);
   1861             delete_fbemarker_tmpdir(initial_userdata_dir);
   1862         } else {
   1863             fb_perform_format(transport, "userdata", 1, "", "", "");
   1864         }
   1865 
   1866         std::string cache_type;
   1867         if (fb_getvar(transport, "partition-type:cache", &cache_type) && !cache_type.empty()) {
   1868             fprintf(stderr, "wiping cache...\n");
   1869             fb_queue_erase("cache");
   1870             fb_perform_format(transport, "cache", 1, "", "", "");
   1871         }
   1872     }
   1873     if (wants_set_active) {
   1874         fb_set_active(next_active.c_str());
   1875     }
   1876     if (wants_reboot && !skip_reboot) {
   1877         fb_queue_reboot();
   1878         fb_queue_wait_for_disconnect();
   1879     } else if (wants_reboot_bootloader) {
   1880         fb_queue_command("reboot-bootloader", "rebooting into bootloader");
   1881         fb_queue_wait_for_disconnect();
   1882     } else if (wants_reboot_emergency) {
   1883         fb_queue_command("reboot-emergency", "rebooting into emergency download (EDL) mode");
   1884         fb_queue_wait_for_disconnect();
   1885     }
   1886 
   1887     return fb_execute_queue(transport) ? EXIT_FAILURE : EXIT_SUCCESS;
   1888 }
   1889