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