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