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