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