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
60char cur_product[FB_RESPONSE_SZ + 1];
61
62static const char *serial = 0;
63static const char *product = 0;
64static const char *cmdline = 0;
65static unsigned short vendor_id = 0;
66static int long_listing = 0;
67static int64_t sparse_limit = -1;
68static int64_t target_sparse_limit = -1;
69
70unsigned page_size = 2048;
71unsigned base_addr      = 0x10000000;
72unsigned kernel_offset  = 0x00008000;
73unsigned ramdisk_offset = 0x01000000;
74unsigned second_offset  = 0x00f00000;
75unsigned tags_offset    = 0x00000100;
76
77enum fb_buffer_type {
78    FB_BUFFER,
79    FB_BUFFER_SPARSE,
80};
81
82struct fastboot_buffer {
83    enum fb_buffer_type type;
84    void *data;
85    unsigned int sz;
86};
87
88static 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
100char *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
142static 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
152static 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
174oops:
175    errno_tmp = errno;
176    close(fd);
177    if(data != 0) free(data);
178    errno = errno_tmp;
179    return 0;
180}
181
182static 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
192int 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
218int match_fastboot(usb_ifc_info *info)
219{
220    return match_fastboot_with_serial(info, serial);
221}
222
223int 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
246usb_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
264void 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
271void 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"
283            "                                           partitions\n"
284            "  flashing unlock                          unlocks the device. Allows user to"
285            "                                           flash any partition except the ones"
286            "                                           that are related to bootloader\n"
287            "  flashing lock_critical                   Prevents flashing bootloader related"
288            "                                           partitions\n"
289            "  flashing unlock_critical                 Enables flashing bootloader related"
290            "                                           partitions\n"
291            "  flashing get_unlock_ability              Queries bootloader to see if the"
292            "                                           device is unlocked\n"
293            "  erase <partition>                        erase a flash partition\n"
294            "  format[:[<fs type>][:[<size>]] <partition> format a flash partition.\n"
295            "                                           Can override the fs type and/or\n"
296            "                                           size the bootloader reports.\n"
297            "  getvar <variable>                        display a bootloader variable\n"
298            "  boot <kernel> [ <ramdisk> ]              download and boot kernel\n"
299            "  flash:raw boot <kernel> [ <ramdisk> ]    create bootimage and flash it\n"
300            "  devices                                  list all connected devices\n"
301            "  continue                                 continue with autoboot\n"
302            "  reboot [bootloader]                      reboot device, optionally into bootloader\n"
303            "  reboot-bootloader                        reboot device into bootloader\n"
304            "  help                                     show this help message\n"
305            "\n"
306            "options:\n"
307            "  -w                                       erase userdata and cache (and format\n"
308            "                                           if supported by partition type)\n"
309            "  -u                                       do not first erase partition before\n"
310            "                                           formatting\n"
311            "  -s <specific device>                     specify device serial number\n"
312            "                                           or path to device port\n"
313            "  -l                                       with \"devices\", lists device paths\n"
314            "  -p <product>                             specify product name\n"
315            "  -c <cmdline>                             override kernel commandline\n"
316            "  -i <vendor id>                           specify a custom USB vendor id\n"
317            "  -b <base_addr>                           specify a custom kernel base address.\n"
318            "                                           default: 0x10000000\n"
319            "  -n <page size>                           specify the nand page size.\n"
320            "                                           default: 2048\n"
321            "  -S <size>[K|M|G]                         automatically sparse files greater\n"
322            "                                           than size.  0 to disable\n"
323        );
324}
325
326void *load_bootable_image(const char *kernel, const char *ramdisk,
327                          unsigned *sz, const char *cmdline)
328{
329    void *kdata = 0, *rdata = 0;
330    unsigned ksize = 0, rsize = 0;
331    void *bdata;
332    unsigned bsize;
333
334    if(kernel == 0) {
335        fprintf(stderr, "no image specified\n");
336        return 0;
337    }
338
339    kdata = load_file(kernel, &ksize);
340    if(kdata == 0) {
341        fprintf(stderr, "cannot load '%s': %s\n", kernel, strerror(errno));
342        return 0;
343    }
344
345        /* is this actually a boot image? */
346    if(!memcmp(kdata, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
347        if(cmdline) bootimg_set_cmdline((boot_img_hdr*) kdata, cmdline);
348
349        if(ramdisk) {
350            fprintf(stderr, "cannot boot a boot.img *and* ramdisk\n");
351            return 0;
352        }
353
354        *sz = ksize;
355        return kdata;
356    }
357
358    if(ramdisk) {
359        rdata = load_file(ramdisk, &rsize);
360        if(rdata == 0) {
361            fprintf(stderr,"cannot load '%s': %s\n", ramdisk, strerror(errno));
362            return  0;
363        }
364    }
365
366    fprintf(stderr,"creating boot image...\n");
367    bdata = mkbootimg(kdata, ksize, kernel_offset,
368                      rdata, rsize, ramdisk_offset,
369                      0, 0, second_offset,
370                      page_size, base_addr, tags_offset, &bsize);
371    if(bdata == 0) {
372        fprintf(stderr,"failed to create boot.img\n");
373        return 0;
374    }
375    if(cmdline) bootimg_set_cmdline((boot_img_hdr*) bdata, cmdline);
376    fprintf(stderr,"creating boot image - %d bytes\n", bsize);
377    *sz = bsize;
378
379    return bdata;
380}
381
382static void* unzip_file(ZipArchiveHandle zip, const char* entry_name, unsigned* sz)
383{
384    ZipEntryName zip_entry_name(entry_name);
385    ZipEntry zip_entry;
386    if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
387        fprintf(stderr, "archive does not contain '%s'\n", entry_name);
388        return 0;
389    }
390
391    *sz = zip_entry.uncompressed_length;
392
393    uint8_t* data = reinterpret_cast<uint8_t*>(malloc(zip_entry.uncompressed_length));
394    if (data == NULL) {
395        fprintf(stderr, "failed to allocate %u bytes for '%s'\n", *sz, entry_name);
396        return 0;
397    }
398
399    int error = ExtractToMemory(zip, &zip_entry, data, zip_entry.uncompressed_length);
400    if (error != 0) {
401        fprintf(stderr, "failed to extract '%s': %s\n", entry_name, ErrorCodeString(error));
402        free(data);
403        return 0;
404    }
405
406    return data;
407}
408
409#if defined(_WIN32)
410
411// TODO: move this to somewhere it can be shared.
412
413#include <windows.h>
414
415// Windows' tmpfile(3) requires administrator rights because
416// it creates temporary files in the root directory.
417static FILE* win32_tmpfile() {
418    char temp_path[PATH_MAX];
419    DWORD nchars = GetTempPath(sizeof(temp_path), temp_path);
420    if (nchars == 0 || nchars >= sizeof(temp_path)) {
421        fprintf(stderr, "GetTempPath failed, error %ld\n", GetLastError());
422        return nullptr;
423    }
424
425    char filename[PATH_MAX];
426    if (GetTempFileName(temp_path, "fastboot", 0, filename) == 0) {
427        fprintf(stderr, "GetTempFileName failed, error %ld\n", GetLastError());
428        return nullptr;
429    }
430
431    return fopen(filename, "w+bTD");
432}
433
434#define tmpfile win32_tmpfile
435
436#endif
437
438static int unzip_to_file(ZipArchiveHandle zip, char* entry_name) {
439    FILE* fp = tmpfile();
440    if (fp == NULL) {
441        fprintf(stderr, "failed to create temporary file for '%s': %s\n",
442                entry_name, strerror(errno));
443        return -1;
444    }
445
446    ZipEntryName zip_entry_name(entry_name);
447    ZipEntry zip_entry;
448    if (FindEntry(zip, zip_entry_name, &zip_entry) != 0) {
449        fprintf(stderr, "archive does not contain '%s'\n", entry_name);
450        return -1;
451    }
452
453    int fd = fileno(fp);
454    int error = ExtractEntryToFile(zip, &zip_entry, fd);
455    if (error != 0) {
456        fprintf(stderr, "failed to extract '%s': %s\n", entry_name, ErrorCodeString(error));
457        return -1;
458    }
459
460    lseek(fd, 0, SEEK_SET);
461    return fd;
462}
463
464static char *strip(char *s)
465{
466    int n;
467    while(*s && isspace(*s)) s++;
468    n = strlen(s);
469    while(n-- > 0) {
470        if(!isspace(s[n])) break;
471        s[n] = 0;
472    }
473    return s;
474}
475
476#define MAX_OPTIONS 32
477static int setup_requirement_line(char *name)
478{
479    char *val[MAX_OPTIONS];
480    char *prod = NULL;
481    unsigned n, count;
482    char *x;
483    int invert = 0;
484
485    if (!strncmp(name, "reject ", 7)) {
486        name += 7;
487        invert = 1;
488    } else if (!strncmp(name, "require ", 8)) {
489        name += 8;
490        invert = 0;
491    } else if (!strncmp(name, "require-for-product:", 20)) {
492        // Get the product and point name past it
493        prod = name + 20;
494        name = strchr(name, ' ');
495        if (!name) return -1;
496        *name = 0;
497        name += 1;
498        invert = 0;
499    }
500
501    x = strchr(name, '=');
502    if (x == 0) return 0;
503    *x = 0;
504    val[0] = x + 1;
505
506    for(count = 1; count < MAX_OPTIONS; count++) {
507        x = strchr(val[count - 1],'|');
508        if (x == 0) break;
509        *x = 0;
510        val[count] = x + 1;
511    }
512
513    name = strip(name);
514    for(n = 0; n < count; n++) val[n] = strip(val[n]);
515
516    name = strip(name);
517    if (name == 0) return -1;
518
519    const char* var = name;
520    // Work around an unfortunate name mismatch.
521    if (!strcmp(name,"board")) var = "product";
522
523    const char** out = reinterpret_cast<const char**>(malloc(sizeof(char*) * count));
524    if (out == 0) return -1;
525
526    for(n = 0; n < count; n++) {
527        out[n] = strdup(strip(val[n]));
528        if (out[n] == 0) {
529            for(size_t i = 0; i < n; ++i) {
530                free((char*) out[i]);
531            }
532            free(out);
533            return -1;
534        }
535    }
536
537    fb_queue_require(prod, var, invert, n, out);
538    return 0;
539}
540
541static void setup_requirements(char *data, unsigned sz)
542{
543    char *s;
544
545    s = data;
546    while (sz-- > 0) {
547        if(*s == '\n') {
548            *s++ = 0;
549            if (setup_requirement_line(data)) {
550                die("out of memory");
551            }
552            data = s;
553        } else {
554            s++;
555        }
556    }
557}
558
559void queue_info_dump(void)
560{
561    fb_queue_notice("--------------------------------------------");
562    fb_queue_display("version-bootloader", "Bootloader Version...");
563    fb_queue_display("version-baseband",   "Baseband Version.....");
564    fb_queue_display("serialno",           "Serial Number........");
565    fb_queue_notice("--------------------------------------------");
566}
567
568static struct sparse_file **load_sparse_files(int fd, int max_size)
569{
570    struct sparse_file* s = sparse_file_import_auto(fd, false, true);
571    if (!s) {
572        die("cannot sparse read file\n");
573    }
574
575    int files = sparse_file_resparse(s, max_size, NULL, 0);
576    if (files < 0) {
577        die("Failed to resparse\n");
578    }
579
580    sparse_file** out_s = reinterpret_cast<sparse_file**>(calloc(sizeof(struct sparse_file *), files + 1));
581    if (!out_s) {
582        die("Failed to allocate sparse file array\n");
583    }
584
585    files = sparse_file_resparse(s, max_size, out_s, files);
586    if (files < 0) {
587        die("Failed to resparse\n");
588    }
589
590    return out_s;
591}
592
593static int64_t get_target_sparse_limit(struct usb_handle *usb)
594{
595    int64_t limit = 0;
596    char response[FB_RESPONSE_SZ + 1];
597    int status = fb_getvar(usb, response, "max-download-size");
598
599    if (!status) {
600        limit = strtoul(response, NULL, 0);
601        if (limit > 0) {
602            fprintf(stderr, "target reported max download size of %" PRId64 " bytes\n",
603                    limit);
604        }
605    }
606
607    return limit;
608}
609
610static int64_t get_sparse_limit(struct usb_handle *usb, int64_t size)
611{
612    int64_t limit;
613
614    if (sparse_limit == 0) {
615        return 0;
616    } else if (sparse_limit > 0) {
617        limit = sparse_limit;
618    } else {
619        if (target_sparse_limit == -1) {
620            target_sparse_limit = get_target_sparse_limit(usb);
621        }
622        if (target_sparse_limit > 0) {
623            limit = target_sparse_limit;
624        } else {
625            return 0;
626        }
627    }
628
629    if (size > limit) {
630        return limit;
631    }
632
633    return 0;
634}
635
636/* Until we get lazy inode table init working in make_ext4fs, we need to
637 * erase partitions of type ext4 before flashing a filesystem so no stale
638 * inodes are left lying around.  Otherwise, e2fsck gets very upset.
639 */
640static int needs_erase(usb_handle* usb, const char *part)
641{
642    /* The function fb_format_supported() currently returns the value
643     * we want, so just call it.
644     */
645     return fb_format_supported(usb, part, NULL);
646}
647
648static int load_buf_fd(usb_handle *usb, int fd,
649        struct fastboot_buffer *buf)
650{
651    int64_t sz64;
652    void *data;
653    int64_t limit;
654
655
656    sz64 = file_size(fd);
657    if (sz64 < 0) {
658        return -1;
659    }
660
661    lseek(fd, 0, SEEK_SET);
662    limit = get_sparse_limit(usb, sz64);
663    if (limit) {
664        struct sparse_file **s = load_sparse_files(fd, limit);
665        if (s == NULL) {
666            return -1;
667        }
668        buf->type = FB_BUFFER_SPARSE;
669        buf->data = s;
670    } else {
671        unsigned int sz;
672        data = load_fd(fd, &sz);
673        if (data == 0) return -1;
674        buf->type = FB_BUFFER;
675        buf->data = data;
676        buf->sz = sz;
677    }
678
679    return 0;
680}
681
682static int load_buf(usb_handle *usb, const char *fname,
683        struct fastboot_buffer *buf)
684{
685    int fd;
686
687    fd = open(fname, O_RDONLY | O_BINARY);
688    if (fd < 0) {
689        return -1;
690    }
691
692    return load_buf_fd(usb, fd, buf);
693}
694
695static void flash_buf(const char *pname, struct fastboot_buffer *buf)
696{
697    sparse_file** s;
698
699    switch (buf->type) {
700        case FB_BUFFER_SPARSE:
701            s = reinterpret_cast<sparse_file**>(buf->data);
702            while (*s) {
703                int64_t sz64 = sparse_file_len(*s, true, false);
704                fb_queue_flash_sparse(pname, *s++, sz64);
705            }
706            break;
707        case FB_BUFFER:
708            fb_queue_flash(pname, buf->data, buf->sz);
709            break;
710        default:
711            die("unknown buffer type: %d", buf->type);
712    }
713}
714
715void do_flash(usb_handle *usb, const char *pname, const char *fname)
716{
717    struct fastboot_buffer buf;
718
719    if (load_buf(usb, fname, &buf)) {
720        die("cannot load '%s'", fname);
721    }
722    flash_buf(pname, &buf);
723}
724
725void do_update_signature(ZipArchiveHandle zip, char *fn)
726{
727    unsigned sz;
728    void* data = unzip_file(zip, fn, &sz);
729    if (data == 0) return;
730    fb_queue_download("signature", data, sz);
731    fb_queue_command("signature", "installing signature");
732}
733
734void do_update(usb_handle *usb, const char *filename, int erase_first)
735{
736    queue_info_dump();
737
738    fb_queue_query_save("product", cur_product, sizeof(cur_product));
739
740    ZipArchiveHandle zip;
741    int error = OpenArchive(filename, &zip);
742    if (error != 0) {
743        CloseArchive(zip);
744        die("failed to open zip file '%s': %s", filename, ErrorCodeString(error));
745    }
746
747    unsigned sz;
748    void* data = unzip_file(zip, "android-info.txt", &sz);
749    if (data == 0) {
750        CloseArchive(zip);
751        die("update package '%s' has no android-info.txt", filename);
752    }
753
754    setup_requirements(reinterpret_cast<char*>(data), sz);
755
756    for (size_t i = 0; i < ARRAY_SIZE(images); ++i) {
757        int fd = unzip_to_file(zip, images[i].img_name);
758        if (fd == -1) {
759            if (images[i].is_optional) {
760                continue;
761            }
762            CloseArchive(zip);
763            exit(1); // unzip_to_file already explained why.
764        }
765        fastboot_buffer buf;
766        int rc = load_buf_fd(usb, fd, &buf);
767        if (rc) die("cannot load %s from flash", images[i].img_name);
768        do_update_signature(zip, images[i].sig_name);
769        if (erase_first && needs_erase(usb, images[i].part_name)) {
770            fb_queue_erase(images[i].part_name);
771        }
772        flash_buf(images[i].part_name, &buf);
773        /* not closing the fd here since the sparse code keeps the fd around
774         * but hasn't mmaped data yet. The tmpfile will get cleaned up when the
775         * program exits.
776         */
777    }
778
779    CloseArchive(zip);
780}
781
782void do_send_signature(char *fn)
783{
784    void *data;
785    unsigned sz;
786    char *xtn;
787
788    xtn = strrchr(fn, '.');
789    if (!xtn) return;
790    if (strcmp(xtn, ".img")) return;
791
792    strcpy(xtn,".sig");
793    data = load_file(fn, &sz);
794    strcpy(xtn,".img");
795    if (data == 0) return;
796    fb_queue_download("signature", data, sz);
797    fb_queue_command("signature", "installing signature");
798}
799
800void do_flashall(usb_handle *usb, int erase_first)
801{
802    queue_info_dump();
803
804    fb_queue_query_save("product", cur_product, sizeof(cur_product));
805
806    char* fname = find_item("info", product);
807    if (fname == 0) die("cannot find android-info.txt");
808
809    unsigned sz;
810    void* data = load_file(fname, &sz);
811    if (data == 0) die("could not load android-info.txt: %s", strerror(errno));
812
813    setup_requirements(reinterpret_cast<char*>(data), sz);
814
815    for (size_t i = 0; i < ARRAY_SIZE(images); i++) {
816        fname = find_item(images[i].part_name, product);
817        fastboot_buffer buf;
818        if (load_buf(usb, fname, &buf)) {
819            if (images[i].is_optional)
820                continue;
821            die("could not load %s\n", images[i].img_name);
822        }
823        do_send_signature(fname);
824        if (erase_first && needs_erase(usb, images[i].part_name)) {
825            fb_queue_erase(images[i].part_name);
826        }
827        flash_buf(images[i].part_name, &buf);
828    }
829}
830
831#define skip(n) do { argc -= (n); argv += (n); } while (0)
832#define require(n) do { if (argc < (n)) {usage(); exit(1);}} while (0)
833
834int do_oem_command(int argc, char **argv)
835{
836    char command[256];
837    if (argc <= 1) return 0;
838
839    command[0] = 0;
840    while(1) {
841        strcat(command,*argv);
842        skip(1);
843        if(argc == 0) break;
844        strcat(command," ");
845    }
846
847    fb_queue_command(command,"");
848    return 0;
849}
850
851static int64_t parse_num(const char *arg)
852{
853    char *endptr;
854    unsigned long long num;
855
856    num = strtoull(arg, &endptr, 0);
857    if (endptr == arg) {
858        return -1;
859    }
860
861    if (*endptr == 'k' || *endptr == 'K') {
862        if (num >= (-1ULL) / 1024) {
863            return -1;
864        }
865        num *= 1024LL;
866        endptr++;
867    } else if (*endptr == 'm' || *endptr == 'M') {
868        if (num >= (-1ULL) / (1024 * 1024)) {
869            return -1;
870        }
871        num *= 1024LL * 1024LL;
872        endptr++;
873    } else if (*endptr == 'g' || *endptr == 'G') {
874        if (num >= (-1ULL) / (1024 * 1024 * 1024)) {
875            return -1;
876        }
877        num *= 1024LL * 1024LL * 1024LL;
878        endptr++;
879    }
880
881    if (*endptr != '\0') {
882        return -1;
883    }
884
885    if (num > INT64_MAX) {
886        return -1;
887    }
888
889    return num;
890}
891
892void fb_perform_format(usb_handle* usb,
893                       const char *partition, int skip_if_not_supported,
894                       const char *type_override, const char *size_override)
895{
896    char pTypeBuff[FB_RESPONSE_SZ + 1], pSizeBuff[FB_RESPONSE_SZ + 1];
897    char *pType = pTypeBuff;
898    char *pSize = pSizeBuff;
899    unsigned int limit = INT_MAX;
900    struct fastboot_buffer buf;
901    const char *errMsg = NULL;
902    const struct fs_generator *gen;
903    uint64_t pSz;
904    int status;
905    int fd;
906
907    if (target_sparse_limit > 0 && target_sparse_limit < limit)
908        limit = target_sparse_limit;
909    if (sparse_limit > 0 && sparse_limit < limit)
910        limit = sparse_limit;
911
912    status = fb_getvar(usb, pType, "partition-type:%s", partition);
913    if (status) {
914        errMsg = "Can't determine partition type.\n";
915        goto failed;
916    }
917    if (type_override) {
918        if (strcmp(type_override, pType)) {
919            fprintf(stderr,
920                    "Warning: %s type is %s, but %s was requested for formating.\n",
921                    partition, pType, type_override);
922        }
923        pType = (char *)type_override;
924    }
925
926    status = fb_getvar(usb, pSize, "partition-size:%s", partition);
927    if (status) {
928        errMsg = "Unable to get partition size\n";
929        goto failed;
930    }
931    if (size_override) {
932        if (strcmp(size_override, pSize)) {
933            fprintf(stderr,
934                    "Warning: %s size is %s, but %s was requested for formating.\n",
935                    partition, pSize, size_override);
936        }
937        pSize = (char *)size_override;
938    }
939
940    gen = fs_get_generator(pType);
941    if (!gen) {
942        if (skip_if_not_supported) {
943            fprintf(stderr, "Erase successful, but not automatically formatting.\n");
944            fprintf(stderr, "File system type %s not supported.\n", pType);
945            return;
946        }
947        fprintf(stderr, "Formatting is not supported for filesystem with type '%s'.\n", pType);
948        return;
949    }
950
951    pSz = strtoll(pSize, (char **)NULL, 16);
952
953    fd = fileno(tmpfile());
954    if (fs_generator_generate(gen, fd, pSz)) {
955        close(fd);
956        fprintf(stderr, "Cannot generate image.\n");
957        return;
958    }
959
960    if (load_buf_fd(usb, fd, &buf)) {
961        fprintf(stderr, "Cannot read image.\n");
962        close(fd);
963        return;
964    }
965    flash_buf(partition, &buf);
966
967    return;
968
969
970failed:
971    if (skip_if_not_supported) {
972        fprintf(stderr, "Erase successful, but not automatically formatting.\n");
973        if (errMsg)
974            fprintf(stderr, "%s", errMsg);
975    }
976    fprintf(stderr,"FAILED (%s)\n", fb_get_error());
977}
978
979int main(int argc, char **argv)
980{
981    int wants_wipe = 0;
982    int wants_reboot = 0;
983    int wants_reboot_bootloader = 0;
984    int erase_first = 1;
985    void *data;
986    unsigned sz;
987    int status;
988    int c;
989    int longindex;
990
991    const struct option longopts[] = {
992        {"base", required_argument, 0, 'b'},
993        {"kernel_offset", required_argument, 0, 'k'},
994        {"page_size", required_argument, 0, 'n'},
995        {"ramdisk_offset", required_argument, 0, 'r'},
996        {"tags_offset", required_argument, 0, 't'},
997        {"help", no_argument, 0, 'h'},
998        {"unbuffered", no_argument, 0, 0},
999        {"version", no_argument, 0, 0},
1000        {0, 0, 0, 0}
1001    };
1002
1003    serial = getenv("ANDROID_SERIAL");
1004
1005    while (1) {
1006        c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lp:c:i:m:h", longopts, &longindex);
1007        if (c < 0) {
1008            break;
1009        }
1010        /* Alphabetical cases */
1011        switch (c) {
1012        case 'b':
1013            base_addr = strtoul(optarg, 0, 16);
1014            break;
1015        case 'c':
1016            cmdline = optarg;
1017            break;
1018        case 'h':
1019            usage();
1020            return 1;
1021        case 'i': {
1022                char *endptr = NULL;
1023                unsigned long val;
1024
1025                val = strtoul(optarg, &endptr, 0);
1026                if (!endptr || *endptr != '\0' || (val & ~0xffff))
1027                    die("invalid vendor id '%s'", optarg);
1028                vendor_id = (unsigned short)val;
1029                break;
1030            }
1031        case 'k':
1032            kernel_offset = strtoul(optarg, 0, 16);
1033            break;
1034        case 'l':
1035            long_listing = 1;
1036            break;
1037        case 'n':
1038            page_size = (unsigned)strtoul(optarg, NULL, 0);
1039            if (!page_size) die("invalid page size");
1040            break;
1041        case 'p':
1042            product = optarg;
1043            break;
1044        case 'r':
1045            ramdisk_offset = strtoul(optarg, 0, 16);
1046            break;
1047        case 't':
1048            tags_offset = strtoul(optarg, 0, 16);
1049            break;
1050        case 's':
1051            serial = optarg;
1052            break;
1053        case 'S':
1054            sparse_limit = parse_num(optarg);
1055            if (sparse_limit < 0) {
1056                    die("invalid sparse limit");
1057            }
1058            break;
1059        case 'u':
1060            erase_first = 0;
1061            break;
1062        case 'w':
1063            wants_wipe = 1;
1064            break;
1065        case '?':
1066            return 1;
1067        case 0:
1068            if (strcmp("unbuffered", longopts[longindex].name) == 0) {
1069                setvbuf(stdout, NULL, _IONBF, 0);
1070                setvbuf(stderr, NULL, _IONBF, 0);
1071            } else if (strcmp("version", longopts[longindex].name) == 0) {
1072                fprintf(stdout, "fastboot version %s\n", FASTBOOT_REVISION);
1073                return 0;
1074            }
1075            break;
1076        default:
1077            abort();
1078        }
1079    }
1080
1081    argc -= optind;
1082    argv += optind;
1083
1084    if (argc == 0 && !wants_wipe) {
1085        usage();
1086        return 1;
1087    }
1088
1089    if (argc > 0 && !strcmp(*argv, "devices")) {
1090        skip(1);
1091        list_devices();
1092        return 0;
1093    }
1094
1095    if (argc > 0 && !strcmp(*argv, "help")) {
1096        usage();
1097        return 0;
1098    }
1099
1100    usb_handle* usb = open_device();
1101
1102    while (argc > 0) {
1103        if(!strcmp(*argv, "getvar")) {
1104            require(2);
1105            fb_queue_display(argv[1], argv[1]);
1106            skip(2);
1107        } else if(!strcmp(*argv, "erase")) {
1108            require(2);
1109
1110            if (fb_format_supported(usb, argv[1], NULL)) {
1111                fprintf(stderr, "******** Did you mean to fastboot format this partition?\n");
1112            }
1113
1114            fb_queue_erase(argv[1]);
1115            skip(2);
1116        } else if(!strncmp(*argv, "format", strlen("format"))) {
1117            char *overrides;
1118            char *type_override = NULL;
1119            char *size_override = NULL;
1120            require(2);
1121            /*
1122             * Parsing for: "format[:[type][:[size]]]"
1123             * Some valid things:
1124             *  - select ontly the size, and leave default fs type:
1125             *    format::0x4000000 userdata
1126             *  - default fs type and size:
1127             *    format userdata
1128             *    format:: userdata
1129             */
1130            overrides = strchr(*argv, ':');
1131            if (overrides) {
1132                overrides++;
1133                size_override = strchr(overrides, ':');
1134                if (size_override) {
1135                    size_override[0] = '\0';
1136                    size_override++;
1137                }
1138                type_override = overrides;
1139            }
1140            if (type_override && !type_override[0]) type_override = NULL;
1141            if (size_override && !size_override[0]) size_override = NULL;
1142            if (erase_first && needs_erase(usb, argv[1])) {
1143                fb_queue_erase(argv[1]);
1144            }
1145            fb_perform_format(usb, argv[1], 0, type_override, size_override);
1146            skip(2);
1147        } else if(!strcmp(*argv, "signature")) {
1148            require(2);
1149            data = load_file(argv[1], &sz);
1150            if (data == 0) die("could not load '%s': %s", argv[1], strerror(errno));
1151            if (sz != 256) die("signature must be 256 bytes");
1152            fb_queue_download("signature", data, sz);
1153            fb_queue_command("signature", "installing signature");
1154            skip(2);
1155        } else if(!strcmp(*argv, "reboot")) {
1156            wants_reboot = 1;
1157            skip(1);
1158            if (argc > 0) {
1159                if (!strcmp(*argv, "bootloader")) {
1160                    wants_reboot = 0;
1161                    wants_reboot_bootloader = 1;
1162                    skip(1);
1163                }
1164            }
1165            require(0);
1166        } else if(!strcmp(*argv, "reboot-bootloader")) {
1167            wants_reboot_bootloader = 1;
1168            skip(1);
1169        } else if (!strcmp(*argv, "continue")) {
1170            fb_queue_command("continue", "resuming boot");
1171            skip(1);
1172        } else if(!strcmp(*argv, "boot")) {
1173            char *kname = 0;
1174            char *rname = 0;
1175            skip(1);
1176            if (argc > 0) {
1177                kname = argv[0];
1178                skip(1);
1179            }
1180            if (argc > 0) {
1181                rname = argv[0];
1182                skip(1);
1183            }
1184            data = load_bootable_image(kname, rname, &sz, cmdline);
1185            if (data == 0) return 1;
1186            fb_queue_download("boot.img", data, sz);
1187            fb_queue_command("boot", "booting");
1188        } else if(!strcmp(*argv, "flash")) {
1189            char *pname = argv[1];
1190            char *fname = 0;
1191            require(2);
1192            if (argc > 2) {
1193                fname = argv[2];
1194                skip(3);
1195            } else {
1196                fname = find_item(pname, product);
1197                skip(2);
1198            }
1199            if (fname == 0) die("cannot determine image filename for '%s'", pname);
1200            if (erase_first && needs_erase(usb, pname)) {
1201                fb_queue_erase(pname);
1202            }
1203            do_flash(usb, pname, fname);
1204        } else if(!strcmp(*argv, "flash:raw")) {
1205            char *pname = argv[1];
1206            char *kname = argv[2];
1207            char *rname = 0;
1208            require(3);
1209            if(argc > 3) {
1210                rname = argv[3];
1211                skip(4);
1212            } else {
1213                skip(3);
1214            }
1215            data = load_bootable_image(kname, rname, &sz, cmdline);
1216            if (data == 0) die("cannot load bootable image");
1217            fb_queue_flash(pname, data, sz);
1218        } else if(!strcmp(*argv, "flashall")) {
1219            skip(1);
1220            do_flashall(usb, erase_first);
1221            wants_reboot = 1;
1222        } else if(!strcmp(*argv, "update")) {
1223            if (argc > 1) {
1224                do_update(usb, argv[1], erase_first);
1225                skip(2);
1226            } else {
1227                do_update(usb, "update.zip", erase_first);
1228                skip(1);
1229            }
1230            wants_reboot = 1;
1231        } else if(!strcmp(*argv, "oem")) {
1232            argc = do_oem_command(argc, argv);
1233        } else if(!strcmp(*argv, "flashing") && argc == 2) {
1234            if(!strcmp(*(argv+1), "unlock") || !strcmp(*(argv+1), "lock")
1235               || !strcmp(*(argv+1), "unlock_critical")
1236               || !strcmp(*(argv+1), "lock_critical")
1237               || !strcmp(*(argv+1), "get_unlock_ability")) {
1238              argc = do_oem_command(argc, argv);
1239            } else {
1240              usage();
1241              return 1;
1242            }
1243        } else {
1244            usage();
1245            return 1;
1246        }
1247    }
1248
1249    if (wants_wipe) {
1250        fb_queue_erase("userdata");
1251        fb_perform_format(usb, "userdata", 1, NULL, NULL);
1252        fb_queue_erase("cache");
1253        fb_perform_format(usb, "cache", 1, NULL, NULL);
1254    }
1255    if (wants_reboot) {
1256        fb_queue_reboot();
1257        fb_queue_wait_for_disconnect();
1258    } else if (wants_reboot_bootloader) {
1259        fb_queue_command("reboot-bootloader", "rebooting into bootloader");
1260        fb_queue_wait_for_disconnect();
1261    }
1262
1263    if (fb_queue_is_empty())
1264        return 0;
1265
1266    status = fb_execute_queue(usb);
1267    return (status) ? 1 : 0;
1268}
1269