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