engine.c revision 6f1cd0b2ad7a16d4ec0b5324f992cae33dc34f34
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 "fastboot.h"
30#include "make_ext4fs.h"
31
32#include <errno.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <stdarg.h>
36#include <stdbool.h>
37#include <string.h>
38#include <sys/stat.h>
39#include <sys/time.h>
40#include <sys/types.h>
41#include <unistd.h>
42
43#ifdef USE_MINGW
44#include <fcntl.h>
45#else
46#include <sys/mman.h>
47#endif
48
49#define ARRAY_SIZE(x)           (sizeof(x)/sizeof(x[0]))
50
51double now()
52{
53    struct timeval tv;
54    gettimeofday(&tv, NULL);
55    return (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
56}
57
58char *mkmsg(const char *fmt, ...)
59{
60    char buf[256];
61    char *s;
62    va_list ap;
63
64    va_start(ap, fmt);
65    vsprintf(buf, fmt, ap);
66    va_end(ap);
67
68    s = strdup(buf);
69    if (s == 0) die("out of memory");
70    return s;
71}
72
73#define OP_DOWNLOAD   1
74#define OP_COMMAND    2
75#define OP_QUERY      3
76#define OP_NOTICE     4
77#define OP_FORMAT     5
78#define OP_DOWNLOAD_SPARSE 6
79#define OP_COMMAND_IGNORE_FAIL 7
80
81typedef struct Action Action;
82
83#define CMD_SIZE 64
84
85struct Action
86{
87    unsigned op;
88    Action *next;
89
90    char cmd[CMD_SIZE];
91    const char *prod;
92    void *data;
93    unsigned size;
94
95    const char *msg;
96    int (*func)(Action *a, int status, char *resp);
97
98    double start;
99};
100
101static Action *action_list = 0;
102static Action *action_last = 0;
103
104
105struct image_data {
106    long long partition_size;
107    long long image_size; // real size of image file
108    void *buffer;
109};
110
111void generate_ext4_image(struct image_data *image);
112void cleanup_image(struct image_data *image);
113
114int fb_getvar(struct usb_handle *usb, char *response, const char *fmt, ...)
115{
116    char cmd[CMD_SIZE] = "getvar:";
117    int getvar_len = strlen(cmd);
118    va_list args;
119
120    response[FB_RESPONSE_SZ] = '\0';
121    va_start(args, fmt);
122    vsnprintf(cmd + getvar_len, sizeof(cmd) - getvar_len, fmt, args);
123    va_end(args);
124    cmd[CMD_SIZE - 1] = '\0';
125    return fb_command_response(usb, cmd, response);
126}
127
128struct generator {
129    char *fs_type;
130
131    /* generate image and return it as image->buffer.
132     * size of the buffer returned as image->image_size.
133     *
134     * image->partition_size specifies what is the size of the
135     * file partition we generate image for.
136     */
137    void (*generate)(struct image_data *image);
138
139    /* it cleans the buffer allocated during image creation.
140     * this function probably does free() or munmap().
141     */
142    void (*cleanup)(struct image_data *image);
143} generators[] = {
144    { "ext4", generate_ext4_image, cleanup_image }
145};
146
147/* Return true if this partition is supported by the fastboot format command.
148 * It is also used to determine if we should first erase a partition before
149 * flashing it with an ext4 filesystem.  See needs_erase()
150 *
151 * Not all devices report the filesystem type, so don't report any errors,
152 * just return false.
153 */
154int fb_format_supported(usb_handle *usb, const char *partition)
155{
156    char response[FB_RESPONSE_SZ+1];
157    struct generator *generator = NULL;
158    int status;
159    unsigned int i;
160
161    status = fb_getvar(usb, response, "partition-type:%s", partition);
162    if (status) {
163        return 0;
164    }
165
166    for (i = 0; i < ARRAY_SIZE(generators); i++) {
167        if (!strncmp(generators[i].fs_type, response, FB_RESPONSE_SZ)) {
168            generator = &generators[i];
169            break;
170        }
171    }
172
173    if (generator) {
174        return 1;
175    }
176
177    return 0;
178}
179
180static int cb_default(Action *a, int status, char *resp)
181{
182    if (status) {
183        fprintf(stderr,"FAILED (%s)\n", resp);
184    } else {
185        double split = now();
186        fprintf(stderr,"OKAY [%7.3fs]\n", (split - a->start));
187        a->start = split;
188    }
189    return status;
190}
191
192static Action *queue_action(unsigned op, const char *fmt, ...)
193{
194    Action *a;
195    va_list ap;
196    size_t cmdsize;
197
198    a = calloc(1, sizeof(Action));
199    if (a == 0) die("out of memory");
200
201    va_start(ap, fmt);
202    cmdsize = vsnprintf(a->cmd, sizeof(a->cmd), fmt, ap);
203    va_end(ap);
204
205    if (cmdsize >= sizeof(a->cmd)) {
206        free(a);
207        die("Command length (%d) exceeds maximum size (%d)", cmdsize, sizeof(a->cmd));
208    }
209
210    if (action_last) {
211        action_last->next = a;
212    } else {
213        action_list = a;
214    }
215    action_last = a;
216    a->op = op;
217    a->func = cb_default;
218
219    a->start = -1;
220
221    return a;
222}
223
224void fb_queue_erase(const char *ptn)
225{
226    Action *a;
227    a = queue_action(OP_COMMAND, "erase:%s", ptn);
228    a->msg = mkmsg("erasing '%s'", ptn);
229}
230
231/* Loads file content into buffer. Returns NULL on error. */
232static void *load_buffer(int fd, off_t size)
233{
234    void *buffer;
235
236#ifdef USE_MINGW
237    ssize_t count = 0;
238
239    // mmap is more efficient but mingw does not support it.
240    // In this case we read whole image into memory buffer.
241    buffer = malloc(size);
242    if (!buffer) {
243        perror("malloc");
244        return NULL;
245    }
246
247    lseek(fd, 0, SEEK_SET);
248    while(count < size) {
249        ssize_t actually_read = read(fd, (char*)buffer+count, size-count);
250
251        if (actually_read == 0) {
252            break;
253        }
254        if (actually_read < 0) {
255            if (errno == EINTR) {
256                continue;
257            }
258            perror("read");
259            free(buffer);
260            return NULL;
261        }
262
263        count += actually_read;
264    }
265#else
266    buffer = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
267    if (buffer == MAP_FAILED) {
268        perror("mmap");
269        return NULL;
270    }
271#endif
272
273    return buffer;
274}
275
276void cleanup_image(struct image_data *image)
277{
278#ifdef USE_MINGW
279    free(image->buffer);
280#else
281    munmap(image->buffer, image->image_size);
282#endif
283}
284
285void generate_ext4_image(struct image_data *image)
286{
287    int fd;
288    struct stat st;
289
290#ifdef USE_MINGW
291    /* Ideally we should use tmpfile() here, the same as with unix version.
292     * But unfortunately it is not portable as it is not clear whether this
293     * function opens file in TEXT or BINARY mode.
294     *
295     * There are also some reports it is buggy:
296     *    http://pdplab.it.uom.gr/teaching/gcc_manuals/gnulib.html#tmpfile
297     *    http://www.mega-nerd.com/erikd/Blog/Windiots/tmpfile.html
298     */
299    char *filename = tempnam(getenv("TEMP"), "fastboot-format.img");
300    fd = open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0644);
301    unlink(filename);
302#else
303    fd = fileno(tmpfile());
304#endif
305    make_ext4fs_sparse_fd(fd, image->partition_size, NULL, NULL);
306
307    fstat(fd, &st);
308    image->image_size = st.st_size;
309    image->buffer = load_buffer(fd, st.st_size);
310
311    close(fd);
312}
313
314int fb_format(Action *a, usb_handle *usb, int skip_if_not_supported)
315{
316    const char *partition = a->cmd;
317    char response[FB_RESPONSE_SZ+1];
318    int status = 0;
319    struct image_data image;
320    struct generator *generator = NULL;
321    int fd;
322    unsigned i;
323    char cmd[CMD_SIZE];
324
325    status = fb_getvar(usb, response, "partition-type:%s", partition);
326    if (status) {
327        if (skip_if_not_supported) {
328            fprintf(stderr,
329                    "Erase successful, but not automatically formatting.\n");
330            fprintf(stderr,
331                    "Can't determine partition type.\n");
332            return 0;
333        }
334        fprintf(stderr,"FAILED (%s)\n", fb_get_error());
335        return status;
336    }
337
338    for (i = 0; i < ARRAY_SIZE(generators); i++) {
339        if (!strncmp(generators[i].fs_type, response, FB_RESPONSE_SZ)) {
340            generator = &generators[i];
341            break;
342        }
343    }
344    if (!generator) {
345        if (skip_if_not_supported) {
346            fprintf(stderr,
347                    "Erase successful, but not automatically formatting.\n");
348            fprintf(stderr,
349                    "File system type %s not supported.\n", response);
350            return 0;
351        }
352        fprintf(stderr,"Formatting is not supported for filesystem with type '%s'.\n",
353                response);
354        return -1;
355    }
356
357    status = fb_getvar(usb, response, "partition-size:%s", partition);
358    if (status) {
359        if (skip_if_not_supported) {
360            fprintf(stderr,
361                    "Erase successful, but not automatically formatting.\n");
362            fprintf(stderr, "Unable to get partition size\n.");
363            return 0;
364        }
365        fprintf(stderr,"FAILED (%s)\n", fb_get_error());
366        return status;
367    }
368    image.partition_size = strtoll(response, (char **)NULL, 16);
369
370    generator->generate(&image);
371    if (!image.buffer) {
372        fprintf(stderr,"Cannot generate image.\n");
373        return -1;
374    }
375
376    // Following piece of code is similar to fb_queue_flash() but executes
377    // actions directly without queuing
378    snprintf(cmd, sizeof(cmd), "preflash:%s", partition);
379    fb_command(usb, cmd);  /* Ignore status */
380    fprintf(stderr, "sending '%s' (%lli KB)...\n", partition, image.image_size/1024);
381    status = fb_download_data(usb, image.buffer, image.image_size);
382    if (status) goto cleanup;
383
384    fprintf(stderr, "writing '%s'...\n", partition);
385    snprintf(cmd, sizeof(cmd), "flash:%s", partition);
386    status = fb_command(usb, cmd);
387    if (status) goto cleanup;
388
389cleanup:
390    generator->cleanup(&image);
391
392    return status;
393}
394
395void fb_queue_format(const char *partition, int skip_if_not_supported)
396{
397    Action *a;
398
399    a = queue_action(OP_FORMAT, partition);
400    a->data = (void*)skip_if_not_supported;
401    a->msg = mkmsg("formatting '%s' partition", partition);
402}
403
404void fb_queue_flash(const char *ptn, void *data, unsigned sz)
405{
406    Action *a;
407
408    a = queue_action(OP_COMMAND_IGNORE_FAIL, "preflash:%s", ptn);
409    a->msg = mkmsg("prep for '%s' (%d KB)", ptn, sz / 1024);
410    a = queue_action(OP_DOWNLOAD, "");
411    a->data = data;
412    a->size = sz;
413    a->msg = mkmsg("sending '%s' (%d KB)", ptn, sz / 1024);
414
415    a = queue_action(OP_COMMAND, "flash:%s", ptn);
416    a->msg = mkmsg("writing '%s'", ptn);
417}
418
419void fb_queue_flash_sparse(const char *ptn, struct sparse_file *s, unsigned sz)
420{
421    Action *a;
422
423    a = queue_action(OP_COMMAND_IGNORE_FAIL, "preflash:%s", ptn);
424    a->msg = mkmsg("prep for sparse '%s' (%d KB)", ptn, sz / 1024);
425    a = queue_action(OP_DOWNLOAD_SPARSE, "");
426    a->data = s;
427    a->size = 0;
428    a->msg = mkmsg("sending sparse '%s' (%d KB)", ptn, sz / 1024);
429
430    a = queue_action(OP_COMMAND, "flash:%s", ptn);
431    a->msg = mkmsg("writing '%s'", ptn);
432}
433
434static int match(char *str, const char **value, unsigned count)
435{
436    const char *val;
437    unsigned n;
438    int len;
439
440    for (n = 0; n < count; n++) {
441        const char *val = value[n];
442        int len = strlen(val);
443        int match;
444
445        if ((len > 1) && (val[len-1] == '*')) {
446            len--;
447            match = !strncmp(val, str, len);
448        } else {
449            match = !strcmp(val, str);
450        }
451
452        if (match) return 1;
453    }
454
455    return 0;
456}
457
458
459
460static int cb_check(Action *a, int status, char *resp, int invert)
461{
462    const char **value = a->data;
463    unsigned count = a->size;
464    unsigned n;
465    int yes;
466
467    if (status) {
468        fprintf(stderr,"FAILED (%s)\n", resp);
469        return status;
470    }
471
472    if (a->prod) {
473        if (strcmp(a->prod, cur_product) != 0) {
474            double split = now();
475            fprintf(stderr,"IGNORE, product is %s required only for %s [%7.3fs]\n",
476                    cur_product, a->prod, (split - a->start));
477            a->start = split;
478            return 0;
479        }
480    }
481
482    yes = match(resp, value, count);
483    if (invert) yes = !yes;
484
485    if (yes) {
486        double split = now();
487        fprintf(stderr,"OKAY [%7.3fs]\n", (split - a->start));
488        a->start = split;
489        return 0;
490    }
491
492    fprintf(stderr,"FAILED\n\n");
493    fprintf(stderr,"Device %s is '%s'.\n", a->cmd + 7, resp);
494    fprintf(stderr,"Update %s '%s'",
495            invert ? "rejects" : "requires", value[0]);
496    for (n = 1; n < count; n++) {
497        fprintf(stderr," or '%s'", value[n]);
498    }
499    fprintf(stderr,".\n\n");
500    return -1;
501}
502
503static int cb_require(Action *a, int status, char *resp)
504{
505    return cb_check(a, status, resp, 0);
506}
507
508static int cb_reject(Action *a, int status, char *resp)
509{
510    return cb_check(a, status, resp, 1);
511}
512
513void fb_queue_require(const char *prod, const char *var,
514		int invert, unsigned nvalues, const char **value)
515{
516    Action *a;
517    a = queue_action(OP_QUERY, "getvar:%s", var);
518    a->prod = prod;
519    a->data = value;
520    a->size = nvalues;
521    a->msg = mkmsg("checking %s", var);
522    a->func = invert ? cb_reject : cb_require;
523    if (a->data == 0) die("out of memory");
524}
525
526static int cb_display(Action *a, int status, char *resp)
527{
528    if (status) {
529        fprintf(stderr, "%s FAILED (%s)\n", a->cmd, resp);
530        return status;
531    }
532    fprintf(stderr, "%s: %s\n", (char*) a->data, resp);
533    return 0;
534}
535
536void fb_queue_display(const char *var, const char *prettyname)
537{
538    Action *a;
539    a = queue_action(OP_QUERY, "getvar:%s", var);
540    a->data = strdup(prettyname);
541    if (a->data == 0) die("out of memory");
542    a->func = cb_display;
543}
544
545static int cb_save(Action *a, int status, char *resp)
546{
547    if (status) {
548        fprintf(stderr, "%s FAILED (%s)\n", a->cmd, resp);
549        return status;
550    }
551    strncpy(a->data, resp, a->size);
552    return 0;
553}
554
555void fb_queue_query_save(const char *var, char *dest, unsigned dest_size)
556{
557    Action *a;
558    a = queue_action(OP_QUERY, "getvar:%s", var);
559    a->data = (void *)dest;
560    a->size = dest_size;
561    a->func = cb_save;
562}
563
564static int cb_do_nothing(Action *a, int status, char *resp)
565{
566    fprintf(stderr,"\n");
567    return 0;
568}
569
570void fb_queue_reboot(void)
571{
572    Action *a = queue_action(OP_COMMAND, "reboot");
573    a->func = cb_do_nothing;
574    a->msg = "rebooting";
575}
576
577void fb_queue_command(const char *cmd, const char *msg)
578{
579    Action *a = queue_action(OP_COMMAND, cmd);
580    a->msg = msg;
581}
582
583void fb_queue_download(const char *name, void *data, unsigned size)
584{
585    Action *a;
586    a = queue_action(OP_COMMAND_IGNORE_FAIL, "preflash:");
587    a = queue_action(OP_DOWNLOAD, "");
588    a->data = data;
589    a->size = size;
590    a->msg = mkmsg("downloading '%s'", name);
591}
592
593void fb_queue_notice(const char *notice)
594{
595    Action *a = queue_action(OP_NOTICE, "");
596    a->data = (void*) notice;
597}
598
599int fb_execute_queue(usb_handle *usb)
600{
601    Action *a;
602    char resp[FB_RESPONSE_SZ+1];
603    int status = 0;
604
605    a = action_list;
606    if (!a)
607        return status;
608    resp[FB_RESPONSE_SZ] = 0;
609
610    double start = -1;
611    for (a = action_list; a; a = a->next) {
612        a->start = now();
613        if (start < 0) start = a->start;
614        if (a->msg) {
615            // fprintf(stderr,"%30s... ",a->msg);
616            fprintf(stderr,"%s...\n",a->msg);
617        }
618        if (a->op == OP_DOWNLOAD) {
619            status = fb_download_data(usb, a->data, a->size);
620            status = a->func(a, status, status ? fb_get_error() : "");
621            if (status) break;
622        } else if (a->op == OP_COMMAND) {
623            status = fb_command(usb, a->cmd);
624            status = a->func(a, status, status ? fb_get_error() : "");
625            if (status) break;
626        } else if (a->op == OP_COMMAND_IGNORE_FAIL) {
627            fb_command(usb, a->cmd);   /* Ignore status */
628        } else if (a->op == OP_QUERY) {
629            status = fb_command_response(usb, a->cmd, resp);
630            status = a->func(a, status, status ? fb_get_error() : resp);
631            if (status) break;
632        } else if (a->op == OP_NOTICE) {
633            fprintf(stderr,"%s\n",(char*)a->data);
634        } else if (a->op == OP_FORMAT) {
635            status = fb_format(a, usb, (int)a->data);
636            status = a->func(a, status, status ? fb_get_error() : "");
637            if (status) break;
638        } else if (a->op == OP_DOWNLOAD_SPARSE) {
639            status = fb_download_data_sparse(usb, a->data);
640            status = a->func(a, status, status ? fb_get_error() : "");
641            if (status) break;
642        } else {
643            die("bogus action");
644        }
645    }
646
647    fprintf(stderr,"finished. total time: %.3fs\n", (now() - start));
648    return status;
649}
650
651int fb_queue_is_empty(void)
652{
653    return (action_list == NULL);
654}
655