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