• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #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 <stdbool.h>
38 #include <stdint.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/stat.h>
43 #include <sys/time.h>
44 #include <sys/types.h>
45 #include <unistd.h>
46 
47 #include <sparse/sparse.h>
48 #include <ziparchive/zip_archive.h>
49 
50 #include "bootimg_utils.h"
51 #include "fastboot.h"
52 #include "fs.h"
53 
54 #ifndef O_BINARY
55 #define O_BINARY 0
56 #endif
57 
58 #define ARRAY_SIZE(a) (sizeof(a)/sizeof(*(a)))
59 
60 char cur_product[FB_RESPONSE_SZ + 1];
61 
62 static const char *serial = 0;
63 static const char *product = 0;
64 static const char *cmdline = 0;
65 static unsigned short vendor_id = 0;
66 static int long_listing = 0;
67 static int64_t sparse_limit = -1;
68 static int64_t target_sparse_limit = -1;
69 
70 unsigned page_size = 2048;
71 unsigned base_addr      = 0x10000000;
72 unsigned kernel_offset  = 0x00008000;
73 unsigned ramdisk_offset = 0x01000000;
74 unsigned second_offset  = 0x00f00000;
75 unsigned tags_offset    = 0x00000100;
76 
77 enum fb_buffer_type {
78     FB_BUFFER,
79     FB_BUFFER_SPARSE,
80 };
81 
82 struct fastboot_buffer {
83     enum fb_buffer_type type;
84     void *data;
85     unsigned int sz;
86 };
87 
88 static struct {
89     char img_name[13];
90     char sig_name[13];
91     char part_name[9];
92     bool is_optional;
93 } images[] = {
94     {"boot.img", "boot.sig", "boot", false},
95     {"recovery.img", "recovery.sig", "recovery", true},
96     {"system.img", "system.sig", "system", false},
97     {"vendor.img", "vendor.sig", "vendor", true},
98 };
99 
find_item(const char * item,const char * product)100 char *find_item(const char *item, const char *product)
101 {
102     char *dir;
103     const char *fn;
104     char path[PATH_MAX + 128];
105 
106     if(!strcmp(item,"boot")) {
107         fn = "boot.img";
108     } else if(!strcmp(item,"recovery")) {
109         fn = "recovery.img";
110     } else if(!strcmp(item,"system")) {
111         fn = "system.img";
112     } else if(!strcmp(item,"vendor")) {
113         fn = "vendor.img";
114     } else if(!strcmp(item,"userdata")) {
115         fn = "userdata.img";
116     } else if(!strcmp(item,"cache")) {
117         fn = "cache.img";
118     } else if(!strcmp(item,"info")) {
119         fn = "android-info.txt";
120     } else {
121         fprintf(stderr,"unknown partition '%s'\n", item);
122         return 0;
123     }
124 
125     if(product) {
126         get_my_path(path);
127         sprintf(path + strlen(path),
128                 "../../../target/product/%s/%s", product, fn);
129         return strdup(path);
130     }
131 
132     dir = getenv("ANDROID_PRODUCT_OUT");
133     if((dir == 0) || (dir[0] == 0)) {
134         die("neither -p product specified nor ANDROID_PRODUCT_OUT set");
135         return 0;
136     }
137 
138     sprintf(path, "%s/%s", dir, fn);
139     return strdup(path);
140 }
141 
file_size(int fd)142 static int64_t file_size(int fd)
143 {
144     struct stat st;
145     int ret;
146 
147     ret = fstat(fd, &st);
148 
149     return ret ? -1 : st.st_size;
150 }
151 
load_fd(int fd,unsigned * _sz)152 static void *load_fd(int fd, unsigned *_sz)
153 {
154     char *data;
155     int sz;
156     int errno_tmp;
157 
158     data = 0;
159 
160     sz = file_size(fd);
161     if (sz < 0) {
162         goto oops;
163     }
164 
165     data = (char*) malloc(sz);
166     if(data == 0) goto oops;
167 
168     if(read(fd, data, sz) != sz) goto oops;
169     close(fd);
170 
171     if(_sz) *_sz = sz;
172     return data;
173 
174 oops:
175     errno_tmp = errno;
176     close(fd);
177     if(data != 0) free(data);
178     errno = errno_tmp;
179     return 0;
180 }
181 
load_file(const char * fn,unsigned * _sz)182 static void *load_file(const char *fn, unsigned *_sz)
183 {
184     int fd;
185 
186     fd = open(fn, O_RDONLY | O_BINARY);
187     if(fd < 0) return 0;
188 
189     return load_fd(fd, _sz);
190 }
191 
match_fastboot_with_serial(usb_ifc_info * info,const char * local_serial)192 int match_fastboot_with_serial(usb_ifc_info *info, const char *local_serial)
193 {
194     if(!(vendor_id && (info->dev_vendor == vendor_id)) &&
195        (info->dev_vendor != 0x18d1) &&  // Google
196        (info->dev_vendor != 0x8087) &&  // Intel
197        (info->dev_vendor != 0x0451) &&
198        (info->dev_vendor != 0x0502) &&
199        (info->dev_vendor != 0x0fce) &&  // Sony Ericsson
200        (info->dev_vendor != 0x05c6) &&  // Qualcomm
201        (info->dev_vendor != 0x22b8) &&  // Motorola
202        (info->dev_vendor != 0x0955) &&  // Nvidia
203        (info->dev_vendor != 0x413c) &&  // DELL
204        (info->dev_vendor != 0x2314) &&  // INQ Mobile
205        (info->dev_vendor != 0x0b05) &&  // Asus
206        (info->dev_vendor != 0x0bb4))    // HTC
207             return -1;
208     if(info->ifc_class != 0xff) return -1;
209     if(info->ifc_subclass != 0x42) return -1;
210     if(info->ifc_protocol != 0x03) return -1;
211     // require matching serial number or device path if requested
212     // at the command line with the -s option.
213     if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
214                    strcmp(local_serial, info->device_path) != 0)) return -1;
215     return 0;
216 }
217 
match_fastboot(usb_ifc_info * info)218 int match_fastboot(usb_ifc_info *info)
219 {
220     return match_fastboot_with_serial(info, serial);
221 }
222 
list_devices_callback(usb_ifc_info * info)223 int list_devices_callback(usb_ifc_info *info)
224 {
225     if (match_fastboot_with_serial(info, NULL) == 0) {
226         const char* serial = info->serial_number;
227         if (!info->writable) {
228             serial = "no permissions"; // like "adb devices"
229         }
230         if (!serial[0]) {
231             serial = "????????????";
232         }
233         // output compatible with "adb devices"
234         if (!long_listing) {
235             printf("%s\tfastboot\n", serial);
236         } else if (strcmp("", info->device_path) == 0) {
237             printf("%-22s fastboot\n", serial);
238         } else {
239             printf("%-22s fastboot %s\n", serial, info->device_path);
240         }
241     }
242 
243     return -1;
244 }
245 
open_device(void)246 usb_handle *open_device(void)
247 {
248     static usb_handle *usb = 0;
249     int announce = 1;
250 
251     if(usb) return usb;
252 
253     for(;;) {
254         usb = usb_open(match_fastboot);
255         if(usb) return usb;
256         if(announce) {
257             announce = 0;
258             fprintf(stderr,"< waiting for device >\n");
259         }
260         usleep(1000);
261     }
262 }
263 
list_devices(void)264 void list_devices(void) {
265     // We don't actually open a USB device here,
266     // just getting our callback called so we can
267     // list all the connected devices.
268     usb_open(list_devices_callback);
269 }
270 
usage(void)271 void usage(void)
272 {
273     fprintf(stderr,
274 /*           1234567890123456789012345678901234567890123456789012345678901234567890123456 */
275             "usage: fastboot [ <option> ] <command>\n"
276             "\n"
277             "commands:\n"
278             "  update <filename>                        reflash device from update.zip\n"
279             "  flashall                                 flash boot, system, vendor and if found,\n"
280             "                                           recovery\n"
281             "  flash <partition> [ <filename> ]         write a file to a flash partition\n"
282             "  flashing lock                            locks the device. Prevents flashing\n"
283             "                                           partitions\n"
284             "  flashing unlock                          unlocks the device. Allows user to\n"
285             "                                           flash any partition except the ones\n"
286             "                                           that are related to bootloader\n"
287             "  flashing lock_critical                   Prevents flashing bootloader related\n"
288             "                                           partitions\n"
289             "  flashing unlock_critical                 Enables flashing bootloader related\n"
290             "                                           partitions\n"
291             "  flashing get_unlock_ability              Queries bootloader to see if the\n"
292             "                                           device is unlocked\n"
293             "  flashing get_unlock_bootloader_nonce     Queries the bootloader to get the\n"
294             "                                           unlock nonce\n"
295             "  flashing unlock_bootloader <request>     Issue unlock bootloader using request\n"
296             "  flashing lock_bootloader                 Locks the bootloader to prevent\n"
297             "                                           bootloader version rollback\n"
298             "  erase <partition>                        erase a flash partition\n"
299             "  format[:[<fs type>][:[<size>]] <partition> format a flash partition.\n"
300             "                                           Can override the fs type and/or\n"
301             "                                           size the bootloader reports.\n"
302             "  getvar <variable>                        display a bootloader variable\n"
303             "  boot <kernel> [ <ramdisk> ]              download and boot kernel\n"
304             "  flash:raw boot <kernel> [ <ramdisk> ]    create bootimage and flash it\n"
305             "  devices                                  list all connected devices\n"
306             "  continue                                 continue with autoboot\n"
307             "  reboot [bootloader]                      reboot device, optionally into bootloader\n"
308             "  reboot-bootloader                        reboot device into bootloader\n"
309             "  help                                     show this help message\n"
310             "\n"
311             "options:\n"
312             "  -w                                       erase userdata and cache (and format\n"
313             "                                           if supported by partition type)\n"
314             "  -u                                       do not first erase partition before\n"
315             "                                           formatting\n"
316             "  -s <specific device>                     specify device serial number\n"
317             "                                           or path to device port\n"
318             "  -l                                       with \"devices\", lists device paths\n"
319             "  -p <product>                             specify product name\n"
320             "  -c <cmdline>                             override kernel commandline\n"
321             "  -i <vendor id>                           specify a custom USB vendor id\n"
322             "  -b <base_addr>                           specify a custom kernel base address.\n"
323             "                                           default: 0x10000000\n"
324             "  -n <page size>                           specify the nand page size.\n"
325             "                                           default: 2048\n"
326             "  -S <size>[K|M|G]                         automatically sparse files greater\n"
327             "                                           than size.  0 to disable\n"
328         );
329 }
330 
load_bootable_image(const char * kernel,const char * ramdisk,unsigned * sz,const char * cmdline)331 void *load_bootable_image(const char *kernel, const char *ramdisk,
332                           unsigned *sz, const char *cmdline)
333 {
334     void *kdata = 0, *rdata = 0;
335     unsigned ksize = 0, rsize = 0;
336     void *bdata;
337     unsigned bsize;
338 
339     if(kernel == 0) {
340         fprintf(stderr, "no image specified\n");
341         return 0;
342     }
343 
344     kdata = load_file(kernel, &ksize);
345     if(kdata == 0) {
346         fprintf(stderr, "cannot load '%s': %s\n", kernel, strerror(errno));
347         return 0;
348     }
349 
350         /* is this actually a boot image? */
351     if(!memcmp(kdata, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
352         if(cmdline) bootimg_set_cmdline((boot_img_hdr*) kdata, cmdline);
353 
354         if(ramdisk) {
355             fprintf(stderr, "cannot boot a boot.img *and* ramdisk\n");
356             return 0;
357         }
358 
359         *sz = ksize;
360         return kdata;
361     }
362 
363     if(ramdisk) {
364         rdata = load_file(ramdisk, &rsize);
365         if(rdata == 0) {
366             fprintf(stderr,"cannot load '%s': %s\n", ramdisk, strerror(errno));
367             return  0;
368         }
369     }
370 
371     fprintf(stderr,"creating boot image...\n");
372     bdata = mkbootimg(kdata, ksize, kernel_offset,
373                       rdata, rsize, ramdisk_offset,
374                       0, 0, second_offset,
375                       page_size, base_addr, tags_offset, &bsize);
376     if(bdata == 0) {
377         fprintf(stderr,"failed to create boot.img\n");
378         return 0;
379     }
380     if(cmdline) bootimg_set_cmdline((boot_img_hdr*) bdata, cmdline);
381     fprintf(stderr,"creating boot image - %d bytes\n", bsize);
382     *sz = bsize;
383 
384     return bdata;
385 }
386 
unzip_file(ZipArchiveHandle zip,const char * entry_name,unsigned * sz)387 static void* unzip_file(ZipArchiveHandle zip, const char* entry_name, unsigned* sz)
388 {
389     ZipEntryName zip_entry_name(entry_name);
390     ZipEntry zip_entry;
391     if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
392         fprintf(stderr, "archive does not contain '%s'\n", entry_name);
393         return 0;
394     }
395 
396     *sz = zip_entry.uncompressed_length;
397 
398     uint8_t* data = reinterpret_cast<uint8_t*>(malloc(zip_entry.uncompressed_length));
399     if (data == NULL) {
400         fprintf(stderr, "failed to allocate %u bytes for '%s'\n", *sz, entry_name);
401         return 0;
402     }
403 
404     int error = ExtractToMemory(zip, &zip_entry, data, zip_entry.uncompressed_length);
405     if (error != 0) {
406         fprintf(stderr, "failed to extract '%s': %s\n", entry_name, ErrorCodeString(error));
407         free(data);
408         return 0;
409     }
410 
411     return data;
412 }
413 
414 #if defined(_WIN32)
415 
416 // TODO: move this to somewhere it can be shared.
417 
418 #include <windows.h>
419 
420 // Windows' tmpfile(3) requires administrator rights because
421 // it creates temporary files in the root directory.
win32_tmpfile()422 static FILE* win32_tmpfile() {
423     char temp_path[PATH_MAX];
424     DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
425     if (nchars == 0 || nchars >= sizeof(temp_path)) {
426         fprintf(stderr, "GetTempPath failed, error %ld\n", GetLastError());
427         return nullptr;
428     }
429 
430     char filename[PATH_MAX];
431     if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
432         fprintf(stderr, "GetTempFileName failed, error %ld\n", GetLastError());
433         return nullptr;
434     }
435 
436     return fopen(filename, "w+bTD");
437 }
438 
439 #define tmpfile win32_tmpfile
440 
441 #endif
442 
unzip_to_file(ZipArchiveHandle zip,char * entry_name)443 static int unzip_to_file(ZipArchiveHandle zip, char* entry_name) {
444     FILE* fp = tmpfile();
445     if (fp == NULL) {
446         fprintf(stderr, "failed to create temporary file for '%s': %s\n",
447                 entry_name, strerror(errno));
448         return -1;
449     }
450 
451     ZipEntryName zip_entry_name(entry_name);
452     ZipEntry zip_entry;
453     if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
454         fprintf(stderr, "archive does not contain '%s'\n", entry_name);
455         return -1;
456     }
457 
458     int fd = fileno(fp);
459     int error = ExtractEntryToFile(zip, &zip_entry, fd);
460     if (error != 0) {
461         fprintf(stderr, "failed to extract '%s': %s\n", entry_name, ErrorCodeString(error));
462         return -1;
463     }
464 
465     lseek(fd, 0, SEEK_SET);
466     return fd;
467 }
468 
strip(char * s)469 static char *strip(char *s)
470 {
471     int n;
472     while(*s && isspace(*s)) s++;
473     n = strlen(s);
474     while(n-- > 0) {
475         if(!isspace(s[n])) break;
476         s[n] = 0;
477     }
478     return s;
479 }
480 
481 #define MAX_OPTIONS 32
setup_requirement_line(char * name)482 static int setup_requirement_line(char *name)
483 {
484     char *val[MAX_OPTIONS];
485     char *prod = NULL;
486     unsigned n, count;
487     char *x;
488     int invert = 0;
489 
490     if (!strncmp(name, "reject ", 7)) {
491         name += 7;
492         invert = 1;
493     } else if (!strncmp(name, "require ", 8)) {
494         name += 8;
495         invert = 0;
496     } else if (!strncmp(name, "require-for-product:", 20)) {
497         // Get the product and point name past it
498         prod = name + 20;
499         name = strchr(name, ' ');
500         if (!name) return -1;
501         *name = 0;
502         name += 1;
503         invert = 0;
504     }
505 
506     x = strchr(name, '=');
507     if (x == 0) return 0;
508     *x = 0;
509     val[0] = x + 1;
510 
511     for(count = 1; count < MAX_OPTIONS; count++) {
512         x = strchr(val[count - 1],'|');
513         if (x == 0) break;
514         *x = 0;
515         val[count] = x + 1;
516     }
517 
518     name = strip(name);
519     for(n = 0; n < count; n++) val[n] = strip(val[n]);
520 
521     name = strip(name);
522     if (name == 0) return -1;
523 
524     const char* var = name;
525     // Work around an unfortunate name mismatch.
526     if (!strcmp(name,"board")) var = "product";
527 
528     const char** out = reinterpret_cast<const char**>(malloc(sizeof(char*) * count));
529     if (out == 0) return -1;
530 
531     for(n = 0; n < count; n++) {
532         out[n] = strdup(strip(val[n]));
533         if (out[n] == 0) {
534             for(size_t i = 0; i < n; ++i) {
535                 free((char*) out[i]);
536             }
537             free(out);
538             return -1;
539         }
540     }
541 
542     fb_queue_require(prod, var, invert, n, out);
543     return 0;
544 }
545 
setup_requirements(char * data,unsigned sz)546 static void setup_requirements(char *data, unsigned sz)
547 {
548     char *s;
549 
550     s = data;
551     while (sz-- > 0) {
552         if(*s == '\n') {
553             *s++ = 0;
554             if (setup_requirement_line(data)) {
555                 die("out of memory");
556             }
557             data = s;
558         } else {
559             s++;
560         }
561     }
562 }
563 
queue_info_dump(void)564 void queue_info_dump(void)
565 {
566     fb_queue_notice("--------------------------------------------");
567     fb_queue_display("version-bootloader", "Bootloader Version...");
568     fb_queue_display("version-baseband",   "Baseband Version.....");
569     fb_queue_display("serialno",           "Serial Number........");
570     fb_queue_notice("--------------------------------------------");
571 }
572 
load_sparse_files(int fd,int max_size)573 static struct sparse_file **load_sparse_files(int fd, int max_size)
574 {
575     struct sparse_file* s = sparse_file_import_auto(fd, false, true);
576     if (!s) {
577         die("cannot sparse read file\n");
578     }
579 
580     int files = sparse_file_resparse(s, max_size, NULL, 0);
581     if (files < 0) {
582         die("Failed to resparse\n");
583     }
584 
585     sparse_file** out_s = reinterpret_cast<sparse_file**>(calloc(sizeof(struct sparse_file *), files + 1));
586     if (!out_s) {
587         die("Failed to allocate sparse file array\n");
588     }
589 
590     files = sparse_file_resparse(s, max_size, out_s, files);
591     if (files < 0) {
592         die("Failed to resparse\n");
593     }
594 
595     return out_s;
596 }
597 
get_target_sparse_limit(struct usb_handle * usb)598 static int64_t get_target_sparse_limit(struct usb_handle *usb)
599 {
600     int64_t limit = 0;
601     char response[FB_RESPONSE_SZ + 1];
602     int status = fb_getvar(usb, response, "max-download-size");
603 
604     if (!status) {
605         limit = strtoul(response, NULL, 0);
606         if (limit > 0) {
607             fprintf(stderr, "target reported max download size of %" PRId64 " bytes\n",
608                     limit);
609         }
610     }
611 
612     return limit;
613 }
614 
get_sparse_limit(struct usb_handle * usb,int64_t size)615 static int64_t get_sparse_limit(struct usb_handle *usb, int64_t size)
616 {
617     int64_t limit;
618 
619     if (sparse_limit == 0) {
620         return 0;
621     } else if (sparse_limit > 0) {
622         limit = sparse_limit;
623     } else {
624         if (target_sparse_limit == -1) {
625             target_sparse_limit = get_target_sparse_limit(usb);
626         }
627         if (target_sparse_limit > 0) {
628             limit = target_sparse_limit;
629         } else {
630             return 0;
631         }
632     }
633 
634     if (size > limit) {
635         return limit;
636     }
637 
638     return 0;
639 }
640 
641 /* Until we get lazy inode table init working in make_ext4fs, we need to
642  * erase partitions of type ext4 before flashing a filesystem so no stale
643  * inodes are left lying around.  Otherwise, e2fsck gets very upset.
644  */
needs_erase(usb_handle * usb,const char * part)645 static int needs_erase(usb_handle* usb, const char *part)
646 {
647     /* The function fb_format_supported() currently returns the value
648      * we want, so just call it.
649      */
650      return fb_format_supported(usb, part, NULL);
651 }
652 
load_buf_fd(usb_handle * usb,int fd,struct fastboot_buffer * buf)653 static int load_buf_fd(usb_handle *usb, int fd,
654         struct fastboot_buffer *buf)
655 {
656     int64_t sz64;
657     void *data;
658     int64_t limit;
659 
660 
661     sz64 = file_size(fd);
662     if (sz64 < 0) {
663         return -1;
664     }
665 
666     lseek(fd, 0, SEEK_SET);
667     limit = get_sparse_limit(usb, sz64);
668     if (limit) {
669         struct sparse_file **s = load_sparse_files(fd, limit);
670         if (s == NULL) {
671             return -1;
672         }
673         buf->type = FB_BUFFER_SPARSE;
674         buf->data = s;
675     } else {
676         unsigned int sz;
677         data = load_fd(fd, &sz);
678         if (data == 0) return -1;
679         buf->type = FB_BUFFER;
680         buf->data = data;
681         buf->sz = sz;
682     }
683 
684     return 0;
685 }
686 
load_buf(usb_handle * usb,const char * fname,struct fastboot_buffer * buf)687 static int load_buf(usb_handle *usb, const char *fname,
688         struct fastboot_buffer *buf)
689 {
690     int fd;
691 
692     fd = open(fname, O_RDONLY | O_BINARY);
693     if (fd < 0) {
694         return -1;
695     }
696 
697     return load_buf_fd(usb, fd, buf);
698 }
699 
flash_buf(const char * pname,struct fastboot_buffer * buf)700 static void flash_buf(const char *pname, struct fastboot_buffer *buf)
701 {
702     sparse_file** s;
703 
704     switch (buf->type) {
705         case FB_BUFFER_SPARSE:
706             s = reinterpret_cast<sparse_file**>(buf->data);
707             while (*s) {
708                 int64_t sz64 = sparse_file_len(*s, true, false);
709                 fb_queue_flash_sparse(pname, *s++, sz64);
710             }
711             break;
712         case FB_BUFFER:
713             fb_queue_flash(pname, buf->data, buf->sz);
714             break;
715         default:
716             die("unknown buffer type: %d", buf->type);
717     }
718 }
719 
do_flash(usb_handle * usb,const char * pname,const char * fname)720 void do_flash(usb_handle *usb, const char *pname, const char *fname)
721 {
722     struct fastboot_buffer buf;
723 
724     if (load_buf(usb, fname, &buf)) {
725         die("cannot load '%s'", fname);
726     }
727     flash_buf(pname, &buf);
728 }
729 
do_update_signature(ZipArchiveHandle zip,char * fn)730 void do_update_signature(ZipArchiveHandle zip, char *fn)
731 {
732     unsigned sz;
733     void* data = unzip_file(zip, fn, &sz);
734     if (data == 0) return;
735     fb_queue_download("signature", data, sz);
736     fb_queue_command("signature", "installing signature");
737 }
738 
do_update(usb_handle * usb,const char * filename,int erase_first)739 void do_update(usb_handle *usb, const char *filename, int erase_first)
740 {
741     queue_info_dump();
742 
743     fb_queue_query_save("product", cur_product, sizeof(cur_product));
744 
745     ZipArchiveHandle zip;
746     int error = OpenArchive(filename, &zip);
747     if (error != 0) {
748         CloseArchive(zip);
749         die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
750     }
751 
752     unsigned sz;
753     void* data = unzip_file(zip, "android-info.txt", &sz);
754     if (data == 0) {
755         CloseArchive(zip);
756         die("update package '%s' has no android-info.txt", filename);
757     }
758 
759     setup_requirements(reinterpret_cast<char*>(data), sz);
760 
761     for (size_t i = 0; i < ARRAY_SIZE(images); ++i) {
762         int fd = unzip_to_file(zip, images[i].img_name);
763         if (fd == -1) {
764             if (images[i].is_optional) {
765                 continue;
766             }
767             CloseArchive(zip);
768             exit(1); // unzip_to_file already explained why.
769         }
770         fastboot_buffer buf;
771         int rc = load_buf_fd(usb, fd, &buf);
772         if (rc) die("cannot load %s from flash", images[i].img_name);
773         do_update_signature(zip, images[i].sig_name);
774         if (erase_first && needs_erase(usb, images[i].part_name)) {
775             fb_queue_erase(images[i].part_name);
776         }
777         flash_buf(images[i].part_name, &buf);
778         /* not closing the fd here since the sparse code keeps the fd around
779          * but hasn't mmaped data yet. The tmpfile will get cleaned up when the
780          * program exits.
781          */
782     }
783 
784     CloseArchive(zip);
785 }
786 
do_send_signature(char * fn)787 void do_send_signature(char *fn)
788 {
789     void *data;
790     unsigned sz;
791     char *xtn;
792 
793     xtn = strrchr(fn, '.');
794     if (!xtn) return;
795     if (strcmp(xtn, ".img")) return;
796 
797     strcpy(xtn,".sig");
798     data = load_file(fn, &sz);
799     strcpy(xtn,".img");
800     if (data == 0) return;
801     fb_queue_download("signature", data, sz);
802     fb_queue_command("signature", "installing signature");
803 }
804 
do_flashall(usb_handle * usb,int erase_first)805 void do_flashall(usb_handle *usb, int erase_first)
806 {
807     queue_info_dump();
808 
809     fb_queue_query_save("product", cur_product, sizeof(cur_product));
810 
811     char* fname = find_item("info", product);
812     if (fname == 0) die("cannot find android-info.txt");
813 
814     unsigned sz;
815     void* data = load_file(fname, &sz);
816     if (data == 0) die("could not load android-info.txt: %s", strerror(errno));
817 
818     setup_requirements(reinterpret_cast<char*>(data), sz);
819 
820     for (size_t i = 0; i < ARRAY_SIZE(images); i++) {
821         fname = find_item(images[i].part_name, product);
822         fastboot_buffer buf;
823         if (load_buf(usb, fname, &buf)) {
824             if (images[i].is_optional)
825                 continue;
826             die("could not load %s\n", images[i].img_name);
827         }
828         do_send_signature(fname);
829         if (erase_first && needs_erase(usb, images[i].part_name)) {
830             fb_queue_erase(images[i].part_name);
831         }
832         flash_buf(images[i].part_name, &buf);
833     }
834 }
835 
836 #define skip(n) do { argc -= (n); argv += (n); } while (0)
837 #define require(n) do { if (argc < (n)) {usage(); exit(1);}} while (0)
838 
do_bypass_unlock_command(int argc,char ** argv)839 int do_bypass_unlock_command(int argc, char **argv)
840 {
841     unsigned sz;
842     void *data;
843 
844     if (argc <= 2) return 0;
845     skip(2);
846 
847     /*
848      * Process unlock_bootloader, we have to load the message file
849      * and send that to the remote device.
850      */
851     require(1);
852     data = load_file(*argv, &sz);
853     if (data == 0) die("could not load '%s': %s", *argv, strerror(errno));
854     fb_queue_download("unlock_message", data, sz);
855     fb_queue_command("flashing unlock_bootloader", "unlocking bootloader");
856     skip(1);
857     return 0;
858 }
859 
do_oem_command(int argc,char ** argv)860 int do_oem_command(int argc, char **argv)
861 {
862     char command[256];
863     if (argc <= 1) return 0;
864 
865     command[0] = 0;
866     while(1) {
867         strcat(command,*argv);
868         skip(1);
869         if(argc == 0) break;
870         strcat(command," ");
871     }
872 
873     fb_queue_command(command,"");
874     return 0;
875 }
876 
parse_num(const char * arg)877 static int64_t parse_num(const char *arg)
878 {
879     char *endptr;
880     unsigned long long num;
881 
882     num = strtoull(arg, &endptr, 0);
883     if (endptr == arg) {
884         return -1;
885     }
886 
887     if (*endptr == 'k' || *endptr == 'K') {
888         if (num >= (-1ULL) / 1024) {
889             return -1;
890         }
891         num *= 1024LL;
892         endptr++;
893     } else if (*endptr == 'm' || *endptr == 'M') {
894         if (num >= (-1ULL) / (1024 * 1024)) {
895             return -1;
896         }
897         num *= 1024LL * 1024LL;
898         endptr++;
899     } else if (*endptr == 'g' || *endptr == 'G') {
900         if (num >= (-1ULL) / (1024 * 1024 * 1024)) {
901             return -1;
902         }
903         num *= 1024LL * 1024LL * 1024LL;
904         endptr++;
905     }
906 
907     if (*endptr != '\0') {
908         return -1;
909     }
910 
911     if (num > INT64_MAX) {
912         return -1;
913     }
914 
915     return num;
916 }
917 
fb_perform_format(usb_handle * usb,const char * partition,int skip_if_not_supported,const char * type_override,const char * size_override)918 void fb_perform_format(usb_handle* usb,
919                        const char *partition, int skip_if_not_supported,
920                        const char *type_override, const char *size_override)
921 {
922     char pTypeBuff[FB_RESPONSE_SZ + 1], pSizeBuff[FB_RESPONSE_SZ + 1];
923     char *pType = pTypeBuff;
924     char *pSize = pSizeBuff;
925     unsigned int limit = INT_MAX;
926     struct fastboot_buffer buf;
927     const char *errMsg = NULL;
928     const struct fs_generator *gen;
929     uint64_t pSz;
930     int status;
931     int fd;
932 
933     if (target_sparse_limit > 0 && target_sparse_limit < limit)
934         limit = target_sparse_limit;
935     if (sparse_limit > 0 && sparse_limit < limit)
936         limit = sparse_limit;
937 
938     status = fb_getvar(usb, pType, "partition-type:%s", partition);
939     if (status) {
940         errMsg = "Can't determine partition type.\n";
941         goto failed;
942     }
943     if (type_override) {
944         if (strcmp(type_override, pType)) {
945             fprintf(stderr,
946                     "Warning: %s type is %s, but %s was requested for formating.\n",
947                     partition, pType, type_override);
948         }
949         pType = (char *)type_override;
950     }
951 
952     status = fb_getvar(usb, pSize, "partition-size:%s", partition);
953     if (status) {
954         errMsg = "Unable to get partition size\n";
955         goto failed;
956     }
957     if (size_override) {
958         if (strcmp(size_override, pSize)) {
959             fprintf(stderr,
960                     "Warning: %s size is %s, but %s was requested for formating.\n",
961                     partition, pSize, size_override);
962         }
963         pSize = (char *)size_override;
964     }
965 
966     gen = fs_get_generator(pType);
967     if (!gen) {
968         if (skip_if_not_supported) {
969             fprintf(stderr, "Erase successful, but not automatically formatting.\n");
970             fprintf(stderr, "File system type %s not supported.\n", pType);
971             return;
972         }
973         fprintf(stderr, "Formatting is not supported for filesystem with type '%s'.\n", pType);
974         return;
975     }
976 
977     pSz = strtoll(pSize, (char **)NULL, 16);
978 
979     fd = fileno(tmpfile());
980     if (fs_generator_generate(gen, fd, pSz)) {
981         close(fd);
982         fprintf(stderr, "Cannot generate image.\n");
983         return;
984     }
985 
986     if (load_buf_fd(usb, fd, &buf)) {
987         fprintf(stderr, "Cannot read image.\n");
988         close(fd);
989         return;
990     }
991     flash_buf(partition, &buf);
992 
993     return;
994 
995 
996 failed:
997     if (skip_if_not_supported) {
998         fprintf(stderr, "Erase successful, but not automatically formatting.\n");
999         if (errMsg)
1000             fprintf(stderr, "%s", errMsg);
1001     }
1002     fprintf(stderr,"FAILED (%s)\n", fb_get_error());
1003 }
1004 
main(int argc,char ** argv)1005 int main(int argc, char **argv)
1006 {
1007     int wants_wipe = 0;
1008     int wants_reboot = 0;
1009     int wants_reboot_bootloader = 0;
1010     int erase_first = 1;
1011     void *data;
1012     unsigned sz;
1013     int status;
1014     int c;
1015     int longindex;
1016 
1017     const struct option longopts[] = {
1018         {"base", required_argument, 0, 'b'},
1019         {"kernel_offset", required_argument, 0, 'k'},
1020         {"page_size", required_argument, 0, 'n'},
1021         {"ramdisk_offset", required_argument, 0, 'r'},
1022         {"tags_offset", required_argument, 0, 't'},
1023         {"help", no_argument, 0, 'h'},
1024         {"unbuffered", no_argument, 0, 0},
1025         {"version", no_argument, 0, 0},
1026         {0, 0, 0, 0}
1027     };
1028 
1029     serial = getenv("ANDROID_SERIAL");
1030 
1031     while (1) {
1032         c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lp:c:i:m:h", longopts, &longindex);
1033         if (c < 0) {
1034             break;
1035         }
1036         /* Alphabetical cases */
1037         switch (c) {
1038         case 'b':
1039             base_addr = strtoul(optarg, 0, 16);
1040             break;
1041         case 'c':
1042             cmdline = optarg;
1043             break;
1044         case 'h':
1045             usage();
1046             return 1;
1047         case 'i': {
1048                 char *endptr = NULL;
1049                 unsigned long val;
1050 
1051                 val = strtoul(optarg, &endptr, 0);
1052                 if (!endptr || *endptr != '\0' || (val & ~0xffff))
1053                     die("invalid vendor id '%s'", optarg);
1054                 vendor_id = (unsigned short)val;
1055                 break;
1056             }
1057         case 'k':
1058             kernel_offset = strtoul(optarg, 0, 16);
1059             break;
1060         case 'l':
1061             long_listing = 1;
1062             break;
1063         case 'n':
1064             page_size = (unsigned)strtoul(optarg, NULL, 0);
1065             if (!page_size) die("invalid page size");
1066             break;
1067         case 'p':
1068             product = optarg;
1069             break;
1070         case 'r':
1071             ramdisk_offset = strtoul(optarg, 0, 16);
1072             break;
1073         case 't':
1074             tags_offset = strtoul(optarg, 0, 16);
1075             break;
1076         case 's':
1077             serial = optarg;
1078             break;
1079         case 'S':
1080             sparse_limit = parse_num(optarg);
1081             if (sparse_limit < 0) {
1082                     die("invalid sparse limit");
1083             }
1084             break;
1085         case 'u':
1086             erase_first = 0;
1087             break;
1088         case 'w':
1089             wants_wipe = 1;
1090             break;
1091         case '?':
1092             return 1;
1093         case 0:
1094             if (strcmp("unbuffered", longopts[longindex].name) == 0) {
1095                 setvbuf(stdout, NULL, _IONBF, 0);
1096                 setvbuf(stderr, NULL, _IONBF, 0);
1097             } else if (strcmp("version", longopts[longindex].name) == 0) {
1098                 fprintf(stdout, "fastboot version %s\n", FASTBOOT_REVISION);
1099                 return 0;
1100             }
1101             break;
1102         default:
1103             abort();
1104         }
1105     }
1106 
1107     argc -= optind;
1108     argv += optind;
1109 
1110     if (argc == 0 && !wants_wipe) {
1111         usage();
1112         return 1;
1113     }
1114 
1115     if (argc > 0 && !strcmp(*argv, "devices")) {
1116         skip(1);
1117         list_devices();
1118         return 0;
1119     }
1120 
1121     if (argc > 0 && !strcmp(*argv, "help")) {
1122         usage();
1123         return 0;
1124     }
1125 
1126     usb_handle* usb = open_device();
1127 
1128     while (argc > 0) {
1129         if(!strcmp(*argv, "getvar")) {
1130             require(2);
1131             fb_queue_display(argv[1], argv[1]);
1132             skip(2);
1133         } else if(!strcmp(*argv, "erase")) {
1134             require(2);
1135 
1136             if (fb_format_supported(usb, argv[1], NULL)) {
1137                 fprintf(stderr, "******** Did you mean to fastboot format this partition?\n");
1138             }
1139 
1140             fb_queue_erase(argv[1]);
1141             skip(2);
1142         } else if(!strncmp(*argv, "format", strlen("format"))) {
1143             char *overrides;
1144             char *type_override = NULL;
1145             char *size_override = NULL;
1146             require(2);
1147             /*
1148              * Parsing for: "format[:[type][:[size]]]"
1149              * Some valid things:
1150              *  - select ontly the size, and leave default fs type:
1151              *    format::0x4000000 userdata
1152              *  - default fs type and size:
1153              *    format userdata
1154              *    format:: userdata
1155              */
1156             overrides = strchr(*argv, ':');
1157             if (overrides) {
1158                 overrides++;
1159                 size_override = strchr(overrides, ':');
1160                 if (size_override) {
1161                     size_override[0] = '\0';
1162                     size_override++;
1163                 }
1164                 type_override = overrides;
1165             }
1166             if (type_override && !type_override[0]) type_override = NULL;
1167             if (size_override && !size_override[0]) size_override = NULL;
1168             if (erase_first && needs_erase(usb, argv[1])) {
1169                 fb_queue_erase(argv[1]);
1170             }
1171             fb_perform_format(usb, argv[1], 0, type_override, size_override);
1172             skip(2);
1173         } else if(!strcmp(*argv, "signature")) {
1174             require(2);
1175             data = load_file(argv[1], &sz);
1176             if (data == 0) die("could not load '%s': %s", argv[1], strerror(errno));
1177             if (sz != 256) die("signature must be 256 bytes");
1178             fb_queue_download("signature", data, sz);
1179             fb_queue_command("signature", "installing signature");
1180             skip(2);
1181         } else if(!strcmp(*argv, "reboot")) {
1182             wants_reboot = 1;
1183             skip(1);
1184             if (argc > 0) {
1185                 if (!strcmp(*argv, "bootloader")) {
1186                     wants_reboot = 0;
1187                     wants_reboot_bootloader = 1;
1188                     skip(1);
1189                 }
1190             }
1191             require(0);
1192         } else if(!strcmp(*argv, "reboot-bootloader")) {
1193             wants_reboot_bootloader = 1;
1194             skip(1);
1195         } else if (!strcmp(*argv, "continue")) {
1196             fb_queue_command("continue", "resuming boot");
1197             skip(1);
1198         } else if(!strcmp(*argv, "boot")) {
1199             char *kname = 0;
1200             char *rname = 0;
1201             skip(1);
1202             if (argc > 0) {
1203                 kname = argv[0];
1204                 skip(1);
1205             }
1206             if (argc > 0) {
1207                 rname = argv[0];
1208                 skip(1);
1209             }
1210             data = load_bootable_image(kname, rname, &sz, cmdline);
1211             if (data == 0) return 1;
1212             fb_queue_download("boot.img", data, sz);
1213             fb_queue_command("boot", "booting");
1214         } else if(!strcmp(*argv, "flash")) {
1215             char *pname = argv[1];
1216             char *fname = 0;
1217             require(2);
1218             if (argc > 2) {
1219                 fname = argv[2];
1220                 skip(3);
1221             } else {
1222                 fname = find_item(pname, product);
1223                 skip(2);
1224             }
1225             if (fname == 0) die("cannot determine image filename for '%s'", pname);
1226             if (erase_first && needs_erase(usb, pname)) {
1227                 fb_queue_erase(pname);
1228             }
1229             do_flash(usb, pname, fname);
1230         } else if(!strcmp(*argv, "flash:raw")) {
1231             char *pname = argv[1];
1232             char *kname = argv[2];
1233             char *rname = 0;
1234             require(3);
1235             if(argc > 3) {
1236                 rname = argv[3];
1237                 skip(4);
1238             } else {
1239                 skip(3);
1240             }
1241             data = load_bootable_image(kname, rname, &sz, cmdline);
1242             if (data == 0) die("cannot load bootable image");
1243             fb_queue_flash(pname, data, sz);
1244         } else if(!strcmp(*argv, "flashall")) {
1245             skip(1);
1246             do_flashall(usb, erase_first);
1247             wants_reboot = 1;
1248         } else if(!strcmp(*argv, "update")) {
1249             if (argc > 1) {
1250                 do_update(usb, argv[1], erase_first);
1251                 skip(2);
1252             } else {
1253                 do_update(usb, "update.zip", erase_first);
1254                 skip(1);
1255             }
1256             wants_reboot = 1;
1257         } else if(!strcmp(*argv, "oem")) {
1258             argc = do_oem_command(argc, argv);
1259         } else if(!strcmp(*argv, "flashing")) {
1260             if (argc == 2 && (!strcmp(*(argv+1), "unlock") ||
1261                               !strcmp(*(argv+1), "lock") ||
1262                               !strcmp(*(argv+1), "unlock_critical") ||
1263                               !strcmp(*(argv+1), "lock_critical") ||
1264                               !strcmp(*(argv+1), "get_unlock_ability") ||
1265                               !strcmp(*(argv+1), "get_unlock_bootloader_nonce") ||
1266                               !strcmp(*(argv+1), "lock_bootloader"))) {
1267                 argc = do_oem_command(argc, argv);
1268             } else
1269             if (argc == 3 && !strcmp(*(argv+1), "unlock_bootloader")) {
1270                 argc = do_bypass_unlock_command(argc, argv);
1271             } else {
1272               usage();
1273               return 1;
1274             }
1275         } else {
1276             usage();
1277             return 1;
1278         }
1279     }
1280 
1281     if (wants_wipe) {
1282         fb_queue_erase("userdata");
1283         fb_perform_format(usb, "userdata", 1, NULL, NULL);
1284         fb_queue_erase("cache");
1285         fb_perform_format(usb, "cache", 1, NULL, NULL);
1286     }
1287     if (wants_reboot) {
1288         fb_queue_reboot();
1289         fb_queue_wait_for_disconnect();
1290     } else if (wants_reboot_bootloader) {
1291         fb_queue_command("reboot-bootloader", "rebooting into bootloader");
1292         fb_queue_wait_for_disconnect();
1293     }
1294 
1295     if (fb_queue_is_empty())
1296         return 0;
1297 
1298     status = fb_execute_queue(usb);
1299     return (status) ? 1 : 0;
1300 }
1301