fastboot.c revision ee52055ae5eeb951bb4805bd8aa57d63718e1ce7
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            "  continue                                 continue with autoboot\n"
227            "  reboot                                   reboot device normally\n"
228            "  reboot-bootloader                        reboot device into bootloader\n"
229            "  help                                     show this help message\n"
230            "\n"
231            "options:\n"
232            "  -w                                       erase userdata and cache\n"
233            "  -s <serial number>                       specify device serial number\n"
234            "  -p <product>                             specify product name\n"
235            "  -c <cmdline>                             override kernel commandline\n"
236            "  -i <vendor id>                           specify a custom USB vendor id\n"
237            "  -b <base_addr>                           specify a custom kernel base address\n"
238            "  -n <page size>                           specify the nand page size. default: 2048\n"
239        );
240}
241
242void *load_bootable_image(unsigned page_size, const char *kernel, const char *ramdisk,
243                          unsigned *sz, const char *cmdline)
244{
245    void *kdata = 0, *rdata = 0;
246    unsigned ksize = 0, rsize = 0;
247    void *bdata;
248    unsigned bsize;
249
250    if(kernel == 0) {
251        fprintf(stderr, "no image specified\n");
252        return 0;
253    }
254
255    kdata = load_file(kernel, &ksize);
256    if(kdata == 0) {
257        fprintf(stderr, "cannot load '%s'\n", kernel);
258        return 0;
259    }
260
261        /* is this actually a boot image? */
262    if(!memcmp(kdata, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
263        if(cmdline) bootimg_set_cmdline((boot_img_hdr*) kdata, cmdline);
264
265        if(ramdisk) {
266            fprintf(stderr, "cannot boot a boot.img *and* ramdisk\n");
267            return 0;
268        }
269
270        *sz = ksize;
271        return kdata;
272    }
273
274    if(ramdisk) {
275        rdata = load_file(ramdisk, &rsize);
276        if(rdata == 0) {
277            fprintf(stderr,"cannot load '%s'\n", ramdisk);
278            return  0;
279        }
280    }
281
282    fprintf(stderr,"creating boot image...\n");
283    bdata = mkbootimg(kdata, ksize, rdata, rsize, 0, 0, page_size, base_addr, &bsize);
284    if(bdata == 0) {
285        fprintf(stderr,"failed to create boot.img\n");
286        return 0;
287    }
288    if(cmdline) bootimg_set_cmdline((boot_img_hdr*) bdata, cmdline);
289    fprintf(stderr,"creating boot image - %d bytes\n", bsize);
290    *sz = bsize;
291
292    return bdata;
293}
294
295void *unzip_file(zipfile_t zip, const char *name, unsigned *sz)
296{
297    void *data;
298    zipentry_t entry;
299    unsigned datasz;
300
301    entry = lookup_zipentry(zip, name);
302    if (entry == NULL) {
303        fprintf(stderr, "archive does not contain '%s'\n", name);
304        return 0;
305    }
306
307    *sz = get_zipentry_size(entry);
308
309    datasz = *sz * 1.001;
310    data = malloc(datasz);
311
312    if(data == 0) {
313        fprintf(stderr, "failed to allocate %d bytes\n", *sz);
314        return 0;
315    }
316
317    if (decompress_zipentry(entry, data, datasz)) {
318        fprintf(stderr, "failed to unzip '%s' from archive\n", name);
319        free(data);
320        return 0;
321    }
322
323    return data;
324}
325
326static char *strip(char *s)
327{
328    int n;
329    while(*s && isspace(*s)) s++;
330    n = strlen(s);
331    while(n-- > 0) {
332        if(!isspace(s[n])) break;
333        s[n] = 0;
334    }
335    return s;
336}
337
338#define MAX_OPTIONS 32
339static int setup_requirement_line(char *name)
340{
341    char *val[MAX_OPTIONS];
342    const char **out;
343    unsigned n, count;
344    char *x;
345    int invert = 0;
346
347    if (!strncmp(name, "reject ", 7)) {
348        name += 7;
349        invert = 1;
350    } else if (!strncmp(name, "require ", 8)) {
351        name += 8;
352        invert = 0;
353    }
354
355    x = strchr(name, '=');
356    if (x == 0) return 0;
357    *x = 0;
358    val[0] = x + 1;
359
360    for(count = 1; count < MAX_OPTIONS; count++) {
361        x = strchr(val[count - 1],'|');
362        if (x == 0) break;
363        *x = 0;
364        val[count] = x + 1;
365    }
366
367    name = strip(name);
368    for(n = 0; n < count; n++) val[n] = strip(val[n]);
369
370    name = strip(name);
371    if (name == 0) return -1;
372
373        /* work around an unfortunate name mismatch */
374    if (!strcmp(name,"board")) name = "product";
375
376    out = malloc(sizeof(char*) * count);
377    if (out == 0) return -1;
378
379    for(n = 0; n < count; n++) {
380        out[n] = strdup(strip(val[n]));
381        if (out[n] == 0) return -1;
382    }
383
384    fb_queue_require(name, invert, n, out);
385    return 0;
386}
387
388static void setup_requirements(char *data, unsigned sz)
389{
390    char *s;
391
392    s = data;
393    while (sz-- > 0) {
394        if(*s == '\n') {
395            *s++ = 0;
396            if (setup_requirement_line(data)) {
397                die("out of memory");
398            }
399            data = s;
400        } else {
401            s++;
402        }
403    }
404}
405
406void queue_info_dump(void)
407{
408    fb_queue_notice("--------------------------------------------");
409    fb_queue_display("version-bootloader", "Bootloader Version...");
410    fb_queue_display("version-baseband",   "Baseband Version.....");
411    fb_queue_display("serialno",           "Serial Number........");
412    fb_queue_notice("--------------------------------------------");
413}
414
415void do_update_signature(zipfile_t zip, char *fn)
416{
417    void *data;
418    unsigned sz;
419    data = unzip_file(zip, fn, &sz);
420    if (data == 0) return;
421    fb_queue_download("signature", data, sz);
422    fb_queue_command("signature", "installing signature");
423}
424
425void do_update(char *fn)
426{
427    void *zdata;
428    unsigned zsize;
429    void *data;
430    unsigned sz;
431    zipfile_t zip;
432
433    queue_info_dump();
434
435    zdata = load_file(fn, &zsize);
436    if (zdata == 0) die("failed to load '%s'", fn);
437
438    zip = init_zipfile(zdata, zsize);
439    if(zip == 0) die("failed to access zipdata in '%s'");
440
441    data = unzip_file(zip, "android-info.txt", &sz);
442    if (data == 0) {
443        char *tmp;
444            /* fallback for older zipfiles */
445        data = unzip_file(zip, "android-product.txt", &sz);
446        if ((data == 0) || (sz < 1)) {
447            die("update package has no android-info.txt or android-product.txt");
448        }
449        tmp = malloc(sz + 128);
450        if (tmp == 0) die("out of memory");
451        sprintf(tmp,"board=%sversion-baseband=0.66.04.19\n",(char*)data);
452        data = tmp;
453        sz = strlen(tmp);
454    }
455
456    setup_requirements(data, sz);
457
458    data = unzip_file(zip, "boot.img", &sz);
459    if (data == 0) die("update package missing boot.img");
460    do_update_signature(zip, "boot.sig");
461    fb_queue_flash("boot", data, sz);
462
463    data = unzip_file(zip, "recovery.img", &sz);
464    if (data != 0) {
465        do_update_signature(zip, "recovery.sig");
466        fb_queue_flash("recovery", data, sz);
467    }
468
469    data = unzip_file(zip, "system.img", &sz);
470    if (data == 0) die("update package missing system.img");
471    do_update_signature(zip, "system.sig");
472    fb_queue_flash("system", data, sz);
473}
474
475void do_send_signature(char *fn)
476{
477    void *data;
478    unsigned sz;
479    char *xtn;
480
481    xtn = strrchr(fn, '.');
482    if (!xtn) return;
483    if (strcmp(xtn, ".img")) return;
484
485    strcpy(xtn,".sig");
486    data = load_file(fn, &sz);
487    strcpy(xtn,".img");
488    if (data == 0) return;
489    fb_queue_download("signature", data, sz);
490    fb_queue_command("signature", "installing signature");
491}
492
493void do_flashall(void)
494{
495    char *fname;
496    void *data;
497    unsigned sz;
498
499    queue_info_dump();
500
501    fname = find_item("info", product);
502    if (fname == 0) die("cannot find android-info.txt");
503    data = load_file(fname, &sz);
504    if (data == 0) die("could not load android-info.txt");
505    setup_requirements(data, sz);
506
507    fname = find_item("boot", product);
508    data = load_file(fname, &sz);
509    if (data == 0) die("could not load boot.img");
510    do_send_signature(fname);
511    fb_queue_flash("boot", data, sz);
512
513    fname = find_item("recovery", product);
514    data = load_file(fname, &sz);
515    if (data != 0) {
516        do_send_signature(fname);
517        fb_queue_flash("recovery", data, sz);
518    }
519
520    fname = find_item("system", product);
521    data = load_file(fname, &sz);
522    if (data == 0) die("could not load system.img");
523    do_send_signature(fname);
524    fb_queue_flash("system", data, sz);
525}
526
527#define skip(n) do { argc -= (n); argv += (n); } while (0)
528#define require(n) do { if (argc < (n)) usage(); exit(1);} while (0)
529
530int do_oem_command(int argc, char **argv)
531{
532    int i;
533    char command[256];
534    if (argc <= 1) return 0;
535
536    command[0] = 0;
537    while(1) {
538        strcat(command,*argv);
539        skip(1);
540        if(argc == 0) break;
541        strcat(command," ");
542    }
543
544    fb_queue_command(command,"");
545    return 0;
546}
547
548int main(int argc, char **argv)
549{
550    int wants_wipe = 0;
551    int wants_reboot = 0;
552    int wants_reboot_bootloader = 0;
553    void *data;
554    unsigned sz;
555    unsigned page_size = 2048;
556    int status;
557
558    skip(1);
559    if (argc == 0) {
560        usage();
561        return 1;
562    }
563
564    if (!strcmp(*argv, "devices")) {
565        list_devices();
566        return 0;
567    }
568
569    if (!strcmp(*argv, "help")) {
570        usage();
571        return 0;
572    }
573
574
575    serial = getenv("ANDROID_SERIAL");
576
577    while (argc > 0) {
578        if(!strcmp(*argv, "-w")) {
579            wants_wipe = 1;
580            skip(1);
581        } else if(!strcmp(*argv, "-b")) {
582            require(2);
583            base_addr = strtoul(argv[1], 0, 16);
584            skip(2);
585        } else if(!strcmp(*argv, "-n")) {
586            require(2);
587            page_size = (unsigned)strtoul(argv[1], NULL, 0);
588            if (!page_size) die("invalid page size");
589            skip(2);
590        } else if(!strcmp(*argv, "-s")) {
591            require(2);
592            serial = argv[1];
593            skip(2);
594        } else if(!strcmp(*argv, "-p")) {
595            require(2);
596            product = argv[1];
597            skip(2);
598        } else if(!strcmp(*argv, "-c")) {
599            require(2);
600            cmdline = argv[1];
601            skip(2);
602        } else if(!strcmp(*argv, "-i")) {
603            char *endptr = NULL;
604            unsigned long val;
605
606            require(2);
607            val = strtoul(argv[1], &endptr, 0);
608            if (!endptr || *endptr != '\0' || (val & ~0xffff))
609                die("invalid vendor id '%s'", argv[1]);
610            vendor_id = (unsigned short)val;
611            skip(2);
612        } else if(!strcmp(*argv, "getvar")) {
613            require(2);
614            fb_queue_display(argv[1], argv[1]);
615            skip(2);
616        } else if(!strcmp(*argv, "erase")) {
617            require(2);
618            fb_queue_erase(argv[1]);
619            skip(2);
620        } else if(!strcmp(*argv, "signature")) {
621            require(2);
622            data = load_file(argv[1], &sz);
623            if (data == 0) die("could not load '%s'", argv[1]);
624            if (sz != 256) die("signature must be 256 bytes");
625            fb_queue_download("signature", data, sz);
626            fb_queue_command("signature", "installing signature");
627            skip(2);
628        } else if(!strcmp(*argv, "reboot")) {
629            wants_reboot = 1;
630            skip(1);
631        } else if(!strcmp(*argv, "reboot-bootloader")) {
632            wants_reboot_bootloader = 1;
633            skip(1);
634        } else if (!strcmp(*argv, "continue")) {
635            fb_queue_command("continue", "resuming boot");
636            skip(1);
637        } else if(!strcmp(*argv, "boot")) {
638            char *kname = 0;
639            char *rname = 0;
640            skip(1);
641            if (argc > 0) {
642                kname = argv[0];
643                skip(1);
644            }
645            if (argc > 0) {
646                rname = argv[0];
647                skip(1);
648            }
649            data = load_bootable_image(page_size, kname, rname, &sz, cmdline);
650            if (data == 0) return 1;
651            fb_queue_download("boot.img", data, sz);
652            fb_queue_command("boot", "booting");
653        } else if(!strcmp(*argv, "flash")) {
654            char *pname = argv[1];
655            char *fname = 0;
656            require(2);
657            if (argc > 2) {
658                fname = argv[2];
659                skip(3);
660            } else {
661                fname = find_item(pname, product);
662                skip(2);
663            }
664            if (fname == 0) die("cannot determine image filename for '%s'", pname);
665            data = load_file(fname, &sz);
666            if (data == 0) die("cannot load '%s'\n", fname);
667            fb_queue_flash(pname, data, sz);
668        } else if(!strcmp(*argv, "flash:raw")) {
669            char *pname = argv[1];
670            char *kname = argv[2];
671            char *rname = 0;
672            require(3);
673            if(argc > 3) {
674                rname = argv[3];
675                skip(4);
676            } else {
677                skip(3);
678            }
679            data = load_bootable_image(page_size, kname, rname, &sz, cmdline);
680            if (data == 0) die("cannot load bootable image");
681            fb_queue_flash(pname, data, sz);
682        } else if(!strcmp(*argv, "flashall")) {
683            skip(1);
684            do_flashall();
685            wants_reboot = 1;
686        } else if(!strcmp(*argv, "update")) {
687            if (argc > 1) {
688                do_update(argv[1]);
689                skip(2);
690            } else {
691                do_update("update.zip");
692                skip(1);
693            }
694            wants_reboot = 1;
695        } else if(!strcmp(*argv, "oem")) {
696            argc = do_oem_command(argc, argv);
697        } else {
698            usage();
699            return 1;
700        }
701    }
702
703    if (wants_wipe) {
704        fb_queue_erase("userdata");
705        fb_queue_erase("cache");
706    }
707    if (wants_reboot) {
708        fb_queue_reboot();
709    } else if (wants_reboot_bootloader) {
710        fb_queue_command("reboot-bootloader", "rebooting into bootloader");
711    }
712
713    usb = open_device();
714
715    status = fb_execute_queue(usb);
716    return (status) ? 1 : 0;
717}
718