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