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 "fastboot.h"
30 
31 #include <ctype.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <getopt.h>
35 #include <inttypes.h>
36 #include <limits.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sys/stat.h>
42 #include <sys/time.h>
43 #include <sys/types.h>
44 #include <unistd.h>
45 
46 #include <chrono>
47 #include <functional>
48 #include <regex>
49 #include <string>
50 #include <thread>
51 #include <utility>
52 #include <vector>
53 
54 #include <android-base/endian.h>
55 #include <android-base/file.h>
56 #include <android-base/macros.h>
57 #include <android-base/parseint.h>
58 #include <android-base/parsenetaddress.h>
59 #include <android-base/stringprintf.h>
60 #include <android-base/strings.h>
61 #include <android-base/unique_fd.h>
62 #include <build/version.h>
63 #include <libavb/libavb.h>
64 #include <liblp/liblp.h>
65 #include <platform_tools_version.h>
66 #include <sparse/sparse.h>
67 #include <ziparchive/zip_archive.h>
68 
69 #include "bootimg_utils.h"
70 #include "constants.h"
71 #include "diagnose_usb.h"
72 #include "fastboot_driver.h"
73 #include "fs.h"
74 #include "tcp.h"
75 #include "transport.h"
76 #include "udp.h"
77 #include "usb.h"
78 #include "util.h"
79 
80 using android::base::ReadFully;
81 using android::base::Split;
82 using android::base::Trim;
83 using android::base::unique_fd;
84 using namespace std::string_literals;
85 
86 static const char* serial = nullptr;
87 
88 static bool g_long_listing = false;
89 // Don't resparse files in too-big chunks.
90 // libsparse will support INT_MAX, but this results in large allocations, so
91 // let's keep it at 1GB to avoid memory pressure on the host.
92 static constexpr int64_t RESPARSE_LIMIT = 1 * 1024 * 1024 * 1024;
93 static uint64_t sparse_limit = 0;
94 static int64_t target_sparse_limit = -1;
95 
96 static unsigned g_base_addr = 0x10000000;
97 static boot_img_hdr_v2 g_boot_img_hdr = {};
98 static std::string g_cmdline;
99 static std::string g_dtb_path;
100 
101 static bool g_disable_verity = false;
102 static bool g_disable_verification = false;
103 
104 static const std::string convert_fbe_marker_filename("convert_fbe");
105 
106 fastboot::FastBootDriver* fb = nullptr;
107 
108 enum fb_buffer_type {
109     FB_BUFFER_FD,
110     FB_BUFFER_SPARSE,
111 };
112 
113 struct fastboot_buffer {
114     enum fb_buffer_type type;
115     void* data;
116     int64_t sz;
117     int fd;
118     int64_t image_size;
119 };
120 
121 enum class ImageType {
122     // Must be flashed for device to boot into the kernel.
123     BootCritical,
124     // Normal partition to be flashed during "flashall".
125     Normal,
126     // Partition that is never flashed during "flashall".
127     Extra
128 };
129 
130 struct Image {
131     const char* nickname;
132     const char* img_name;
133     const char* sig_name;
134     const char* part_name;
135     bool optional_if_no_image;
136     ImageType type;
IsSecondaryImage137     bool IsSecondary() const { return nickname == nullptr; }
138 };
139 
140 static Image images[] = {
141         // clang-format off
142     { "boot",     "boot.img",         "boot.sig",     "boot",     false, ImageType::BootCritical },
143     { nullptr,    "boot_other.img",   "boot.sig",     "boot",     true,  ImageType::Normal },
144     { "cache",    "cache.img",        "cache.sig",    "cache",    true,  ImageType::Extra },
145     { "dtbo",     "dtbo.img",         "dtbo.sig",     "dtbo",     true,  ImageType::BootCritical },
146     { "dts",      "dt.img",           "dt.sig",       "dts",      true,  ImageType::BootCritical },
147     { "odm",      "odm.img",          "odm.sig",      "odm",      true,  ImageType::Normal },
148     { "odm_dlkm", "odm_dlkm.img",     "odm_dlkm.sig", "odm_dlkm", true,  ImageType::Normal },
149     { "product",  "product.img",      "product.sig",  "product",  true,  ImageType::Normal },
150     { "recovery", "recovery.img",     "recovery.sig", "recovery", true,  ImageType::BootCritical },
151     { "super",    "super.img",        "super.sig",    "super",    true,  ImageType::Extra },
152     { "system",   "system.img",       "system.sig",   "system",   false, ImageType::Normal },
153     { "system_ext",
154                   "system_ext.img",   "system_ext.sig",
155                                                       "system_ext",
156                                                                   true,  ImageType::Normal },
157     { nullptr,    "system_other.img", "system.sig",   "system",   true,  ImageType::Normal },
158     { "userdata", "userdata.img",     "userdata.sig", "userdata", true,  ImageType::Extra },
159     { "vbmeta",   "vbmeta.img",       "vbmeta.sig",   "vbmeta",   true,  ImageType::BootCritical },
160     { "vbmeta_system",
161                   "vbmeta_system.img",
162                                       "vbmeta_system.sig",
163                                                       "vbmeta_system",
164                                                                   true,  ImageType::BootCritical },
165     { "vendor",   "vendor.img",       "vendor.sig",   "vendor",   true,  ImageType::Normal },
166     { "vendor_boot",
167                   "vendor_boot.img",  "vendor_boot.sig",
168                                                       "vendor_boot",
169                                                                   true,  ImageType::BootCritical },
170     { "vendor_dlkm",
171                   "vendor_dlkm.img",  "vendor_dlkm.sig",
172                                                       "vendor_dlkm",
173                                                                   true,  ImageType::Normal },
174     { nullptr,    "vendor_other.img", "vendor.sig",   "vendor",   true,  ImageType::Normal },
175         // clang-format on
176 };
177 
get_android_product_out()178 static char* get_android_product_out() {
179     char* dir = getenv("ANDROID_PRODUCT_OUT");
180     if (dir == nullptr || dir[0] == '\0') {
181         return nullptr;
182     }
183     return dir;
184 }
185 
find_item_given_name(const std::string & img_name)186 static std::string find_item_given_name(const std::string& img_name) {
187     char* dir = get_android_product_out();
188     if (!dir) {
189         die("ANDROID_PRODUCT_OUT not set");
190     }
191     return std::string(dir) + "/" + img_name;
192 }
193 
find_item(const std::string & item)194 static std::string find_item(const std::string& item) {
195     for (size_t i = 0; i < arraysize(images); ++i) {
196         if (images[i].nickname && item == images[i].nickname) {
197             return find_item_given_name(images[i].img_name);
198         }
199     }
200 
201     fprintf(stderr, "unknown partition '%s'\n", item.c_str());
202     return "";
203 }
204 
205 double last_start_time;
206 
Status(const std::string & message)207 static void Status(const std::string& message) {
208     if (!message.empty()) {
209         static constexpr char kStatusFormat[] = "%-50s ";
210         fprintf(stderr, kStatusFormat, message.c_str());
211     }
212     last_start_time = now();
213 }
214 
Epilog(int status)215 static void Epilog(int status) {
216     if (status) {
217         fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
218         die("Command failed");
219     } else {
220         double split = now();
221         fprintf(stderr, "OKAY [%7.3fs]\n", (split - last_start_time));
222     }
223 }
224 
InfoMessage(const std::string & info)225 static void InfoMessage(const std::string& info) {
226     fprintf(stderr, "(bootloader) %s\n", info.c_str());
227 }
228 
get_file_size(int fd)229 static int64_t get_file_size(int fd) {
230     struct stat sb;
231     if (fstat(fd, &sb) == -1) {
232         die("could not get file size");
233     }
234     return sb.st_size;
235 }
236 
ReadFileToVector(const std::string & file,std::vector<char> * out)237 bool ReadFileToVector(const std::string& file, std::vector<char>* out) {
238     out->clear();
239 
240     unique_fd fd(TEMP_FAILURE_RETRY(open(file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY)));
241     if (fd == -1) {
242         return false;
243     }
244 
245     out->resize(get_file_size(fd));
246     return ReadFully(fd, out->data(), out->size());
247 }
248 
match_fastboot_with_serial(usb_ifc_info * info,const char * local_serial)249 static int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
250     if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
251         return -1;
252     }
253 
254     // require matching serial number or device path if requested
255     // at the command line with the -s option.
256     if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
257                    strcmp(local_serial, info->device_path) != 0)) return -1;
258     return 0;
259 }
260 
match_fastboot(usb_ifc_info * info)261 static int match_fastboot(usb_ifc_info* info) {
262     return match_fastboot_with_serial(info, serial);
263 }
264 
list_devices_callback(usb_ifc_info * info)265 static int list_devices_callback(usb_ifc_info* info) {
266     if (match_fastboot_with_serial(info, nullptr) == 0) {
267         std::string serial = info->serial_number;
268         std::string interface = info->interface;
269         if (interface.empty()) {
270             interface = "fastboot";
271         }
272         if (!info->writable) {
273             serial = UsbNoPermissionsShortHelpText();
274         }
275         if (!serial[0]) {
276             serial = "????????????";
277         }
278         // output compatible with "adb devices"
279         if (!g_long_listing) {
280             printf("%s\t%s", serial.c_str(), interface.c_str());
281         } else {
282             printf("%-22s %s", serial.c_str(), interface.c_str());
283             if (strlen(info->device_path) > 0) printf(" %s", info->device_path);
284         }
285         putchar('\n');
286     }
287 
288     return -1;
289 }
290 
291 // Opens a new Transport connected to a device. If |serial| is non-null it will be used to identify
292 // a specific device, otherwise the first USB device found will be used.
293 //
294 // If |serial| is non-null but invalid, this exits.
295 // Otherwise it blocks until the target is available.
296 //
297 // The returned Transport is a singleton, so multiple calls to this function will return the same
298 // object, and the caller should not attempt to delete the returned Transport.
open_device()299 static Transport* open_device() {
300     bool announce = true;
301 
302     Socket::Protocol protocol = Socket::Protocol::kTcp;
303     std::string host;
304     int port = 0;
305     if (serial != nullptr) {
306         const char* net_address = nullptr;
307 
308         if (android::base::StartsWith(serial, "tcp:")) {
309             protocol = Socket::Protocol::kTcp;
310             port = tcp::kDefaultPort;
311             net_address = serial + strlen("tcp:");
312         } else if (android::base::StartsWith(serial, "udp:")) {
313             protocol = Socket::Protocol::kUdp;
314             port = udp::kDefaultPort;
315             net_address = serial + strlen("udp:");
316         }
317 
318         if (net_address != nullptr) {
319             std::string error;
320             if (!android::base::ParseNetAddress(net_address, &host, &port, nullptr, &error)) {
321                 die("invalid network address '%s': %s\n", net_address, error.c_str());
322             }
323         }
324     }
325 
326     Transport* transport = nullptr;
327     while (true) {
328         if (!host.empty()) {
329             std::string error;
330             if (protocol == Socket::Protocol::kTcp) {
331                 transport = tcp::Connect(host, port, &error).release();
332             } else if (protocol == Socket::Protocol::kUdp) {
333                 transport = udp::Connect(host, port, &error).release();
334             }
335 
336             if (transport == nullptr && announce) {
337                 fprintf(stderr, "error: %s\n", error.c_str());
338             }
339         } else {
340             transport = usb_open(match_fastboot);
341         }
342 
343         if (transport != nullptr) {
344             return transport;
345         }
346 
347         if (announce) {
348             announce = false;
349             fprintf(stderr, "< waiting for %s >\n", serial ? serial : "any device");
350         }
351         std::this_thread::sleep_for(std::chrono::milliseconds(1));
352     }
353 }
354 
list_devices()355 static void list_devices() {
356     // We don't actually open a USB device here,
357     // just getting our callback called so we can
358     // list all the connected devices.
359     usb_open(list_devices_callback);
360 }
361 
syntax_error(const char * fmt,...)362 static void syntax_error(const char* fmt, ...) {
363     fprintf(stderr, "fastboot: usage: ");
364 
365     va_list ap;
366     va_start(ap, fmt);
367     vfprintf(stderr, fmt, ap);
368     va_end(ap);
369 
370     fprintf(stderr, "\n");
371     exit(1);
372 }
373 
show_help()374 static int show_help() {
375     // clang-format off
376     fprintf(stdout,
377 //                    1         2         3         4         5         6         7         8
378 //           12345678901234567890123456789012345678901234567890123456789012345678901234567890
379             "usage: fastboot [OPTION...] COMMAND...\n"
380             "\n"
381             "flashing:\n"
382             " update ZIP                 Flash all partitions from an update.zip package.\n"
383             " flashall                   Flash all partitions from $ANDROID_PRODUCT_OUT.\n"
384             "                            On A/B devices, flashed slot is set as active.\n"
385             "                            Secondary images may be flashed to inactive slot.\n"
386             " flash PARTITION [FILENAME] Flash given partition, using the image from\n"
387             "                            $ANDROID_PRODUCT_OUT if no filename is given.\n"
388             "\n"
389             "basics:\n"
390             " devices [-l]               List devices in bootloader (-l: with device paths).\n"
391             " getvar NAME                Display given bootloader variable.\n"
392             " reboot [bootloader]        Reboot device.\n"
393             "\n"
394             "locking/unlocking:\n"
395             " flashing lock|unlock       Lock/unlock partitions for flashing\n"
396             " flashing lock_critical|unlock_critical\n"
397             "                            Lock/unlock 'critical' bootloader partitions.\n"
398             " flashing get_unlock_ability\n"
399             "                            Check whether unlocking is allowed (1) or not(0).\n"
400             "\n"
401             "advanced:\n"
402             " erase PARTITION            Erase a flash partition.\n"
403             " format[:FS_TYPE[:SIZE]] PARTITION\n"
404             "                            Format a flash partition.\n"
405             " set_active SLOT            Set the active slot.\n"
406             " oem [COMMAND...]           Execute OEM-specific command.\n"
407             " gsi wipe|disable           Wipe or disable a GSI installation (fastbootd only).\n"
408             " wipe-super [SUPER_EMPTY]   Wipe the super partition. This will reset it to\n"
409             "                            contain an empty set of default dynamic partitions.\n"
410             " snapshot-update cancel     On devices that support snapshot-based updates, cancel\n"
411             "                            an in-progress update. This may make the device\n"
412             "                            unbootable until it is reflashed.\n"
413             " snapshot-update merge      On devices that support snapshot-based updates, finish\n"
414             "                            an in-progress update if it is in the \"merging\"\n"
415             "                            phase.\n"
416             "\n"
417             "boot image:\n"
418             " boot KERNEL [RAMDISK [SECOND]]\n"
419             "                            Download and boot kernel from RAM.\n"
420             " flash:raw PARTITION KERNEL [RAMDISK [SECOND]]\n"
421             "                            Create boot image and flash it.\n"
422             " --dtb DTB                  Specify path to DTB for boot image header version 2.\n"
423             " --cmdline CMDLINE          Override kernel command line.\n"
424             " --base ADDRESS             Set kernel base address (default: 0x10000000).\n"
425             " --kernel-offset            Set kernel offset (default: 0x00008000).\n"
426             " --ramdisk-offset           Set ramdisk offset (default: 0x01000000).\n"
427             " --tags-offset              Set tags offset (default: 0x00000100).\n"
428             " --dtb-offset               Set dtb offset (default: 0x01100000).\n"
429             " --page-size BYTES          Set flash page size (default: 2048).\n"
430             " --header-version VERSION   Set boot image header version.\n"
431             " --os-version MAJOR[.MINOR[.PATCH]]\n"
432             "                            Set boot image OS version (default: 0.0.0).\n"
433             " --os-patch-level YYYY-MM-DD\n"
434             "                            Set boot image OS security patch level.\n"
435             // TODO: still missing: `second_addr`, `name`, `id`, `recovery_dtbo_*`.
436             "\n"
437             // TODO: what device(s) used this? is there any documentation?
438             //" continue                               Continue with autoboot.\n"
439             //"\n"
440             "Android Things:\n"
441             " stage IN_FILE              Sends given file to stage for the next command.\n"
442             " get_staged OUT_FILE        Writes data staged by the last command to a file.\n"
443             "\n"
444             "options:\n"
445             " -w                         Wipe userdata.\n"
446             " -s SERIAL                  Specify a USB device.\n"
447             " -s tcp|udp:HOST[:PORT]     Specify a network device.\n"
448             " -S SIZE[K|M|G]             Break into sparse files no larger than SIZE.\n"
449             " --force                    Force a flash operation that may be unsafe.\n"
450             " --slot SLOT                Use SLOT; 'all' for both slots, 'other' for\n"
451             "                            non-current slot (default: current active slot).\n"
452             " --set-active[=SLOT]        Sets the active slot before rebooting.\n"
453             " --skip-secondary           Don't flash secondary slots in flashall/update.\n"
454             " --skip-reboot              Don't reboot device after flashing.\n"
455             " --disable-verity           Sets disable-verity when flashing vbmeta.\n"
456             " --disable-verification     Sets disable-verification when flashing vbmeta.\n"
457 #if !defined(_WIN32)
458             " --wipe-and-use-fbe         Enable file-based encryption, wiping userdata.\n"
459 #endif
460             // TODO: remove --unbuffered?
461             " --unbuffered               Don't buffer input or output.\n"
462             " --verbose, -v              Verbose output.\n"
463             " --version                  Display version.\n"
464             " --help, -h                 Show this message.\n"
465         );
466     // clang-format off
467     return 0;
468 }
469 
LoadBootableImage(const std::string & kernel,const std::string & ramdisk,const std::string & second_stage)470 static std::vector<char> LoadBootableImage(const std::string& kernel, const std::string& ramdisk,
471                                            const std::string& second_stage) {
472     std::vector<char> kernel_data;
473     if (!ReadFileToVector(kernel, &kernel_data)) {
474         die("cannot load '%s': %s", kernel.c_str(), strerror(errno));
475     }
476 
477     // Is this actually a boot image?
478     if (kernel_data.size() < sizeof(boot_img_hdr_v3)) {
479         die("cannot load '%s': too short", kernel.c_str());
480     }
481     if (!memcmp(kernel_data.data(), BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
482         if (!g_cmdline.empty()) {
483             bootimg_set_cmdline(reinterpret_cast<boot_img_hdr_v2*>(kernel_data.data()), g_cmdline);
484         }
485 
486         if (!ramdisk.empty()) die("cannot boot a boot.img *and* ramdisk");
487 
488         return kernel_data;
489     }
490 
491     std::vector<char> ramdisk_data;
492     if (!ramdisk.empty()) {
493         if (!ReadFileToVector(ramdisk, &ramdisk_data)) {
494             die("cannot load '%s': %s", ramdisk.c_str(), strerror(errno));
495         }
496     }
497 
498     std::vector<char> second_stage_data;
499     if (!second_stage.empty()) {
500         if (!ReadFileToVector(second_stage, &second_stage_data)) {
501             die("cannot load '%s': %s", second_stage.c_str(), strerror(errno));
502         }
503     }
504 
505     std::vector<char> dtb_data;
506     if (!g_dtb_path.empty()) {
507         if (g_boot_img_hdr.header_version != 2) {
508                     die("Argument dtb not supported for boot image header version %d\n",
509                         g_boot_img_hdr.header_version);
510         }
511         if (!ReadFileToVector(g_dtb_path, &dtb_data)) {
512             die("cannot load '%s': %s", g_dtb_path.c_str(), strerror(errno));
513         }
514     }
515 
516     fprintf(stderr,"creating boot image...\n");
517 
518     std::vector<char> out;
519     boot_img_hdr_v2* boot_image_data = mkbootimg(kernel_data, ramdisk_data, second_stage_data,
520                                                  dtb_data, g_base_addr, g_boot_img_hdr, &out);
521 
522     if (!g_cmdline.empty()) bootimg_set_cmdline(boot_image_data, g_cmdline);
523     fprintf(stderr, "creating boot image - %zu bytes\n", out.size());
524     return out;
525 }
526 
UnzipToMemory(ZipArchiveHandle zip,const std::string & entry_name,std::vector<char> * out)527 static bool UnzipToMemory(ZipArchiveHandle zip, const std::string& entry_name,
528                           std::vector<char>* out) {
529     ZipEntry zip_entry;
530     if (FindEntry(zip, entry_name, &zip_entry) != 0) {
531         fprintf(stderr, "archive does not contain '%s'\n", entry_name.c_str());
532         return false;
533     }
534 
535     out->resize(zip_entry.uncompressed_length);
536 
537     fprintf(stderr, "extracting %s (%zu MB) to RAM...\n", entry_name.c_str(),
538             out->size() / 1024 / 1024);
539 
540     int error = ExtractToMemory(zip, &zip_entry, reinterpret_cast<uint8_t*>(out->data()),
541                                 out->size());
542     if (error != 0) die("failed to extract '%s': %s", entry_name.c_str(), ErrorCodeString(error));
543 
544     return true;
545 }
546 
547 #if defined(_WIN32)
548 
549 // TODO: move this to somewhere it can be shared.
550 
551 #include <windows.h>
552 
553 // Windows' tmpfile(3) requires administrator rights because
554 // it creates temporary files in the root directory.
win32_tmpfile()555 static FILE* win32_tmpfile() {
556     char temp_path[PATH_MAX];
557     DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
558     if (nchars == 0 || nchars >= sizeof(temp_path)) {
559         die("GetTempPath failed, error %ld", GetLastError());
560     }
561 
562     char filename[PATH_MAX];
563     if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
564         die("GetTempFileName failed, error %ld", GetLastError());
565     }
566 
567     return fopen(filename, "w+bTD");
568 }
569 
570 #define tmpfile win32_tmpfile
571 
make_temporary_directory()572 static std::string make_temporary_directory() {
573     die("make_temporary_directory not supported under Windows, sorry!");
574 }
575 
make_temporary_fd(const char *)576 static int make_temporary_fd(const char* /*what*/) {
577     // TODO: reimplement to avoid leaking a FILE*.
578     return fileno(tmpfile());
579 }
580 
581 #else
582 
make_temporary_template()583 static std::string make_temporary_template() {
584     const char* tmpdir = getenv("TMPDIR");
585     if (tmpdir == nullptr) tmpdir = P_tmpdir;
586     return std::string(tmpdir) + "/fastboot_userdata_XXXXXX";
587 }
588 
make_temporary_directory()589 static std::string make_temporary_directory() {
590     std::string result(make_temporary_template());
591     if (mkdtemp(&result[0]) == nullptr) {
592         die("unable to create temporary directory with template %s: %s",
593             result.c_str(), strerror(errno));
594     }
595     return result;
596 }
597 
make_temporary_fd(const char * what)598 static int make_temporary_fd(const char* what) {
599     std::string path_template(make_temporary_template());
600     int fd = mkstemp(&path_template[0]);
601     if (fd == -1) {
602         die("failed to create temporary file for %s with template %s: %s\n",
603             path_template.c_str(), what, strerror(errno));
604     }
605     unlink(path_template.c_str());
606     return fd;
607 }
608 
609 #endif
610 
create_fbemarker_tmpdir()611 static std::string create_fbemarker_tmpdir() {
612     std::string dir = make_temporary_directory();
613     std::string marker_file = dir + "/" + convert_fbe_marker_filename;
614     int fd = open(marker_file.c_str(), O_CREAT | O_WRONLY | O_CLOEXEC, 0666);
615     if (fd == -1) {
616         die("unable to create FBE marker file %s locally: %s",
617             marker_file.c_str(), strerror(errno));
618     }
619     close(fd);
620     return dir;
621 }
622 
delete_fbemarker_tmpdir(const std::string & dir)623 static void delete_fbemarker_tmpdir(const std::string& dir) {
624     std::string marker_file = dir + "/" + convert_fbe_marker_filename;
625     if (unlink(marker_file.c_str()) == -1) {
626         fprintf(stderr, "Unable to delete FBE marker file %s locally: %d, %s\n",
627             marker_file.c_str(), errno, strerror(errno));
628         return;
629     }
630     if (rmdir(dir.c_str()) == -1) {
631         fprintf(stderr, "Unable to delete FBE marker directory %s locally: %d, %s\n",
632             dir.c_str(), errno, strerror(errno));
633         return;
634     }
635 }
636 
unzip_to_file(ZipArchiveHandle zip,const char * entry_name)637 static int unzip_to_file(ZipArchiveHandle zip, const char* entry_name) {
638     unique_fd fd(make_temporary_fd(entry_name));
639 
640     ZipEntry zip_entry;
641     if (FindEntry(zip, entry_name, &zip_entry) != 0) {
642         fprintf(stderr, "archive does not contain '%s'\n", entry_name);
643         errno = ENOENT;
644         return -1;
645     }
646 
647     fprintf(stderr, "extracting %s (%" PRIu32 " MB) to disk...", entry_name,
648             zip_entry.uncompressed_length / 1024 / 1024);
649     double start = now();
650     int error = ExtractEntryToFile(zip, &zip_entry, fd);
651     if (error != 0) {
652         die("\nfailed to extract '%s': %s", entry_name, ErrorCodeString(error));
653     }
654 
655     if (lseek(fd, 0, SEEK_SET) != 0) {
656         die("\nlseek on extracted file '%s' failed: %s", entry_name, strerror(errno));
657     }
658 
659     fprintf(stderr, " took %.3fs\n", now() - start);
660 
661     return fd.release();
662 }
663 
CheckRequirement(const std::string & cur_product,const std::string & var,const std::string & product,bool invert,const std::vector<std::string> & options)664 static void CheckRequirement(const std::string& cur_product, const std::string& var,
665                              const std::string& product, bool invert,
666                              const std::vector<std::string>& options) {
667     Status("Checking '" + var + "'");
668 
669     double start = now();
670 
671     if (!product.empty()) {
672         if (product != cur_product) {
673             double split = now();
674             fprintf(stderr, "IGNORE, product is %s required only for %s [%7.3fs]\n",
675                     cur_product.c_str(), product.c_str(), (split - start));
676             return;
677         }
678     }
679 
680     std::string var_value;
681     if (fb->GetVar(var, &var_value) != fastboot::SUCCESS) {
682         fprintf(stderr, "FAILED\n\n");
683         fprintf(stderr, "Could not getvar for '%s' (%s)\n\n", var.c_str(),
684                 fb->Error().c_str());
685         die("requirements not met!");
686     }
687 
688     bool match = false;
689     for (const auto& option : options) {
690         if (option == var_value || (option.back() == '*' &&
691                                     !var_value.compare(0, option.length() - 1, option, 0,
692                                                        option.length() - 1))) {
693             match = true;
694             break;
695         }
696     }
697 
698     if (invert) {
699         match = !match;
700     }
701 
702     if (match) {
703         double split = now();
704         fprintf(stderr, "OKAY [%7.3fs]\n", (split - start));
705         return;
706     }
707 
708     fprintf(stderr, "FAILED\n\n");
709     fprintf(stderr, "Device %s is '%s'.\n", var.c_str(), var_value.c_str());
710     fprintf(stderr, "Update %s '%s'", invert ? "rejects" : "requires", options[0].c_str());
711     for (auto it = std::next(options.begin()); it != options.end(); ++it) {
712         fprintf(stderr, " or '%s'", it->c_str());
713     }
714     fprintf(stderr, ".\n\n");
715     die("requirements not met!");
716 }
717 
ParseRequirementLine(const std::string & line,std::string * name,std::string * product,bool * invert,std::vector<std::string> * options)718 bool ParseRequirementLine(const std::string& line, std::string* name, std::string* product,
719                           bool* invert, std::vector<std::string>* options) {
720     // "require product=alpha|beta|gamma"
721     // "require version-bootloader=1234"
722     // "require-for-product:gamma version-bootloader=istanbul|constantinople"
723     // "require partition-exists=vendor"
724     *product = "";
725     *invert = false;
726 
727     auto require_reject_regex = std::regex{"(require\\s+|reject\\s+)?\\s*(\\S+)\\s*=\\s*(.*)"};
728     auto require_product_regex =
729             std::regex{"require-for-product:\\s*(\\S+)\\s+(\\S+)\\s*=\\s*(.*)"};
730     std::smatch match_results;
731 
732     if (std::regex_match(line, match_results, require_reject_regex)) {
733         *invert = Trim(match_results[1]) == "reject";
734     } else if (std::regex_match(line, match_results, require_product_regex)) {
735         *product = match_results[1];
736     } else {
737         return false;
738     }
739 
740     *name = match_results[2];
741     // Work around an unfortunate name mismatch.
742     if (*name == "board") {
743         *name = "product";
744     }
745 
746     auto raw_options = Split(match_results[3], "|");
747     for (const auto& option : raw_options) {
748         auto trimmed_option = Trim(option);
749         options->emplace_back(trimmed_option);
750     }
751 
752     return true;
753 }
754 
755 // "require partition-exists=x" is a special case, added because of the trouble we had when
756 // Pixel 2 shipped with new partitions and users used old versions of fastboot to flash them,
757 // missing out new partitions. A device with new partitions can use "partition-exists" to
758 // override the fields `optional_if_no_image` in the `images` array.
HandlePartitionExists(const std::vector<std::string> & options)759 static void HandlePartitionExists(const std::vector<std::string>& options) {
760     const std::string& partition_name = options[0];
761     std::string has_slot;
762     if (fb->GetVar("has-slot:" + partition_name, &has_slot) != fastboot::SUCCESS ||
763         (has_slot != "yes" && has_slot != "no")) {
764         die("device doesn't have required partition %s!", partition_name.c_str());
765     }
766     bool known_partition = false;
767     for (size_t i = 0; i < arraysize(images); ++i) {
768         if (images[i].nickname && images[i].nickname == partition_name) {
769             images[i].optional_if_no_image = false;
770             known_partition = true;
771         }
772     }
773     if (!known_partition) {
774         die("device requires partition %s which is not known to this version of fastboot",
775             partition_name.c_str());
776     }
777 }
778 
CheckRequirements(const std::string & data)779 static void CheckRequirements(const std::string& data) {
780     std::string cur_product;
781     if (fb->GetVar("product", &cur_product) != fastboot::SUCCESS) {
782         fprintf(stderr, "getvar:product FAILED (%s)\n", fb->Error().c_str());
783     }
784 
785     auto lines = Split(data, "\n");
786     for (const auto& line : lines) {
787         if (line.empty()) {
788             continue;
789         }
790 
791         std::string name;
792         std::string product;
793         bool invert;
794         std::vector<std::string> options;
795 
796         if (!ParseRequirementLine(line, &name, &product, &invert, &options)) {
797             fprintf(stderr, "android-info.txt syntax error: %s\n", line.c_str());
798             continue;
799         }
800         if (name == "partition-exists") {
801             HandlePartitionExists(options);
802         } else {
803             CheckRequirement(cur_product, name, product, invert, options);
804         }
805     }
806 }
807 
DisplayVarOrError(const std::string & label,const std::string & var)808 static void DisplayVarOrError(const std::string& label, const std::string& var) {
809     std::string value;
810 
811     if (fb->GetVar(var, &value) != fastboot::SUCCESS) {
812         Status("getvar:" + var);
813         fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
814         return;
815     }
816     fprintf(stderr, "%s: %s\n", label.c_str(), value.c_str());
817 }
818 
DumpInfo()819 static void DumpInfo() {
820     fprintf(stderr, "--------------------------------------------\n");
821     DisplayVarOrError("Bootloader Version...", "version-bootloader");
822     DisplayVarOrError("Baseband Version.....", "version-baseband");
823     DisplayVarOrError("Serial Number........", "serialno");
824     fprintf(stderr, "--------------------------------------------\n");
825 
826 }
827 
load_sparse_files(int fd,int64_t max_size)828 static struct sparse_file** load_sparse_files(int fd, int64_t max_size) {
829     struct sparse_file* s = sparse_file_import_auto(fd, false, true);
830     if (!s) die("cannot sparse read file");
831 
832     if (max_size <= 0 || max_size > std::numeric_limits<uint32_t>::max()) {
833       die("invalid max size %" PRId64, max_size);
834     }
835 
836     int files = sparse_file_resparse(s, max_size, nullptr, 0);
837     if (files < 0) die("Failed to resparse");
838 
839     sparse_file** out_s = reinterpret_cast<sparse_file**>(calloc(sizeof(struct sparse_file *), files + 1));
840     if (!out_s) die("Failed to allocate sparse file array");
841 
842     files = sparse_file_resparse(s, max_size, out_s, files);
843     if (files < 0) die("Failed to resparse");
844 
845     return out_s;
846 }
847 
get_target_sparse_limit()848 static int64_t get_target_sparse_limit() {
849     std::string max_download_size;
850     if (fb->GetVar("max-download-size", &max_download_size) != fastboot::SUCCESS ||
851         max_download_size.empty()) {
852         verbose("target didn't report max-download-size");
853         return 0;
854     }
855 
856     // Some bootloaders (angler, for example) send spurious whitespace too.
857     max_download_size = android::base::Trim(max_download_size);
858 
859     uint64_t limit;
860     if (!android::base::ParseUint(max_download_size, &limit)) {
861         fprintf(stderr, "couldn't parse max-download-size '%s'\n", max_download_size.c_str());
862         return 0;
863     }
864     if (limit > 0) verbose("target reported max download size of %" PRId64 " bytes", limit);
865     return limit;
866 }
867 
get_sparse_limit(int64_t size)868 static int64_t get_sparse_limit(int64_t size) {
869     int64_t limit = sparse_limit;
870     if (limit == 0) {
871         // Unlimited, so see what the target device's limit is.
872         // TODO: shouldn't we apply this limit even if you've used -S?
873         if (target_sparse_limit == -1) {
874             target_sparse_limit = get_target_sparse_limit();
875         }
876         if (target_sparse_limit > 0) {
877             limit = target_sparse_limit;
878         } else {
879             return 0;
880         }
881     }
882 
883     if (size > limit) {
884         return std::min(limit, RESPARSE_LIMIT);
885     }
886 
887     return 0;
888 }
889 
load_buf_fd(int fd,struct fastboot_buffer * buf)890 static bool load_buf_fd(int fd, struct fastboot_buffer* buf) {
891     int64_t sz = get_file_size(fd);
892     if (sz == -1) {
893         return false;
894     }
895 
896     if (sparse_file* s = sparse_file_import(fd, false, false)) {
897         buf->image_size = sparse_file_len(s, false, false);
898         sparse_file_destroy(s);
899     } else {
900         buf->image_size = sz;
901     }
902 
903     lseek(fd, 0, SEEK_SET);
904     int64_t limit = get_sparse_limit(sz);
905     if (limit) {
906         sparse_file** s = load_sparse_files(fd, limit);
907         if (s == nullptr) {
908             return false;
909         }
910         buf->type = FB_BUFFER_SPARSE;
911         buf->data = s;
912     } else {
913         buf->type = FB_BUFFER_FD;
914         buf->data = nullptr;
915         buf->fd = fd;
916         buf->sz = sz;
917     }
918 
919     return true;
920 }
921 
load_buf(const char * fname,struct fastboot_buffer * buf)922 static bool load_buf(const char* fname, struct fastboot_buffer* buf) {
923     unique_fd fd(TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_BINARY)));
924 
925     if (fd == -1) {
926         return false;
927     }
928 
929     struct stat s;
930     if (fstat(fd, &s)) {
931         return false;
932     }
933     if (!S_ISREG(s.st_mode)) {
934         errno = S_ISDIR(s.st_mode) ? EISDIR : EINVAL;
935         return false;
936     }
937 
938     return load_buf_fd(fd.release(), buf);
939 }
940 
rewrite_vbmeta_buffer(struct fastboot_buffer * buf,bool vbmeta_in_boot)941 static void rewrite_vbmeta_buffer(struct fastboot_buffer* buf, bool vbmeta_in_boot) {
942     // Buffer needs to be at least the size of the VBMeta struct which
943     // is 256 bytes.
944     if (buf->sz < 256) {
945         return;
946     }
947 
948     std::string data;
949     if (!android::base::ReadFdToString(buf->fd, &data)) {
950         die("Failed reading from vbmeta");
951     }
952 
953     uint64_t vbmeta_offset = 0;
954     if (vbmeta_in_boot) {
955         // Tries to locate top-level vbmeta from boot.img footer.
956         uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
957         if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
958             die("Failed to find AVB_FOOTER at offset: %" PRId64, footer_offset);
959         }
960         const AvbFooter* footer = reinterpret_cast<const AvbFooter*>(data.c_str() + footer_offset);
961         vbmeta_offset = be64toh(footer->vbmeta_offset);
962     }
963     // Ensures there is AVB_MAGIC at vbmeta_offset.
964     if (0 != data.compare(vbmeta_offset, AVB_MAGIC_LEN, AVB_MAGIC)) {
965         die("Failed to find AVB_MAGIC at offset: %" PRId64, vbmeta_offset);
966     }
967 
968     fprintf(stderr, "Rewriting vbmeta struct at offset: %" PRId64 "\n", vbmeta_offset);
969 
970     // There's a 32-bit big endian |flags| field at offset 120 where
971     // bit 0 corresponds to disable-verity and bit 1 corresponds to
972     // disable-verification.
973     //
974     // See external/avb/libavb/avb_vbmeta_image.h for the layout of
975     // the VBMeta struct.
976     uint64_t flags_offset = 123 + vbmeta_offset;
977     if (g_disable_verity) {
978         data[flags_offset] |= 0x01;
979     }
980     if (g_disable_verification) {
981         data[flags_offset] |= 0x02;
982     }
983 
984     int fd = make_temporary_fd("vbmeta rewriting");
985     if (!android::base::WriteStringToFd(data, fd)) {
986         die("Failed writing to modified vbmeta");
987     }
988     close(buf->fd);
989     buf->fd = fd;
990     lseek(fd, 0, SEEK_SET);
991 }
992 
has_vbmeta_partition()993 static bool has_vbmeta_partition() {
994     std::string partition_type;
995     return fb->GetVar("partition-type:vbmeta", &partition_type) == fastboot::SUCCESS ||
996            fb->GetVar("partition-type:vbmeta_a", &partition_type) == fastboot::SUCCESS ||
997            fb->GetVar("partition-type:vbmeta_b", &partition_type) == fastboot::SUCCESS;
998 }
999 
fb_fix_numeric_var(std::string var)1000 static std::string fb_fix_numeric_var(std::string var) {
1001     // Some bootloaders (angler, for example), send spurious leading whitespace.
1002     var = android::base::Trim(var);
1003     // Some bootloaders (hammerhead, for example) use implicit hex.
1004     // This code used to use strtol with base 16.
1005     if (!android::base::StartsWith(var, "0x")) var = "0x" + var;
1006     return var;
1007 }
1008 
copy_boot_avb_footer(const std::string & partition,struct fastboot_buffer * buf)1009 static void copy_boot_avb_footer(const std::string& partition, struct fastboot_buffer* buf) {
1010     if (buf->sz < AVB_FOOTER_SIZE) {
1011         return;
1012     }
1013 
1014     std::string partition_size_str;
1015     if (fb->GetVar("partition-size:" + partition, &partition_size_str) != fastboot::SUCCESS) {
1016         die("cannot get boot partition size");
1017     }
1018 
1019     partition_size_str = fb_fix_numeric_var(partition_size_str);
1020     int64_t partition_size;
1021     if (!android::base::ParseInt(partition_size_str, &partition_size)) {
1022         die("Couldn't parse partition size '%s'.", partition_size_str.c_str());
1023     }
1024     if (partition_size == buf->sz) {
1025         return;
1026     }
1027     if (partition_size < buf->sz) {
1028         die("boot partition is smaller than boot image");
1029     }
1030 
1031     std::string data;
1032     if (!android::base::ReadFdToString(buf->fd, &data)) {
1033         die("Failed reading from boot");
1034     }
1035 
1036     uint64_t footer_offset = buf->sz - AVB_FOOTER_SIZE;
1037     if (0 != data.compare(footer_offset, AVB_FOOTER_MAGIC_LEN, AVB_FOOTER_MAGIC)) {
1038         return;
1039     }
1040 
1041     int fd = make_temporary_fd("boot rewriting");
1042     if (!android::base::WriteStringToFd(data, fd)) {
1043         die("Failed writing to modified boot");
1044     }
1045     lseek(fd, partition_size - AVB_FOOTER_SIZE, SEEK_SET);
1046     if (!android::base::WriteStringToFd(data.substr(footer_offset), fd)) {
1047         die("Failed copying AVB footer in boot");
1048     }
1049     close(buf->fd);
1050     buf->fd = fd;
1051     buf->sz = partition_size;
1052     lseek(fd, 0, SEEK_SET);
1053 }
1054 
flash_buf(const std::string & partition,struct fastboot_buffer * buf)1055 static void flash_buf(const std::string& partition, struct fastboot_buffer *buf)
1056 {
1057     sparse_file** s;
1058 
1059     if (partition == "boot" || partition == "boot_a" || partition == "boot_b") {
1060         copy_boot_avb_footer(partition, buf);
1061     }
1062 
1063     // Rewrite vbmeta if that's what we're flashing and modification has been requested.
1064     if (g_disable_verity || g_disable_verification) {
1065         if (partition == "vbmeta" || partition == "vbmeta_a" || partition == "vbmeta_b") {
1066             rewrite_vbmeta_buffer(buf, false /* vbmeta_in_boot */);
1067         } else if (!has_vbmeta_partition() &&
1068                    (partition == "boot" || partition == "boot_a" || partition == "boot_b")) {
1069             rewrite_vbmeta_buffer(buf, true /* vbmeta_in_boot */ );
1070         }
1071     }
1072 
1073     switch (buf->type) {
1074         case FB_BUFFER_SPARSE: {
1075             std::vector<std::pair<sparse_file*, int64_t>> sparse_files;
1076             s = reinterpret_cast<sparse_file**>(buf->data);
1077             while (*s) {
1078                 int64_t sz = sparse_file_len(*s, true, false);
1079                 sparse_files.emplace_back(*s, sz);
1080                 ++s;
1081             }
1082 
1083             for (size_t i = 0; i < sparse_files.size(); ++i) {
1084                 const auto& pair = sparse_files[i];
1085                 fb->FlashPartition(partition, pair.first, pair.second, i + 1, sparse_files.size());
1086             }
1087             break;
1088         }
1089         case FB_BUFFER_FD:
1090             fb->FlashPartition(partition, buf->fd, buf->sz);
1091             break;
1092         default:
1093             die("unknown buffer type: %d", buf->type);
1094     }
1095 }
1096 
get_current_slot()1097 static std::string get_current_slot() {
1098     std::string current_slot;
1099     if (fb->GetVar("current-slot", &current_slot) != fastboot::SUCCESS) return "";
1100     return current_slot;
1101 }
1102 
get_slot_count()1103 static int get_slot_count() {
1104     std::string var;
1105     int count = 0;
1106     if (fb->GetVar("slot-count", &var) != fastboot::SUCCESS ||
1107         !android::base::ParseInt(var, &count)) {
1108         return 0;
1109     }
1110     return count;
1111 }
1112 
supports_AB()1113 static bool supports_AB() {
1114   return get_slot_count() >= 2;
1115 }
1116 
1117 // Given a current slot, this returns what the 'other' slot is.
get_other_slot(const std::string & current_slot,int count)1118 static std::string get_other_slot(const std::string& current_slot, int count) {
1119     if (count == 0) return "";
1120 
1121     char next = (current_slot[0] - 'a' + 1)%count + 'a';
1122     return std::string(1, next);
1123 }
1124 
get_other_slot(const std::string & current_slot)1125 static std::string get_other_slot(const std::string& current_slot) {
1126     return get_other_slot(current_slot, get_slot_count());
1127 }
1128 
get_other_slot(int count)1129 static std::string get_other_slot(int count) {
1130     return get_other_slot(get_current_slot(), count);
1131 }
1132 
get_other_slot()1133 static std::string get_other_slot() {
1134     return get_other_slot(get_current_slot(), get_slot_count());
1135 }
1136 
verify_slot(const std::string & slot_name,bool allow_all)1137 static std::string verify_slot(const std::string& slot_name, bool allow_all) {
1138     std::string slot = slot_name;
1139     if (slot == "all") {
1140         if (allow_all) {
1141             return "all";
1142         } else {
1143             int count = get_slot_count();
1144             if (count > 0) {
1145                 return "a";
1146             } else {
1147                 die("No known slots");
1148             }
1149         }
1150     }
1151 
1152     int count = get_slot_count();
1153     if (count == 0) die("Device does not support slots");
1154 
1155     if (slot == "other") {
1156         std::string other = get_other_slot( count);
1157         if (other == "") {
1158            die("No known slots");
1159         }
1160         return other;
1161     }
1162 
1163     if (slot.size() == 1 && (slot[0]-'a' >= 0 && slot[0]-'a' < count)) return slot;
1164 
1165     fprintf(stderr, "Slot %s does not exist. supported slots are:\n", slot.c_str());
1166     for (int i=0; i<count; i++) {
1167         fprintf(stderr, "%c\n", (char)(i + 'a'));
1168     }
1169 
1170     exit(1);
1171 }
1172 
verify_slot(const std::string & slot)1173 static std::string verify_slot(const std::string& slot) {
1174    return verify_slot(slot, true);
1175 }
1176 
do_for_partition(const std::string & part,const std::string & slot,const std::function<void (const std::string &)> & func,bool force_slot)1177 static void do_for_partition(const std::string& part, const std::string& slot,
1178                              const std::function<void(const std::string&)>& func, bool force_slot) {
1179     std::string has_slot;
1180     std::string current_slot;
1181 
1182     if (fb->GetVar("has-slot:" + part, &has_slot) != fastboot::SUCCESS) {
1183         /* If has-slot is not supported, the answer is no. */
1184         has_slot = "no";
1185     }
1186     if (has_slot == "yes") {
1187         if (slot == "") {
1188             current_slot = get_current_slot();
1189             if (current_slot == "") {
1190                 die("Failed to identify current slot");
1191             }
1192             func(part + "_" + current_slot);
1193         } else {
1194             func(part + '_' + slot);
1195         }
1196     } else {
1197         if (force_slot && slot != "") {
1198              fprintf(stderr, "Warning: %s does not support slots, and slot %s was requested.\n",
1199                      part.c_str(), slot.c_str());
1200         }
1201         func(part);
1202     }
1203 }
1204 
1205 /* This function will find the real partition name given a base name, and a slot. If slot is NULL or
1206  * empty, it will use the current slot. If slot is "all", it will return a list of all possible
1207  * partition names. If force_slot is true, it will fail if a slot is specified, and the given
1208  * partition does not support slots.
1209  */
do_for_partitions(const std::string & part,const std::string & slot,const std::function<void (const std::string &)> & func,bool force_slot)1210 static void do_for_partitions(const std::string& part, const std::string& slot,
1211                               const std::function<void(const std::string&)>& func, bool force_slot) {
1212     std::string has_slot;
1213 
1214     if (slot == "all") {
1215         if (fb->GetVar("has-slot:" + part, &has_slot) != fastboot::SUCCESS) {
1216             die("Could not check if partition %s has slot %s", part.c_str(), slot.c_str());
1217         }
1218         if (has_slot == "yes") {
1219             for (int i=0; i < get_slot_count(); i++) {
1220                 do_for_partition(part, std::string(1, (char)(i + 'a')), func, force_slot);
1221             }
1222         } else {
1223             do_for_partition(part, "", func, force_slot);
1224         }
1225     } else {
1226         do_for_partition(part, slot, func, force_slot);
1227     }
1228 }
1229 
is_logical(const std::string & partition)1230 static bool is_logical(const std::string& partition) {
1231     std::string value;
1232     return fb->GetVar("is-logical:" + partition, &value) == fastboot::SUCCESS && value == "yes";
1233 }
1234 
is_retrofit_device()1235 static bool is_retrofit_device() {
1236     std::string value;
1237     if (fb->GetVar("super-partition-name", &value) != fastboot::SUCCESS) {
1238         return false;
1239     }
1240     return android::base::StartsWith(value, "system_");
1241 }
1242 
do_flash(const char * pname,const char * fname)1243 static void do_flash(const char* pname, const char* fname) {
1244     struct fastboot_buffer buf;
1245 
1246     if (!load_buf(fname, &buf)) {
1247         die("cannot load '%s': %s", fname, strerror(errno));
1248     }
1249     if (is_logical(pname)) {
1250         fb->ResizePartition(pname, std::to_string(buf.image_size));
1251     }
1252     flash_buf(pname, &buf);
1253 }
1254 
1255 // Sets slot_override as the active slot. If slot_override is blank,
1256 // set current slot as active instead. This clears slot-unbootable.
set_active(const std::string & slot_override)1257 static void set_active(const std::string& slot_override) {
1258     if (!supports_AB()) return;
1259 
1260     if (slot_override != "") {
1261         fb->SetActive(slot_override);
1262     } else {
1263         std::string current_slot = get_current_slot();
1264         if (current_slot != "") {
1265             fb->SetActive(current_slot);
1266         }
1267     }
1268 }
1269 
is_userspace_fastboot()1270 static bool is_userspace_fastboot() {
1271     std::string value;
1272     return fb->GetVar("is-userspace", &value) == fastboot::SUCCESS && value == "yes";
1273 }
1274 
reboot_to_userspace_fastboot()1275 static void reboot_to_userspace_fastboot() {
1276     fb->RebootTo("fastboot");
1277 
1278     auto* old_transport = fb->set_transport(nullptr);
1279     delete old_transport;
1280 
1281     // Give the current connection time to close.
1282     std::this_thread::sleep_for(std::chrono::milliseconds(1000));
1283 
1284     fb->set_transport(open_device());
1285 
1286     if (!is_userspace_fastboot()) {
1287         die("Failed to boot into userspace fastboot; one or more components might be unbootable.");
1288     }
1289 
1290     // Reset target_sparse_limit after reboot to userspace fastboot. Max
1291     // download sizes may differ in bootloader and fastbootd.
1292     target_sparse_limit = -1;
1293 }
1294 
CancelSnapshotIfNeeded()1295 static void CancelSnapshotIfNeeded() {
1296     std::string merge_status = "none";
1297     if (fb->GetVar(FB_VAR_SNAPSHOT_UPDATE_STATUS, &merge_status) == fastboot::SUCCESS &&
1298         !merge_status.empty() && merge_status != "none") {
1299         fb->SnapshotUpdateCommand("cancel");
1300     }
1301 }
1302 
1303 class ImageSource {
1304   public:
1305     virtual bool ReadFile(const std::string& name, std::vector<char>* out) const = 0;
1306     virtual int OpenFile(const std::string& name) const = 0;
1307 };
1308 
1309 class FlashAllTool {
1310   public:
1311     FlashAllTool(const ImageSource& source, const std::string& slot_override, bool skip_secondary, bool wipe);
1312 
1313     void Flash();
1314 
1315   private:
1316     void CheckRequirements();
1317     void DetermineSecondarySlot();
1318     void CollectImages();
1319     void FlashImages(const std::vector<std::pair<const Image*, std::string>>& images);
1320     void FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf);
1321     void UpdateSuperPartition();
1322 
1323     const ImageSource& source_;
1324     std::string slot_override_;
1325     bool skip_secondary_;
1326     bool wipe_;
1327     std::string secondary_slot_;
1328     std::vector<std::pair<const Image*, std::string>> boot_images_;
1329     std::vector<std::pair<const Image*, std::string>> os_images_;
1330 };
1331 
FlashAllTool(const ImageSource & source,const std::string & slot_override,bool skip_secondary,bool wipe)1332 FlashAllTool::FlashAllTool(const ImageSource& source, const std::string& slot_override, bool skip_secondary, bool wipe)
1333    : source_(source),
1334      slot_override_(slot_override),
1335      skip_secondary_(skip_secondary),
1336      wipe_(wipe)
1337 {
1338 }
1339 
Flash()1340 void FlashAllTool::Flash() {
1341     DumpInfo();
1342     CheckRequirements();
1343 
1344     // Change the slot first, so we boot into the correct recovery image when
1345     // using fastbootd.
1346     if (slot_override_ == "all") {
1347         set_active("a");
1348     } else {
1349         set_active(slot_override_);
1350     }
1351 
1352     DetermineSecondarySlot();
1353     CollectImages();
1354 
1355     CancelSnapshotIfNeeded();
1356 
1357     // First flash boot partitions. We allow this to happen either in userspace
1358     // or in bootloader fastboot.
1359     FlashImages(boot_images_);
1360 
1361     // Sync the super partition. This will reboot to userspace fastboot if needed.
1362     UpdateSuperPartition();
1363 
1364     // Resize any logical partition to 0, so each partition is reset to 0
1365     // extents, and will achieve more optimal allocation.
1366     for (const auto& [image, slot] : os_images_) {
1367         auto resize_partition = [](const std::string& partition) -> void {
1368             if (is_logical(partition)) {
1369                 fb->ResizePartition(partition, "0");
1370             }
1371         };
1372         do_for_partitions(image->part_name, slot, resize_partition, false);
1373     }
1374 
1375     // Flash OS images, resizing logical partitions as needed.
1376     FlashImages(os_images_);
1377 }
1378 
CheckRequirements()1379 void FlashAllTool::CheckRequirements() {
1380     std::vector<char> contents;
1381     if (!source_.ReadFile("android-info.txt", &contents)) {
1382         die("could not read android-info.txt");
1383     }
1384     ::CheckRequirements({contents.data(), contents.size()});
1385 }
1386 
DetermineSecondarySlot()1387 void FlashAllTool::DetermineSecondarySlot() {
1388     if (skip_secondary_) {
1389         return;
1390     }
1391     if (slot_override_ != "" && slot_override_ != "all") {
1392         secondary_slot_ = get_other_slot(slot_override_);
1393     } else {
1394         secondary_slot_ = get_other_slot();
1395     }
1396     if (secondary_slot_ == "") {
1397         if (supports_AB()) {
1398             fprintf(stderr, "Warning: Could not determine slot for secondary images. Ignoring.\n");
1399         }
1400         skip_secondary_ = true;
1401     }
1402 }
1403 
CollectImages()1404 void FlashAllTool::CollectImages() {
1405     for (size_t i = 0; i < arraysize(images); ++i) {
1406         std::string slot = slot_override_;
1407         if (images[i].IsSecondary()) {
1408             if (skip_secondary_) {
1409                 continue;
1410             }
1411             slot = secondary_slot_;
1412         }
1413         if (images[i].type == ImageType::BootCritical) {
1414             boot_images_.emplace_back(&images[i], slot);
1415         } else if (images[i].type == ImageType::Normal) {
1416             os_images_.emplace_back(&images[i], slot);
1417         }
1418     }
1419 }
1420 
FlashImages(const std::vector<std::pair<const Image *,std::string>> & images)1421 void FlashAllTool::FlashImages(const std::vector<std::pair<const Image*, std::string>>& images) {
1422     for (const auto& [image, slot] : images) {
1423         fastboot_buffer buf;
1424         int fd = source_.OpenFile(image->img_name);
1425         if (fd < 0 || !load_buf_fd(fd, &buf)) {
1426             if (image->optional_if_no_image) {
1427                 continue;
1428             }
1429             die("could not load '%s': %s", image->img_name, strerror(errno));
1430         }
1431         FlashImage(*image, slot, &buf);
1432     }
1433 }
1434 
FlashImage(const Image & image,const std::string & slot,fastboot_buffer * buf)1435 void FlashAllTool::FlashImage(const Image& image, const std::string& slot, fastboot_buffer* buf) {
1436     auto flash = [&, this](const std::string& partition_name) {
1437         std::vector<char> signature_data;
1438         if (source_.ReadFile(image.sig_name, &signature_data)) {
1439             fb->Download("signature", signature_data);
1440             fb->RawCommand("signature", "installing signature");
1441         }
1442 
1443         if (is_logical(partition_name)) {
1444             fb->ResizePartition(partition_name, std::to_string(buf->image_size));
1445         }
1446         flash_buf(partition_name.c_str(), buf);
1447     };
1448     do_for_partitions(image.part_name, slot, flash, false);
1449 }
1450 
UpdateSuperPartition()1451 void FlashAllTool::UpdateSuperPartition() {
1452     int fd = source_.OpenFile("super_empty.img");
1453     if (fd < 0) {
1454         return;
1455     }
1456     if (!is_userspace_fastboot()) {
1457         reboot_to_userspace_fastboot();
1458     }
1459 
1460     std::string super_name;
1461     if (fb->GetVar("super-partition-name", &super_name) != fastboot::RetCode::SUCCESS) {
1462         super_name = "super";
1463     }
1464     fb->Download(super_name, fd, get_file_size(fd));
1465 
1466     std::string command = "update-super:" + super_name;
1467     if (wipe_) {
1468         command += ":wipe";
1469     }
1470     fb->RawCommand(command, "Updating super partition");
1471 
1472     // Retrofit devices have two super partitions, named super_a and super_b.
1473     // On these devices, secondary slots must be flashed as physical
1474     // partitions (otherwise they would not mount on first boot). To enforce
1475     // this, we delete any logical partitions for the "other" slot.
1476     if (is_retrofit_device()) {
1477         for (const auto& [image, slot] : os_images_) {
1478             std::string partition_name = image->part_name + "_"s + slot;
1479             if (image->IsSecondary() && is_logical(partition_name)) {
1480                 fb->DeletePartition(partition_name);
1481             }
1482         }
1483     }
1484 }
1485 
1486 class ZipImageSource final : public ImageSource {
1487   public:
ZipImageSource(ZipArchiveHandle zip)1488     explicit ZipImageSource(ZipArchiveHandle zip) : zip_(zip) {}
1489     bool ReadFile(const std::string& name, std::vector<char>* out) const override;
1490     int OpenFile(const std::string& name) const override;
1491 
1492   private:
1493     ZipArchiveHandle zip_;
1494 };
1495 
ReadFile(const std::string & name,std::vector<char> * out) const1496 bool ZipImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
1497     return UnzipToMemory(zip_, name, out);
1498 }
1499 
OpenFile(const std::string & name) const1500 int ZipImageSource::OpenFile(const std::string& name) const {
1501     return unzip_to_file(zip_, name.c_str());
1502 }
1503 
do_update(const char * filename,const std::string & slot_override,bool skip_secondary)1504 static void do_update(const char* filename, const std::string& slot_override, bool skip_secondary) {
1505     ZipArchiveHandle zip;
1506     int error = OpenArchive(filename, &zip);
1507     if (error != 0) {
1508         die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
1509     }
1510 
1511     FlashAllTool tool(ZipImageSource(zip), slot_override, skip_secondary, false);
1512     tool.Flash();
1513 
1514     CloseArchive(zip);
1515 }
1516 
1517 class LocalImageSource final : public ImageSource {
1518   public:
1519     bool ReadFile(const std::string& name, std::vector<char>* out) const override;
1520     int OpenFile(const std::string& name) const override;
1521 };
1522 
ReadFile(const std::string & name,std::vector<char> * out) const1523 bool LocalImageSource::ReadFile(const std::string& name, std::vector<char>* out) const {
1524     auto path = find_item_given_name(name);
1525     if (path.empty()) {
1526         return false;
1527     }
1528     return ReadFileToVector(path, out);
1529 }
1530 
OpenFile(const std::string & name) const1531 int LocalImageSource::OpenFile(const std::string& name) const {
1532     auto path = find_item_given_name(name);
1533     return open(path.c_str(), O_RDONLY | O_BINARY);
1534 }
1535 
do_flashall(const std::string & slot_override,bool skip_secondary,bool wipe)1536 static void do_flashall(const std::string& slot_override, bool skip_secondary, bool wipe) {
1537     FlashAllTool tool(LocalImageSource(), slot_override, skip_secondary, wipe);
1538     tool.Flash();
1539 }
1540 
next_arg(std::vector<std::string> * args)1541 static std::string next_arg(std::vector<std::string>* args) {
1542     if (args->empty()) syntax_error("expected argument");
1543     std::string result = args->front();
1544     args->erase(args->begin());
1545     return result;
1546 }
1547 
do_oem_command(const std::string & cmd,std::vector<std::string> * args)1548 static void do_oem_command(const std::string& cmd, std::vector<std::string>* args) {
1549     if (args->empty()) syntax_error("empty oem command");
1550 
1551     std::string command(cmd);
1552     while (!args->empty()) {
1553         command += " " + next_arg(args);
1554     }
1555     fb->RawCommand(command, "");
1556 }
1557 
fb_get_flash_block_size(std::string name)1558 static unsigned fb_get_flash_block_size(std::string name) {
1559     std::string sizeString;
1560     if (fb->GetVar(name, &sizeString) != fastboot::SUCCESS || sizeString.empty()) {
1561         // This device does not report flash block sizes, so return 0.
1562         return 0;
1563     }
1564     sizeString = fb_fix_numeric_var(sizeString);
1565 
1566     unsigned size;
1567     if (!android::base::ParseUint(sizeString, &size)) {
1568         fprintf(stderr, "Couldn't parse %s '%s'.\n", name.c_str(), sizeString.c_str());
1569         return 0;
1570     }
1571     if ((size & (size - 1)) != 0) {
1572         fprintf(stderr, "Invalid %s %u: must be a power of 2.\n", name.c_str(), size);
1573         return 0;
1574     }
1575     return size;
1576 }
1577 
fb_perform_format(const std::string & partition,int skip_if_not_supported,const std::string & type_override,const std::string & size_override,const std::string & initial_dir)1578 static void fb_perform_format(
1579                               const std::string& partition, int skip_if_not_supported,
1580                               const std::string& type_override, const std::string& size_override,
1581                               const std::string& initial_dir) {
1582     std::string partition_type, partition_size;
1583 
1584     struct fastboot_buffer buf;
1585     const char* errMsg = nullptr;
1586     const struct fs_generator* gen = nullptr;
1587     TemporaryFile output;
1588     unique_fd fd;
1589 
1590     unsigned int limit = INT_MAX;
1591     if (target_sparse_limit > 0 && target_sparse_limit < limit) {
1592         limit = target_sparse_limit;
1593     }
1594     if (sparse_limit > 0 && sparse_limit < limit) {
1595         limit = sparse_limit;
1596     }
1597 
1598     if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
1599         errMsg = "Can't determine partition type.\n";
1600         goto failed;
1601     }
1602     if (!type_override.empty()) {
1603         if (partition_type != type_override) {
1604             fprintf(stderr, "Warning: %s type is %s, but %s was requested for formatting.\n",
1605                     partition.c_str(), partition_type.c_str(), type_override.c_str());
1606         }
1607         partition_type = type_override;
1608     }
1609 
1610     if (fb->GetVar("partition-size:" + partition, &partition_size) != fastboot::SUCCESS) {
1611         errMsg = "Unable to get partition size\n";
1612         goto failed;
1613     }
1614     if (!size_override.empty()) {
1615         if (partition_size != size_override) {
1616             fprintf(stderr, "Warning: %s size is %s, but %s was requested for formatting.\n",
1617                     partition.c_str(), partition_size.c_str(), size_override.c_str());
1618         }
1619         partition_size = size_override;
1620     }
1621     partition_size = fb_fix_numeric_var(partition_size);
1622 
1623     gen = fs_get_generator(partition_type);
1624     if (!gen) {
1625         if (skip_if_not_supported) {
1626             fprintf(stderr, "Erase successful, but not automatically formatting.\n");
1627             fprintf(stderr, "File system type %s not supported.\n", partition_type.c_str());
1628             return;
1629         }
1630         die("Formatting is not supported for file system with type '%s'.",
1631             partition_type.c_str());
1632     }
1633 
1634     int64_t size;
1635     if (!android::base::ParseInt(partition_size, &size)) {
1636         die("Couldn't parse partition size '%s'.", partition_size.c_str());
1637     }
1638 
1639     unsigned eraseBlkSize, logicalBlkSize;
1640     eraseBlkSize = fb_get_flash_block_size("erase-block-size");
1641     logicalBlkSize = fb_get_flash_block_size("logical-block-size");
1642 
1643     if (fs_generator_generate(gen, output.path, size, initial_dir,
1644             eraseBlkSize, logicalBlkSize)) {
1645         die("Cannot generate image for %s", partition.c_str());
1646     }
1647 
1648     fd.reset(open(output.path, O_RDONLY));
1649     if (fd == -1) {
1650         die("Cannot open generated image: %s", strerror(errno));
1651     }
1652     if (!load_buf_fd(fd.release(), &buf)) {
1653         die("Cannot read image: %s", strerror(errno));
1654     }
1655     flash_buf(partition, &buf);
1656     return;
1657 
1658 failed:
1659     if (skip_if_not_supported) {
1660         fprintf(stderr, "Erase successful, but not automatically formatting.\n");
1661         if (errMsg) fprintf(stderr, "%s", errMsg);
1662     }
1663     fprintf(stderr, "FAILED (%s)\n", fb->Error().c_str());
1664     if (!skip_if_not_supported) {
1665         die("Command failed");
1666     }
1667 }
1668 
should_flash_in_userspace(const std::string & partition_name)1669 static bool should_flash_in_userspace(const std::string& partition_name) {
1670     if (!get_android_product_out()) {
1671         return false;
1672     }
1673     auto path = find_item_given_name("super_empty.img");
1674     if (path.empty() || access(path.c_str(), R_OK)) {
1675         return false;
1676     }
1677     auto metadata = android::fs_mgr::ReadFromImageFile(path);
1678     if (!metadata) {
1679         return false;
1680     }
1681     for (const auto& partition : metadata->partitions) {
1682         auto candidate = android::fs_mgr::GetPartitionName(partition);
1683         if (partition.attributes & LP_PARTITION_ATTR_SLOT_SUFFIXED) {
1684             // On retrofit devices, we don't know if, or whether, the A or B
1685             // slot has been flashed for dynamic partitions. Instead we add
1686             // both names to the list as a conservative guess.
1687             if (candidate + "_a" == partition_name || candidate + "_b" == partition_name) {
1688                 return true;
1689             }
1690         } else if (candidate == partition_name) {
1691             return true;
1692         }
1693     }
1694     return false;
1695 }
1696 
wipe_super(const android::fs_mgr::LpMetadata & metadata,const std::string & slot,std::string * message)1697 static bool wipe_super(const android::fs_mgr::LpMetadata& metadata, const std::string& slot,
1698                        std::string* message) {
1699     auto super_device = GetMetadataSuperBlockDevice(metadata);
1700     auto block_size = metadata.geometry.logical_block_size;
1701     auto super_bdev_name = android::fs_mgr::GetBlockDevicePartitionName(*super_device);
1702 
1703     if (super_bdev_name != "super") {
1704         // retrofit devices do not allow flashing to the retrofit partitions,
1705         // so enable it if we can.
1706         fb->RawCommand("oem allow-flash-super");
1707     }
1708 
1709     // Note: do not use die() in here, since we want TemporaryDir's destructor
1710     // to be called.
1711     TemporaryDir temp_dir;
1712 
1713     bool ok;
1714     if (metadata.block_devices.size() > 1) {
1715         ok = WriteSplitImageFiles(temp_dir.path, metadata, block_size, {}, true);
1716     } else {
1717         auto image_path = temp_dir.path + "/"s + super_bdev_name + ".img";
1718         ok = WriteToImageFile(image_path, metadata, block_size, {}, true);
1719     }
1720     if (!ok) {
1721         *message = "Could not generate a flashable super image file";
1722         return false;
1723     }
1724 
1725     for (const auto& block_device : metadata.block_devices) {
1726         auto partition = android::fs_mgr::GetBlockDevicePartitionName(block_device);
1727         bool force_slot = !!(block_device.flags & LP_BLOCK_DEVICE_SLOT_SUFFIXED);
1728 
1729         std::string image_name;
1730         if (metadata.block_devices.size() > 1) {
1731             image_name = "super_" + partition + ".img";
1732         } else {
1733             image_name = partition + ".img";
1734         }
1735 
1736         auto image_path = temp_dir.path + "/"s + image_name;
1737         auto flash = [&](const std::string& partition_name) {
1738             do_flash(partition_name.c_str(), image_path.c_str());
1739         };
1740         do_for_partitions(partition, slot, flash, force_slot);
1741 
1742         unlink(image_path.c_str());
1743     }
1744     return true;
1745 }
1746 
do_wipe_super(const std::string & image,const std::string & slot_override)1747 static void do_wipe_super(const std::string& image, const std::string& slot_override) {
1748     if (access(image.c_str(), R_OK) != 0) {
1749         die("Could not read image: %s", image.c_str());
1750     }
1751     auto metadata = android::fs_mgr::ReadFromImageFile(image);
1752     if (!metadata) {
1753         die("Could not parse image: %s", image.c_str());
1754     }
1755 
1756     auto slot = slot_override;
1757     if (slot.empty()) {
1758         slot = get_current_slot();
1759     }
1760 
1761     std::string message;
1762     if (!wipe_super(*metadata.get(), slot, &message)) {
1763         die(message);
1764     }
1765 }
1766 
Main(int argc,char * argv[])1767 int FastBootTool::Main(int argc, char* argv[]) {
1768     bool wants_wipe = false;
1769     bool wants_reboot = false;
1770     bool wants_reboot_bootloader = false;
1771     bool wants_reboot_recovery = false;
1772     bool wants_reboot_fastboot = false;
1773     bool skip_reboot = false;
1774     bool wants_set_active = false;
1775     bool skip_secondary = false;
1776     bool set_fbe_marker = false;
1777     bool force_flash = false;
1778     int longindex;
1779     std::string slot_override;
1780     std::string next_active;
1781 
1782     g_boot_img_hdr.kernel_addr = 0x00008000;
1783     g_boot_img_hdr.ramdisk_addr = 0x01000000;
1784     g_boot_img_hdr.second_addr = 0x00f00000;
1785     g_boot_img_hdr.tags_addr = 0x00000100;
1786     g_boot_img_hdr.page_size = 2048;
1787     g_boot_img_hdr.dtb_addr = 0x01100000;
1788 
1789     const struct option longopts[] = {
1790         {"base", required_argument, 0, 0},
1791         {"cmdline", required_argument, 0, 0},
1792         {"disable-verification", no_argument, 0, 0},
1793         {"disable-verity", no_argument, 0, 0},
1794         {"force", no_argument, 0, 0},
1795         {"header-version", required_argument, 0, 0},
1796         {"help", no_argument, 0, 'h'},
1797         {"kernel-offset", required_argument, 0, 0},
1798         {"os-patch-level", required_argument, 0, 0},
1799         {"os-version", required_argument, 0, 0},
1800         {"page-size", required_argument, 0, 0},
1801         {"ramdisk-offset", required_argument, 0, 0},
1802         {"set-active", optional_argument, 0, 'a'},
1803         {"skip-reboot", no_argument, 0, 0},
1804         {"skip-secondary", no_argument, 0, 0},
1805         {"slot", required_argument, 0, 0},
1806         {"tags-offset", required_argument, 0, 0},
1807         {"dtb", required_argument, 0, 0},
1808         {"dtb-offset", required_argument, 0, 0},
1809         {"unbuffered", no_argument, 0, 0},
1810         {"verbose", no_argument, 0, 'v'},
1811         {"version", no_argument, 0, 0},
1812 #if !defined(_WIN32)
1813         {"wipe-and-use-fbe", no_argument, 0, 0},
1814 #endif
1815         {0, 0, 0, 0}
1816     };
1817 
1818     serial = getenv("ANDROID_SERIAL");
1819 
1820     int c;
1821     while ((c = getopt_long(argc, argv, "a::hls:S:vw", longopts, &longindex)) != -1) {
1822         if (c == 0) {
1823             std::string name{longopts[longindex].name};
1824             if (name == "base") {
1825                 g_base_addr = strtoul(optarg, 0, 16);
1826             } else if (name == "cmdline") {
1827                 g_cmdline = optarg;
1828             } else if (name == "disable-verification") {
1829                 g_disable_verification = true;
1830             } else if (name == "disable-verity") {
1831                 g_disable_verity = true;
1832             } else if (name == "force") {
1833                 force_flash = true;
1834             } else if (name == "header-version") {
1835                 g_boot_img_hdr.header_version = strtoul(optarg, nullptr, 0);
1836             } else if (name == "dtb") {
1837                 g_dtb_path = optarg;
1838             } else if (name == "kernel-offset") {
1839                 g_boot_img_hdr.kernel_addr = strtoul(optarg, 0, 16);
1840             } else if (name == "os-patch-level") {
1841                 ParseOsPatchLevel(&g_boot_img_hdr, optarg);
1842             } else if (name == "os-version") {
1843                 ParseOsVersion(&g_boot_img_hdr, optarg);
1844             } else if (name == "page-size") {
1845                 g_boot_img_hdr.page_size = strtoul(optarg, nullptr, 0);
1846                 if (g_boot_img_hdr.page_size == 0) die("invalid page size");
1847             } else if (name == "ramdisk-offset") {
1848                 g_boot_img_hdr.ramdisk_addr = strtoul(optarg, 0, 16);
1849             } else if (name == "skip-reboot") {
1850                 skip_reboot = true;
1851             } else if (name == "skip-secondary") {
1852                 skip_secondary = true;
1853             } else if (name == "slot") {
1854                 slot_override = optarg;
1855             } else if (name == "dtb-offset") {
1856                 g_boot_img_hdr.dtb_addr = strtoul(optarg, 0, 16);
1857             } else if (name == "tags-offset") {
1858                 g_boot_img_hdr.tags_addr = strtoul(optarg, 0, 16);
1859             } else if (name == "unbuffered") {
1860                 setvbuf(stdout, nullptr, _IONBF, 0);
1861                 setvbuf(stderr, nullptr, _IONBF, 0);
1862             } else if (name == "version") {
1863                 fprintf(stdout, "fastboot version %s-%s\n", PLATFORM_TOOLS_VERSION, android::build::GetBuildNumber().c_str());
1864                 fprintf(stdout, "Installed as %s\n", android::base::GetExecutablePath().c_str());
1865                 return 0;
1866 #if !defined(_WIN32)
1867             } else if (name == "wipe-and-use-fbe") {
1868                 wants_wipe = true;
1869                 set_fbe_marker = true;
1870 #endif
1871             } else {
1872                 die("unknown option %s", longopts[longindex].name);
1873             }
1874         } else {
1875             switch (c) {
1876                 case 'a':
1877                     wants_set_active = true;
1878                     if (optarg) next_active = optarg;
1879                     break;
1880                 case 'h':
1881                     return show_help();
1882                 case 'l':
1883                     g_long_listing = true;
1884                     break;
1885                 case 's':
1886                     serial = optarg;
1887                     break;
1888                 case 'S':
1889                     if (!android::base::ParseByteCount(optarg, &sparse_limit)) {
1890                         die("invalid sparse limit %s", optarg);
1891                     }
1892                     break;
1893                 case 'v':
1894                     set_verbose();
1895                     break;
1896                 case 'w':
1897                     wants_wipe = true;
1898                     break;
1899                 case '?':
1900                     return 1;
1901                 default:
1902                     abort();
1903             }
1904         }
1905     }
1906 
1907     argc -= optind;
1908     argv += optind;
1909 
1910     if (argc == 0 && !wants_wipe && !wants_set_active) syntax_error("no command");
1911 
1912     if (argc > 0 && !strcmp(*argv, "devices")) {
1913         list_devices();
1914         return 0;
1915     }
1916 
1917     if (argc > 0 && !strcmp(*argv, "help")) {
1918         return show_help();
1919     }
1920 
1921     Transport* transport = open_device();
1922     if (transport == nullptr) {
1923         return 1;
1924     }
1925     fastboot::DriverCallbacks driver_callbacks = {
1926         .prolog = Status,
1927         .epilog = Epilog,
1928         .info = InfoMessage,
1929     };
1930     fastboot::FastBootDriver fastboot_driver(transport, driver_callbacks, false);
1931     fb = &fastboot_driver;
1932 
1933     const double start = now();
1934 
1935     if (slot_override != "") slot_override = verify_slot(slot_override);
1936     if (next_active != "") next_active = verify_slot(next_active, false);
1937 
1938     if (wants_set_active) {
1939         if (next_active == "") {
1940             if (slot_override == "") {
1941                 std::string current_slot;
1942                 if (fb->GetVar("current-slot", &current_slot) == fastboot::SUCCESS) {
1943                     next_active = verify_slot(current_slot, false);
1944                 } else {
1945                     wants_set_active = false;
1946                 }
1947             } else {
1948                 next_active = verify_slot(slot_override, false);
1949             }
1950         }
1951     }
1952 
1953     std::vector<std::string> args(argv, argv + argc);
1954     while (!args.empty()) {
1955         std::string command = next_arg(&args);
1956 
1957         if (command == FB_CMD_GETVAR) {
1958             std::string variable = next_arg(&args);
1959             DisplayVarOrError(variable, variable);
1960         } else if (command == FB_CMD_ERASE) {
1961             std::string partition = next_arg(&args);
1962             auto erase = [&](const std::string& partition) {
1963                 std::string partition_type;
1964                 if (fb->GetVar("partition-type:" + partition, &partition_type) == fastboot::SUCCESS &&
1965                     fs_get_generator(partition_type) != nullptr) {
1966                     fprintf(stderr, "******** Did you mean to fastboot format this %s partition?\n",
1967                             partition_type.c_str());
1968                 }
1969 
1970                 fb->Erase(partition);
1971             };
1972             do_for_partitions(partition, slot_override, erase, true);
1973         } else if (android::base::StartsWith(command, "format")) {
1974             // Parsing for: "format[:[type][:[size]]]"
1975             // Some valid things:
1976             //  - select only the size, and leave default fs type:
1977             //    format::0x4000000 userdata
1978             //  - default fs type and size:
1979             //    format userdata
1980             //    format:: userdata
1981             std::vector<std::string> pieces = android::base::Split(command, ":");
1982             std::string type_override;
1983             if (pieces.size() > 1) type_override = pieces[1].c_str();
1984             std::string size_override;
1985             if (pieces.size() > 2) size_override = pieces[2].c_str();
1986 
1987             std::string partition = next_arg(&args);
1988 
1989             auto format = [&](const std::string& partition) {
1990                 fb_perform_format(partition, 0, type_override, size_override, "");
1991             };
1992             do_for_partitions(partition, slot_override, format, true);
1993         } else if (command == "signature") {
1994             std::string filename = next_arg(&args);
1995             std::vector<char> data;
1996             if (!ReadFileToVector(filename, &data)) {
1997                 die("could not load '%s': %s", filename.c_str(), strerror(errno));
1998             }
1999             if (data.size() != 256) die("signature must be 256 bytes (got %zu)", data.size());
2000             fb->Download("signature", data);
2001             fb->RawCommand("signature", "installing signature");
2002         } else if (command == FB_CMD_REBOOT) {
2003             wants_reboot = true;
2004 
2005             if (args.size() == 1) {
2006                 std::string what = next_arg(&args);
2007                 if (what == "bootloader") {
2008                     wants_reboot = false;
2009                     wants_reboot_bootloader = true;
2010                 } else if (what == "recovery") {
2011                     wants_reboot = false;
2012                     wants_reboot_recovery = true;
2013                 } else if (what == "fastboot") {
2014                     wants_reboot = false;
2015                     wants_reboot_fastboot = true;
2016                 } else {
2017                     syntax_error("unknown reboot target %s", what.c_str());
2018                 }
2019 
2020             }
2021             if (!args.empty()) syntax_error("junk after reboot command");
2022         } else if (command == FB_CMD_REBOOT_BOOTLOADER) {
2023             wants_reboot_bootloader = true;
2024         } else if (command == FB_CMD_REBOOT_RECOVERY) {
2025             wants_reboot_recovery = true;
2026         } else if (command == FB_CMD_REBOOT_FASTBOOT) {
2027             wants_reboot_fastboot = true;
2028         } else if (command == FB_CMD_CONTINUE) {
2029             fb->Continue();
2030         } else if (command == FB_CMD_BOOT) {
2031             std::string kernel = next_arg(&args);
2032             std::string ramdisk;
2033             if (!args.empty()) ramdisk = next_arg(&args);
2034             std::string second_stage;
2035             if (!args.empty()) second_stage = next_arg(&args);
2036             auto data = LoadBootableImage(kernel, ramdisk, second_stage);
2037             fb->Download("boot.img", data);
2038             fb->Boot();
2039         } else if (command == FB_CMD_FLASH) {
2040             std::string pname = next_arg(&args);
2041 
2042             std::string fname;
2043             if (!args.empty()) {
2044                 fname = next_arg(&args);
2045             } else {
2046                 fname = find_item(pname);
2047             }
2048             if (fname.empty()) die("cannot determine image filename for '%s'", pname.c_str());
2049 
2050             auto flash = [&](const std::string &partition) {
2051                 if (should_flash_in_userspace(partition) && !is_userspace_fastboot() &&
2052                     !force_flash) {
2053                     die("The partition you are trying to flash is dynamic, and "
2054                         "should be flashed via fastbootd. Please run:\n"
2055                         "\n"
2056                         "    fastboot reboot fastboot\n"
2057                         "\n"
2058                         "And try again. If you are intentionally trying to "
2059                         "overwrite a fixed partition, use --force.");
2060                 }
2061                 do_flash(partition.c_str(), fname.c_str());
2062             };
2063             do_for_partitions(pname, slot_override, flash, true);
2064         } else if (command == "flash:raw") {
2065             std::string partition = next_arg(&args);
2066             std::string kernel = next_arg(&args);
2067             std::string ramdisk;
2068             if (!args.empty()) ramdisk = next_arg(&args);
2069             std::string second_stage;
2070             if (!args.empty()) second_stage = next_arg(&args);
2071 
2072             auto data = LoadBootableImage(kernel, ramdisk, second_stage);
2073             auto flashraw = [&data](const std::string& partition) {
2074                 fb->FlashPartition(partition, data);
2075             };
2076             do_for_partitions(partition, slot_override, flashraw, true);
2077         } else if (command == "flashall") {
2078             if (slot_override == "all") {
2079                 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
2080                 do_flashall(slot_override, true, wants_wipe);
2081             } else {
2082                 do_flashall(slot_override, skip_secondary, wants_wipe);
2083             }
2084             wants_reboot = true;
2085         } else if (command == "update") {
2086             bool slot_all = (slot_override == "all");
2087             if (slot_all) {
2088                 fprintf(stderr, "Warning: slot set to 'all'. Secondary slots will not be flashed.\n");
2089             }
2090             std::string filename = "update.zip";
2091             if (!args.empty()) {
2092                 filename = next_arg(&args);
2093             }
2094             do_update(filename.c_str(), slot_override, skip_secondary || slot_all);
2095             wants_reboot = true;
2096         } else if (command == FB_CMD_SET_ACTIVE) {
2097             std::string slot = verify_slot(next_arg(&args), false);
2098             fb->SetActive(slot);
2099         } else if (command == "stage") {
2100             std::string filename = next_arg(&args);
2101 
2102             struct fastboot_buffer buf;
2103             if (!load_buf(filename.c_str(), &buf) || buf.type != FB_BUFFER_FD) {
2104                 die("cannot load '%s'", filename.c_str());
2105             }
2106             fb->Download(filename, buf.fd, buf.sz);
2107         } else if (command == "get_staged") {
2108             std::string filename = next_arg(&args);
2109             fb->Upload(filename);
2110         } else if (command == FB_CMD_OEM) {
2111             do_oem_command(FB_CMD_OEM, &args);
2112         } else if (command == "flashing") {
2113             if (args.empty()) {
2114                 syntax_error("missing 'flashing' command");
2115             } else if (args.size() == 1 && (args[0] == "unlock" || args[0] == "lock" ||
2116                                             args[0] == "unlock_critical" ||
2117                                             args[0] == "lock_critical" ||
2118                                             args[0] == "get_unlock_ability")) {
2119                 do_oem_command("flashing", &args);
2120             } else {
2121                 syntax_error("unknown 'flashing' command %s", args[0].c_str());
2122             }
2123         } else if (command == FB_CMD_CREATE_PARTITION) {
2124             std::string partition = next_arg(&args);
2125             std::string size = next_arg(&args);
2126             fb->CreatePartition(partition, size);
2127         } else if (command == FB_CMD_DELETE_PARTITION) {
2128             std::string partition = next_arg(&args);
2129             fb->DeletePartition(partition);
2130         } else if (command == FB_CMD_RESIZE_PARTITION) {
2131             std::string partition = next_arg(&args);
2132             std::string size = next_arg(&args);
2133             fb->ResizePartition(partition, size);
2134         } else if (command == "gsi") {
2135             std::string arg = next_arg(&args);
2136             if (arg == "wipe") {
2137                 fb->RawCommand("gsi:wipe", "wiping GSI");
2138             } else if (arg == "disable") {
2139                 fb->RawCommand("gsi:disable", "disabling GSI");
2140             } else {
2141                 syntax_error("expected 'wipe' or 'disable'");
2142             }
2143         } else if (command == "wipe-super") {
2144             std::string image;
2145             if (args.empty()) {
2146                 image = find_item_given_name("super_empty.img");
2147             } else {
2148                 image = next_arg(&args);
2149             }
2150             do_wipe_super(image, slot_override);
2151         } else if (command == "snapshot-update") {
2152             std::string arg;
2153             if (!args.empty()) {
2154                 arg = next_arg(&args);
2155             }
2156             if (!arg.empty() && (arg != "cancel" && arg != "merge")) {
2157                 syntax_error("expected: snapshot-update [cancel|merge]");
2158             }
2159             fb->SnapshotUpdateCommand(arg);
2160         } else {
2161             syntax_error("unknown command %s", command.c_str());
2162         }
2163     }
2164 
2165     if (wants_wipe) {
2166         if (force_flash) {
2167             CancelSnapshotIfNeeded();
2168         }
2169         std::vector<std::string> partitions = { "userdata", "cache", "metadata" };
2170         for (const auto& partition : partitions) {
2171             std::string partition_type;
2172             if (fb->GetVar("partition-type:" + partition, &partition_type) != fastboot::SUCCESS) {
2173                 continue;
2174             }
2175             if (partition_type.empty()) continue;
2176             fb->Erase(partition);
2177             if (partition == "userdata" && set_fbe_marker) {
2178                 fprintf(stderr, "setting FBE marker on initial userdata...\n");
2179                 std::string initial_userdata_dir = create_fbemarker_tmpdir();
2180                 fb_perform_format(partition, 1, partition_type, "", initial_userdata_dir);
2181                 delete_fbemarker_tmpdir(initial_userdata_dir);
2182             } else {
2183                 fb_perform_format(partition, 1, partition_type, "", "");
2184             }
2185         }
2186     }
2187     if (wants_set_active) {
2188         fb->SetActive(next_active);
2189     }
2190     if (wants_reboot && !skip_reboot) {
2191         fb->Reboot();
2192         fb->WaitForDisconnect();
2193     } else if (wants_reboot_bootloader) {
2194         fb->RebootTo("bootloader");
2195         fb->WaitForDisconnect();
2196     } else if (wants_reboot_recovery) {
2197         fb->RebootTo("recovery");
2198         fb->WaitForDisconnect();
2199     } else if (wants_reboot_fastboot) {
2200         reboot_to_userspace_fastboot();
2201     }
2202 
2203     fprintf(stderr, "Finished. Total time: %.3fs\n", (now() - start));
2204 
2205     auto* old_transport = fb->set_transport(nullptr);
2206     delete old_transport;
2207 
2208     return 0;
2209 }
2210 
ParseOsPatchLevel(boot_img_hdr_v1 * hdr,const char * arg)2211 void FastBootTool::ParseOsPatchLevel(boot_img_hdr_v1* hdr, const char* arg) {
2212     unsigned year, month, day;
2213     if (sscanf(arg, "%u-%u-%u", &year, &month, &day) != 3) {
2214         syntax_error("OS patch level should be YYYY-MM-DD: %s", arg);
2215     }
2216     if (year < 2000 || year >= 2128) syntax_error("year out of range: %d", year);
2217     if (month < 1 || month > 12) syntax_error("month out of range: %d", month);
2218     hdr->SetOsPatchLevel(year, month);
2219 }
2220 
ParseOsVersion(boot_img_hdr_v1 * hdr,const char * arg)2221 void FastBootTool::ParseOsVersion(boot_img_hdr_v1* hdr, const char* arg) {
2222     unsigned major = 0, minor = 0, patch = 0;
2223     std::vector<std::string> versions = android::base::Split(arg, ".");
2224     if (versions.size() < 1 || versions.size() > 3 ||
2225         (versions.size() >= 1 && !android::base::ParseUint(versions[0], &major)) ||
2226         (versions.size() >= 2 && !android::base::ParseUint(versions[1], &minor)) ||
2227         (versions.size() == 3 && !android::base::ParseUint(versions[2], &patch)) ||
2228         (major > 0x7f || minor > 0x7f || patch > 0x7f)) {
2229         syntax_error("bad OS version: %s", arg);
2230     }
2231     hdr->SetOsVersion(major, minor, patch);
2232 }
2233