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