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