fastboot.c revision 38412163da933664791cf511056953b9e3bd1454
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *  * Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 *  * Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in
12 *    the documentation and/or other materials provided with the
13 *    distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <stdio.h>
30#include <stdlib.h>
31#include <stdarg.h>
32#include <string.h>
33#include <errno.h>
34#include <fcntl.h>
35#include <unistd.h>
36#include <limits.h>
37#include <ctype.h>
38
39#include <sys/time.h>
40#include <bootimg.h>
41#include <zipfile/zipfile.h>
42
43#include "fastboot.h"
44
45char cur_product[FB_RESPONSE_SZ + 1];
46
47void bootimg_set_cmdline(boot_img_hdr *h, const char *cmdline);
48
49boot_img_hdr *mkbootimg(void *kernel, unsigned kernel_size,
50                        void *ramdisk, unsigned ramdisk_size,
51                        void *second, unsigned second_size,
52                        unsigned page_size, unsigned base,
53                        unsigned *bootimg_size);
54
55static usb_handle *usb = 0;
56static const char *serial = 0;
57static const char *product = 0;
58static const char *cmdline = 0;
59static int wipe_data = 0;
60static unsigned short vendor_id = 0;
61
62static unsigned base_addr = 0x10000000;
63
64void die(const char *fmt, ...)
65{
66    va_list ap;
67    va_start(ap, fmt);
68    fprintf(stderr,"error: ");
69    vfprintf(stderr, fmt, ap);
70    fprintf(stderr,"\n");
71    va_end(ap);
72    exit(1);
73}
74
75void get_my_path(char *path);
76
77char *find_item(const char *item, const char *product)
78{
79    char *dir;
80    char *fn;
81    char path[PATH_MAX + 128];
82
83    if(!strcmp(item,"boot")) {
84        fn = "boot.img";
85    } else if(!strcmp(item,"recovery")) {
86        fn = "recovery.img";
87    } else if(!strcmp(item,"system")) {
88        fn = "system.img";
89    } else if(!strcmp(item,"userdata")) {
90        fn = "userdata.img";
91    } else if(!strcmp(item,"cache")) {
92        fn = "cache.img";
93    } else if(!strcmp(item,"info")) {
94        fn = "android-info.txt";
95    } else {
96        fprintf(stderr,"unknown partition '%s'\n", item);
97        return 0;
98    }
99
100    if(product) {
101        get_my_path(path);
102        sprintf(path + strlen(path),
103                "../../../target/product/%s/%s", product, fn);
104        return strdup(path);
105    }
106
107    dir = getenv("ANDROID_PRODUCT_OUT");
108    if((dir == 0) || (dir[0] == 0)) {
109        die("neither -p product specified nor ANDROID_PRODUCT_OUT set");
110        return 0;
111    }
112
113    sprintf(path, "%s/%s", dir, fn);
114    return strdup(path);
115}
116
117#ifdef _WIN32
118void *load_file(const char *fn, unsigned *_sz);
119#else
120void *load_file(const char *fn, unsigned *_sz)
121{
122    char *data;
123    int sz;
124    int fd;
125
126    data = 0;
127    fd = open(fn, O_RDONLY);
128    if(fd < 0) return 0;
129
130    sz = lseek(fd, 0, SEEK_END);
131    if(sz < 0) goto oops;
132
133    if(lseek(fd, 0, SEEK_SET) != 0) goto oops;
134
135    data = (char*) malloc(sz);
136    if(data == 0) goto oops;
137
138    if(read(fd, data, sz) != sz) goto oops;
139    close(fd);
140
141    if(_sz) *_sz = sz;
142    return data;
143
144oops:
145    close(fd);
146    if(data != 0) free(data);
147    return 0;
148}
149#endif
150
151int match_fastboot(usb_ifc_info *info)
152{
153    if(!(vendor_id && (info->dev_vendor == vendor_id)) &&
154       (info->dev_vendor != 0x18d1) &&  // Google
155       (info->dev_vendor != 0x8087) &&  // Intel
156       (info->dev_vendor != 0x0451) &&
157       (info->dev_vendor != 0x0502) &&
158       (info->dev_vendor != 0x0fce) &&  // Sony Ericsson
159       (info->dev_vendor != 0x05c6) &&  // Qualcomm
160       (info->dev_vendor != 0x22b8) &&  // Motorola
161       (info->dev_vendor != 0x0955) &&  // Nvidia
162       (info->dev_vendor != 0x413c) &&  // DELL
163       (info->dev_vendor != 0x0bb4))    // HTC
164            return -1;
165    if(info->ifc_class != 0xff) return -1;
166    if(info->ifc_subclass != 0x42) return -1;
167    if(info->ifc_protocol != 0x03) return -1;
168    // require matching serial number if a serial number is specified
169    // at the command line with the -s option.
170    if (serial && strcmp(serial, info->serial_number) != 0) return -1;
171    return 0;
172}
173
174int list_devices_callback(usb_ifc_info *info)
175{
176    if (match_fastboot(info) == 0) {
177        char* serial = info->serial_number;
178        if (!info->writable) {
179            serial = "no permissions"; // like "adb devices"
180        }
181        if (!serial[0]) {
182            serial = "????????????";
183        }
184        // output compatible with "adb devices"
185        printf("%s\tfastboot\n", serial);
186    }
187
188    return -1;
189}
190
191usb_handle *open_device(void)
192{
193    static usb_handle *usb = 0;
194    int announce = 1;
195
196    if(usb) return usb;
197
198    for(;;) {
199        usb = usb_open(match_fastboot);
200        if(usb) return usb;
201        if(announce) {
202            announce = 0;
203            fprintf(stderr,"< waiting for device >\n");
204        }
205        sleep(1);
206    }
207}
208
209void list_devices(void) {
210    // We don't actually open a USB device here,
211    // just getting our callback called so we can
212    // list all the connected devices.
213    usb_open(list_devices_callback);
214}
215
216void usage(void)
217{
218    fprintf(stderr,
219/*           1234567890123456789012345678901234567890123456789012345678901234567890123456 */
220            "usage: fastboot [ <option> ] <command>\n"
221            "\n"
222            "commands:\n"
223            "  update <filename>                        reflash device from update.zip\n"
224            "  flashall                                 flash boot + recovery + system\n"
225            "  flash <partition> [ <filename> ]         write a file to a flash partition\n"
226            "  erase <partition>                        erase a flash partition\n"
227            "  getvar <variable>                        display a bootloader variable\n"
228            "  boot <kernel> [ <ramdisk> ]              download and boot kernel\n"
229            "  flash:raw boot <kernel> [ <ramdisk> ]    create bootimage and flash it\n"
230            "  devices                                  list all connected devices\n"
231            "  continue                                 continue with autoboot\n"
232            "  reboot                                   reboot device normally\n"
233            "  reboot-bootloader                        reboot device into bootloader\n"
234            "  help                                     show this help message\n"
235            "\n"
236            "options:\n"
237            "  -w                                       erase userdata and cache\n"
238            "  -s <serial number>                       specify device serial number\n"
239            "  -p <product>                             specify product name\n"
240            "  -c <cmdline>                             override kernel commandline\n"
241            "  -i <vendor id>                           specify a custom USB vendor id\n"
242            "  -b <base_addr>                           specify a custom kernel base address\n"
243            "  -n <page size>                           specify the nand page size. default: 2048\n"
244        );
245}
246
247void *load_bootable_image(unsigned page_size, const char *kernel, const char *ramdisk,
248                          unsigned *sz, const char *cmdline)
249{
250    void *kdata = 0, *rdata = 0;
251    unsigned ksize = 0, rsize = 0;
252    void *bdata;
253    unsigned bsize;
254
255    if(kernel == 0) {
256        fprintf(stderr, "no image specified\n");
257        return 0;
258    }
259
260    kdata = load_file(kernel, &ksize);
261    if(kdata == 0) {
262        fprintf(stderr, "cannot load '%s'\n", kernel);
263        return 0;
264    }
265
266        /* is this actually a boot image? */
267    if(!memcmp(kdata, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
268        if(cmdline) bootimg_set_cmdline((boot_img_hdr*) kdata, cmdline);
269
270        if(ramdisk) {
271            fprintf(stderr, "cannot boot a boot.img *and* ramdisk\n");
272            return 0;
273        }
274
275        *sz = ksize;
276        return kdata;
277    }
278
279    if(ramdisk) {
280        rdata = load_file(ramdisk, &rsize);
281        if(rdata == 0) {
282            fprintf(stderr,"cannot load '%s'\n", ramdisk);
283            return  0;
284        }
285    }
286
287    fprintf(stderr,"creating boot image...\n");
288    bdata = mkbootimg(kdata, ksize, rdata, rsize, 0, 0, page_size, base_addr, &bsize);
289    if(bdata == 0) {
290        fprintf(stderr,"failed to create boot.img\n");
291        return 0;
292    }
293    if(cmdline) bootimg_set_cmdline((boot_img_hdr*) bdata, cmdline);
294    fprintf(stderr,"creating boot image - %d bytes\n", bsize);
295    *sz = bsize;
296
297    return bdata;
298}
299
300void *unzip_file(zipfile_t zip, const char *name, unsigned *sz)
301{
302    void *data;
303    zipentry_t entry;
304    unsigned datasz;
305
306    entry = lookup_zipentry(zip, name);
307    if (entry == NULL) {
308        fprintf(stderr, "archive does not contain '%s'\n", name);
309        return 0;
310    }
311
312    *sz = get_zipentry_size(entry);
313
314    datasz = *sz * 1.001;
315    data = malloc(datasz);
316
317    if(data == 0) {
318        fprintf(stderr, "failed to allocate %d bytes\n", *sz);
319        return 0;
320    }
321
322    if (decompress_zipentry(entry, data, datasz)) {
323        fprintf(stderr, "failed to unzip '%s' from archive\n", name);
324        free(data);
325        return 0;
326    }
327
328    return data;
329}
330
331static char *strip(char *s)
332{
333    int n;
334    while(*s && isspace(*s)) s++;
335    n = strlen(s);
336    while(n-- > 0) {
337        if(!isspace(s[n])) break;
338        s[n] = 0;
339    }
340    return s;
341}
342
343#define MAX_OPTIONS 32
344static int setup_requirement_line(char *name)
345{
346    char *val[MAX_OPTIONS];
347    const char **out;
348    char *prod = NULL;
349    unsigned n, count;
350    char *x;
351    int invert = 0;
352
353    if (!strncmp(name, "reject ", 7)) {
354        name += 7;
355        invert = 1;
356    } else if (!strncmp(name, "require ", 8)) {
357        name += 8;
358        invert = 0;
359    } else if (!strncmp(name, "require-for-product:", 20)) {
360        // Get the product and point name past it
361        prod = name + 20;
362        name = strchr(name, ' ');
363        if (!name) return -1;
364        *name = 0;
365        name += 1;
366        invert = 0;
367    }
368
369    x = strchr(name, '=');
370    if (x == 0) return 0;
371    *x = 0;
372    val[0] = x + 1;
373
374    for(count = 1; count < MAX_OPTIONS; count++) {
375        x = strchr(val[count - 1],'|');
376        if (x == 0) break;
377        *x = 0;
378        val[count] = x + 1;
379    }
380
381    name = strip(name);
382    for(n = 0; n < count; n++) val[n] = strip(val[n]);
383
384    name = strip(name);
385    if (name == 0) return -1;
386
387        /* work around an unfortunate name mismatch */
388    if (!strcmp(name,"board")) name = "product";
389
390    out = malloc(sizeof(char*) * count);
391    if (out == 0) return -1;
392
393    for(n = 0; n < count; n++) {
394        out[n] = strdup(strip(val[n]));
395        if (out[n] == 0) return -1;
396    }
397
398    fb_queue_require(prod, name, invert, n, out);
399    return 0;
400}
401
402static void setup_requirements(char *data, unsigned sz)
403{
404    char *s;
405
406    s = data;
407    while (sz-- > 0) {
408        if(*s == '\n') {
409            *s++ = 0;
410            if (setup_requirement_line(data)) {
411                die("out of memory");
412            }
413            data = s;
414        } else {
415            s++;
416        }
417    }
418}
419
420void queue_info_dump(void)
421{
422    fb_queue_notice("--------------------------------------------");
423    fb_queue_display("version-bootloader", "Bootloader Version...");
424    fb_queue_display("version-baseband",   "Baseband Version.....");
425    fb_queue_display("serialno",           "Serial Number........");
426    fb_queue_notice("--------------------------------------------");
427}
428
429void do_update_signature(zipfile_t zip, char *fn)
430{
431    void *data;
432    unsigned sz;
433    data = unzip_file(zip, fn, &sz);
434    if (data == 0) return;
435    fb_queue_download("signature", data, sz);
436    fb_queue_command("signature", "installing signature");
437}
438
439void do_update(char *fn)
440{
441    void *zdata;
442    unsigned zsize;
443    void *data;
444    unsigned sz;
445    zipfile_t zip;
446
447    queue_info_dump();
448
449    fb_queue_query_save("product", cur_product, sizeof(cur_product));
450
451    zdata = load_file(fn, &zsize);
452    if (zdata == 0) die("failed to load '%s'", fn);
453
454    zip = init_zipfile(zdata, zsize);
455    if(zip == 0) die("failed to access zipdata in '%s'");
456
457    data = unzip_file(zip, "android-info.txt", &sz);
458    if (data == 0) {
459        char *tmp;
460            /* fallback for older zipfiles */
461        data = unzip_file(zip, "android-product.txt", &sz);
462        if ((data == 0) || (sz < 1)) {
463            die("update package has no android-info.txt or android-product.txt");
464        }
465        tmp = malloc(sz + 128);
466        if (tmp == 0) die("out of memory");
467        sprintf(tmp,"board=%sversion-baseband=0.66.04.19\n",(char*)data);
468        data = tmp;
469        sz = strlen(tmp);
470    }
471
472    setup_requirements(data, sz);
473
474    data = unzip_file(zip, "boot.img", &sz);
475    if (data == 0) die("update package missing boot.img");
476    do_update_signature(zip, "boot.sig");
477    fb_queue_flash("boot", data, sz);
478
479    data = unzip_file(zip, "recovery.img", &sz);
480    if (data != 0) {
481        do_update_signature(zip, "recovery.sig");
482        fb_queue_flash("recovery", data, sz);
483    }
484
485    data = unzip_file(zip, "system.img", &sz);
486    if (data == 0) die("update package missing system.img");
487    do_update_signature(zip, "system.sig");
488    fb_queue_flash("system", data, sz);
489}
490
491void do_send_signature(char *fn)
492{
493    void *data;
494    unsigned sz;
495    char *xtn;
496
497    xtn = strrchr(fn, '.');
498    if (!xtn) return;
499    if (strcmp(xtn, ".img")) return;
500
501    strcpy(xtn,".sig");
502    data = load_file(fn, &sz);
503    strcpy(xtn,".img");
504    if (data == 0) return;
505    fb_queue_download("signature", data, sz);
506    fb_queue_command("signature", "installing signature");
507}
508
509void do_flashall(void)
510{
511    char *fname;
512    void *data;
513    unsigned sz;
514
515    queue_info_dump();
516
517    fb_queue_query_save("product", cur_product, sizeof(cur_product));
518
519    fname = find_item("info", product);
520    if (fname == 0) die("cannot find android-info.txt");
521    data = load_file(fname, &sz);
522    if (data == 0) die("could not load android-info.txt");
523    setup_requirements(data, sz);
524
525    fname = find_item("boot", product);
526    data = load_file(fname, &sz);
527    if (data == 0) die("could not load boot.img");
528    do_send_signature(fname);
529    fb_queue_flash("boot", data, sz);
530
531    fname = find_item("recovery", product);
532    data = load_file(fname, &sz);
533    if (data != 0) {
534        do_send_signature(fname);
535        fb_queue_flash("recovery", data, sz);
536    }
537
538    fname = find_item("system", product);
539    data = load_file(fname, &sz);
540    if (data == 0) die("could not load system.img");
541    do_send_signature(fname);
542    fb_queue_flash("system", data, sz);
543}
544
545#define skip(n) do { argc -= (n); argv += (n); } while (0)
546#define require(n) do { if (argc < (n)) {usage(); exit(1);}} while (0)
547
548int do_oem_command(int argc, char **argv)
549{
550    int i;
551    char command[256];
552    if (argc <= 1) return 0;
553
554    command[0] = 0;
555    while(1) {
556        strcat(command,*argv);
557        skip(1);
558        if(argc == 0) break;
559        strcat(command," ");
560    }
561
562    fb_queue_command(command,"");
563    return 0;
564}
565
566int main(int argc, char **argv)
567{
568    int wants_wipe = 0;
569    int wants_reboot = 0;
570    int wants_reboot_bootloader = 0;
571    void *data;
572    unsigned sz;
573    unsigned page_size = 2048;
574    int status;
575
576    skip(1);
577    if (argc == 0) {
578        usage();
579        return 1;
580    }
581
582    if (!strcmp(*argv, "devices")) {
583        list_devices();
584        return 0;
585    }
586
587    if (!strcmp(*argv, "help")) {
588        usage();
589        return 0;
590    }
591
592
593    serial = getenv("ANDROID_SERIAL");
594
595    while (argc > 0) {
596        if(!strcmp(*argv, "-w")) {
597            wants_wipe = 1;
598            skip(1);
599        } else if(!strcmp(*argv, "-b")) {
600            require(2);
601            base_addr = strtoul(argv[1], 0, 16);
602            skip(2);
603        } else if(!strcmp(*argv, "-n")) {
604            require(2);
605            page_size = (unsigned)strtoul(argv[1], NULL, 0);
606            if (!page_size) die("invalid page size");
607            skip(2);
608        } else if(!strcmp(*argv, "-s")) {
609            require(2);
610            serial = argv[1];
611            skip(2);
612        } else if(!strcmp(*argv, "-p")) {
613            require(2);
614            product = argv[1];
615            skip(2);
616        } else if(!strcmp(*argv, "-c")) {
617            require(2);
618            cmdline = argv[1];
619            skip(2);
620        } else if(!strcmp(*argv, "-i")) {
621            char *endptr = NULL;
622            unsigned long val;
623
624            require(2);
625            val = strtoul(argv[1], &endptr, 0);
626            if (!endptr || *endptr != '\0' || (val & ~0xffff))
627                die("invalid vendor id '%s'", argv[1]);
628            vendor_id = (unsigned short)val;
629            skip(2);
630        } else if(!strcmp(*argv, "getvar")) {
631            require(2);
632            fb_queue_display(argv[1], argv[1]);
633            skip(2);
634        } else if(!strcmp(*argv, "erase")) {
635            require(2);
636            fb_queue_erase(argv[1]);
637            skip(2);
638        } else if(!strcmp(*argv, "signature")) {
639            require(2);
640            data = load_file(argv[1], &sz);
641            if (data == 0) die("could not load '%s'", argv[1]);
642            if (sz != 256) die("signature must be 256 bytes");
643            fb_queue_download("signature", data, sz);
644            fb_queue_command("signature", "installing signature");
645            skip(2);
646        } else if(!strcmp(*argv, "reboot")) {
647            wants_reboot = 1;
648            skip(1);
649        } else if(!strcmp(*argv, "reboot-bootloader")) {
650            wants_reboot_bootloader = 1;
651            skip(1);
652        } else if (!strcmp(*argv, "continue")) {
653            fb_queue_command("continue", "resuming boot");
654            skip(1);
655        } else if(!strcmp(*argv, "boot")) {
656            char *kname = 0;
657            char *rname = 0;
658            skip(1);
659            if (argc > 0) {
660                kname = argv[0];
661                skip(1);
662            }
663            if (argc > 0) {
664                rname = argv[0];
665                skip(1);
666            }
667            data = load_bootable_image(page_size, kname, rname, &sz, cmdline);
668            if (data == 0) return 1;
669            fb_queue_download("boot.img", data, sz);
670            fb_queue_command("boot", "booting");
671        } else if(!strcmp(*argv, "flash")) {
672            char *pname = argv[1];
673            char *fname = 0;
674            require(2);
675            if (argc > 2) {
676                fname = argv[2];
677                skip(3);
678            } else {
679                fname = find_item(pname, product);
680                skip(2);
681            }
682            if (fname == 0) die("cannot determine image filename for '%s'", pname);
683            data = load_file(fname, &sz);
684            if (data == 0) die("cannot load '%s'\n", fname);
685            fb_queue_flash(pname, data, sz);
686        } else if(!strcmp(*argv, "flash:raw")) {
687            char *pname = argv[1];
688            char *kname = argv[2];
689            char *rname = 0;
690            require(3);
691            if(argc > 3) {
692                rname = argv[3];
693                skip(4);
694            } else {
695                skip(3);
696            }
697            data = load_bootable_image(page_size, kname, rname, &sz, cmdline);
698            if (data == 0) die("cannot load bootable image");
699            fb_queue_flash(pname, data, sz);
700        } else if(!strcmp(*argv, "flashall")) {
701            skip(1);
702            do_flashall();
703            wants_reboot = 1;
704        } else if(!strcmp(*argv, "update")) {
705            if (argc > 1) {
706                do_update(argv[1]);
707                skip(2);
708            } else {
709                do_update("update.zip");
710                skip(1);
711            }
712            wants_reboot = 1;
713        } else if(!strcmp(*argv, "oem")) {
714            argc = do_oem_command(argc, argv);
715        } else {
716            usage();
717            return 1;
718        }
719    }
720
721    if (wants_wipe) {
722        fb_queue_erase("userdata");
723        fb_queue_erase("cache");
724    }
725    if (wants_reboot) {
726        fb_queue_reboot();
727    } else if (wants_reboot_bootloader) {
728        fb_queue_command("reboot-bootloader", "rebooting into bootloader");
729    }
730
731    usb = open_device();
732
733    status = fb_execute_queue(usb);
734    return (status) ? 1 : 0;
735}
736