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