engine.c revision 13081c6915220db03886b177f1a8e0b2c63467c9
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#include "ext4_utils.h"
32
33#include <stdio.h>
34#include <stdlib.h>
35#include <stdarg.h>
36#include <stdbool.h>
37#include <string.h>
38#include <sys/mman.h>
39#include <sys/stat.h>
40#include <sys/time.h>
41#include <sys/types.h>
42#include <unistd.h>
43
44extern struct fs_info info;
45
46#define ARRAY_SIZE(x)           (sizeof(x)/sizeof(x[0]))
47
48double now()
49{
50    struct timeval tv;
51    gettimeofday(&tv, NULL);
52    return (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
53}
54
55char *mkmsg(const char *fmt, ...)
56{
57    char buf[256];
58    char *s;
59    va_list ap;
60
61    va_start(ap, fmt);
62    vsprintf(buf, fmt, ap);
63    va_end(ap);
64
65    s = strdup(buf);
66    if (s == 0) die("out of memory");
67    return s;
68}
69
70#define OP_DOWNLOAD   1
71#define OP_COMMAND    2
72#define OP_QUERY      3
73#define OP_NOTICE     4
74#define OP_FORMAT     5
75
76typedef struct Action Action;
77
78#define CMD_SIZE 64
79
80struct Action
81{
82    unsigned op;
83    Action *next;
84
85    char cmd[CMD_SIZE];
86    const char *prod;
87    void *data;
88    unsigned size;
89
90    const char *msg;
91    int (*func)(Action *a, int status, char *resp);
92
93    double start;
94};
95
96static Action *action_list = 0;
97static Action *action_last = 0;
98
99
100struct image_data {
101    long long partition_size;
102    long long image_size; // real size of image file
103    void *buffer;
104};
105
106void generate_ext4_image(struct image_data *image);
107void munmap_image(struct image_data *image);
108
109struct generator {
110    char *fs_type;
111
112    /* generate image and return it as image->buffer.
113     * size of the buffer returned as image->image_size.
114     *
115     * image->partition_size specifies what is the size of the
116     * file partition we generate image for.
117     */
118    void (*generate)(struct image_data *image);
119
120    /* it cleans the buffer allocated during image creation.
121     * this function probably does free() or munmap().
122     */
123    void (*cleanup)(struct image_data *image);
124} generators[] = {
125    { "ext4", generate_ext4_image, munmap_image }
126};
127
128static int cb_default(Action *a, int status, char *resp)
129{
130    if (status) {
131        fprintf(stderr,"FAILED (%s)\n", resp);
132    } else {
133        double split = now();
134        fprintf(stderr,"OKAY [%7.3fs]\n", (split - a->start));
135        a->start = split;
136    }
137    return status;
138}
139
140static Action *queue_action(unsigned op, const char *fmt, ...)
141{
142    Action *a;
143    va_list ap;
144    size_t cmdsize;
145
146    a = calloc(1, sizeof(Action));
147    if (a == 0) die("out of memory");
148
149    va_start(ap, fmt);
150    cmdsize = vsnprintf(a->cmd, sizeof(a->cmd), fmt, ap);
151    va_end(ap);
152
153    if (cmdsize >= sizeof(a->cmd)) {
154        free(a);
155        die("Command length (%d) exceeds maximum size (%d)", cmdsize, sizeof(a->cmd));
156    }
157
158    if (action_last) {
159        action_last->next = a;
160    } else {
161        action_list = a;
162    }
163    action_last = a;
164    a->op = op;
165    a->func = cb_default;
166
167    a->start = -1;
168
169    return a;
170}
171
172void fb_queue_erase(const char *ptn)
173{
174    Action *a;
175    a = queue_action(OP_COMMAND, "erase:%s", ptn);
176    a->msg = mkmsg("erasing '%s'", ptn);
177}
178
179void munmap_image(struct image_data *image)
180{
181    munmap(image->buffer, image->image_size);
182}
183
184void generate_ext4_image(struct image_data *image)
185{
186    int fd;
187    struct stat st;
188
189    fd = fileno(tmpfile());
190    /* reset ext4fs info so we can be called multiple times */
191    reset_ext4fs_info();
192    info.len = image->partition_size;
193    make_ext4fs_internal(fd, NULL, NULL, 0, 0, 1, 0, 0, 0);
194
195    fstat(fd, &st);
196    image->image_size = st.st_size;
197
198    image->buffer = mmap(NULL, image->image_size, PROT_READ, MAP_PRIVATE, fd, 0);
199    if (image->buffer == MAP_FAILED) {
200        perror("mmap");
201        image->buffer = NULL;
202    }
203
204    close(fd);
205}
206
207int fb_format(Action *a, usb_handle *usb, int skip_if_not_supported)
208{
209    const char *partition = a->cmd;
210    char query[256];
211    char response[FB_RESPONSE_SZ+1];
212    int status = 0;
213    struct image_data image;
214    struct generator *generator = NULL;
215    int fd;
216    unsigned i;
217    char cmd[CMD_SIZE];
218
219    response[FB_RESPONSE_SZ] = '\0';
220    snprintf(query, sizeof(query), "getvar:partition-type:%s", partition);
221    status = fb_command_response(usb, query, response);
222    if (status) {
223        if (skip_if_not_supported) {
224            fprintf(stderr,
225                    "Erase successful, but not automatically formatting.\n");
226            fprintf(stderr,
227                    "Can't determine partition type.\n");
228            return 0;
229        }
230        fprintf(stderr,"FAILED (%s)\n", fb_get_error());
231        return status;
232    }
233
234    for (i = 0; i < ARRAY_SIZE(generators); i++) {
235        if (!strncmp(generators[i].fs_type, response, FB_RESPONSE_SZ)) {
236            generator = &generators[i];
237            break;
238        }
239    }
240    if (!generator) {
241        if (skip_if_not_supported) {
242            fprintf(stderr,
243                    "Erase successful, but not automatically formatting.\n");
244            fprintf(stderr,
245                    "File system type %s not supported.\n", response);
246            return 0;
247        }
248        fprintf(stderr,"Formatting is not supported for filesystem with type '%s'.\n",
249                response);
250        return -1;
251    }
252
253    response[FB_RESPONSE_SZ] = '\0';
254    snprintf(query, sizeof(query), "getvar:partition-size:%s", partition);
255    status = fb_command_response(usb, query, response);
256    if (status) {
257        if (skip_if_not_supported) {
258            fprintf(stderr,
259                    "Erase successful, but not automatically formatting.\n");
260            fprintf(stderr, "Unable to get partition size\n.");
261            return 0;
262        }
263        fprintf(stderr,"FAILED (%s)\n", fb_get_error());
264        return status;
265    }
266    image.partition_size = strtoll(response, (char **)NULL, 16);
267
268    generator->generate(&image);
269    if (!image.buffer) {
270        fprintf(stderr,"Cannot generate image.\n");
271        return -1;
272    }
273
274    // Following piece of code is similar to fb_queue_flash() but executes
275    // actions directly without queuing
276    fprintf(stderr, "sending '%s' (%lli KB)...\n", partition, image.image_size/1024);
277    status = fb_download_data(usb, image.buffer, image.image_size);
278    if (status) goto cleanup;
279
280    fprintf(stderr, "writing '%s'...\n", partition);
281    snprintf(cmd, CMD_SIZE, "flash:%s", partition);
282    status = fb_command(usb, cmd);
283    if (status) goto cleanup;
284
285cleanup:
286    generator->cleanup(&image);
287
288    return status;
289}
290
291void fb_queue_format(const char *partition, int skip_if_not_supported)
292{
293    Action *a;
294
295    a = queue_action(OP_FORMAT, partition);
296    a->data = (void*)skip_if_not_supported;
297    a->msg = mkmsg("formatting '%s' partition", partition);
298}
299
300void fb_queue_flash(const char *ptn, void *data, unsigned sz)
301{
302    Action *a;
303
304    a = queue_action(OP_DOWNLOAD, "");
305    a->data = data;
306    a->size = sz;
307    a->msg = mkmsg("sending '%s' (%d KB)", ptn, sz / 1024);
308
309    a = queue_action(OP_COMMAND, "flash:%s", ptn);
310    a->msg = mkmsg("writing '%s'", ptn);
311}
312
313static int match(char *str, const char **value, unsigned count)
314{
315    const char *val;
316    unsigned n;
317    int len;
318
319    for (n = 0; n < count; n++) {
320        const char *val = value[n];
321        int len = strlen(val);
322        int match;
323
324        if ((len > 1) && (val[len-1] == '*')) {
325            len--;
326            match = !strncmp(val, str, len);
327        } else {
328            match = !strcmp(val, str);
329        }
330
331        if (match) return 1;
332    }
333
334    return 0;
335}
336
337
338
339static int cb_check(Action *a, int status, char *resp, int invert)
340{
341    const char **value = a->data;
342    unsigned count = a->size;
343    unsigned n;
344    int yes;
345
346    if (status) {
347        fprintf(stderr,"FAILED (%s)\n", resp);
348        return status;
349    }
350
351    if (a->prod) {
352        if (strcmp(a->prod, cur_product) != 0) {
353            double split = now();
354            fprintf(stderr,"IGNORE, product is %s required only for %s [%7.3fs]\n",
355                    cur_product, a->prod, (split - a->start));
356            a->start = split;
357            return 0;
358        }
359    }
360
361    yes = match(resp, value, count);
362    if (invert) yes = !yes;
363
364    if (yes) {
365        double split = now();
366        fprintf(stderr,"OKAY [%7.3fs]\n", (split - a->start));
367        a->start = split;
368        return 0;
369    }
370
371    fprintf(stderr,"FAILED\n\n");
372    fprintf(stderr,"Device %s is '%s'.\n", a->cmd + 7, resp);
373    fprintf(stderr,"Update %s '%s'",
374            invert ? "rejects" : "requires", value[0]);
375    for (n = 1; n < count; n++) {
376        fprintf(stderr," or '%s'", value[n]);
377    }
378    fprintf(stderr,".\n\n");
379    return -1;
380}
381
382static int cb_require(Action *a, int status, char *resp)
383{
384    return cb_check(a, status, resp, 0);
385}
386
387static int cb_reject(Action *a, int status, char *resp)
388{
389    return cb_check(a, status, resp, 1);
390}
391
392void fb_queue_require(const char *prod, const char *var,
393		int invert, unsigned nvalues, const char **value)
394{
395    Action *a;
396    a = queue_action(OP_QUERY, "getvar:%s", var);
397    a->prod = prod;
398    a->data = value;
399    a->size = nvalues;
400    a->msg = mkmsg("checking %s", var);
401    a->func = invert ? cb_reject : cb_require;
402    if (a->data == 0) die("out of memory");
403}
404
405static int cb_display(Action *a, int status, char *resp)
406{
407    if (status) {
408        fprintf(stderr, "%s FAILED (%s)\n", a->cmd, resp);
409        return status;
410    }
411    fprintf(stderr, "%s: %s\n", (char*) a->data, resp);
412    return 0;
413}
414
415void fb_queue_display(const char *var, const char *prettyname)
416{
417    Action *a;
418    a = queue_action(OP_QUERY, "getvar:%s", var);
419    a->data = strdup(prettyname);
420    if (a->data == 0) die("out of memory");
421    a->func = cb_display;
422}
423
424static int cb_save(Action *a, int status, char *resp)
425{
426    if (status) {
427        fprintf(stderr, "%s FAILED (%s)\n", a->cmd, resp);
428        return status;
429    }
430    strncpy(a->data, resp, a->size);
431    return 0;
432}
433
434void fb_queue_query_save(const char *var, char *dest, unsigned dest_size)
435{
436    Action *a;
437    a = queue_action(OP_QUERY, "getvar:%s", var);
438    a->data = (void *)dest;
439    a->size = dest_size;
440    a->func = cb_save;
441}
442
443static int cb_do_nothing(Action *a, int status, char *resp)
444{
445    fprintf(stderr,"\n");
446    return 0;
447}
448
449void fb_queue_reboot(void)
450{
451    Action *a = queue_action(OP_COMMAND, "reboot");
452    a->func = cb_do_nothing;
453    a->msg = "rebooting";
454}
455
456void fb_queue_command(const char *cmd, const char *msg)
457{
458    Action *a = queue_action(OP_COMMAND, cmd);
459    a->msg = msg;
460}
461
462void fb_queue_download(const char *name, void *data, unsigned size)
463{
464    Action *a = queue_action(OP_DOWNLOAD, "");
465    a->data = data;
466    a->size = size;
467    a->msg = mkmsg("downloading '%s'", name);
468}
469
470void fb_queue_notice(const char *notice)
471{
472    Action *a = queue_action(OP_NOTICE, "");
473    a->data = (void*) notice;
474}
475
476int fb_execute_queue(usb_handle *usb)
477{
478    Action *a;
479    char resp[FB_RESPONSE_SZ+1];
480    int status = 0;
481
482    a = action_list;
483    if (!a)
484        return status;
485    resp[FB_RESPONSE_SZ] = 0;
486
487    double start = -1;
488    for (a = action_list; a; a = a->next) {
489        a->start = now();
490        if (start < 0) start = a->start;
491        if (a->msg) {
492            // fprintf(stderr,"%30s... ",a->msg);
493            fprintf(stderr,"%s...\n",a->msg);
494        }
495        if (a->op == OP_DOWNLOAD) {
496            status = fb_download_data(usb, a->data, a->size);
497            status = a->func(a, status, status ? fb_get_error() : "");
498            if (status) break;
499        } else if (a->op == OP_COMMAND) {
500            status = fb_command(usb, a->cmd);
501            status = a->func(a, status, status ? fb_get_error() : "");
502            if (status) break;
503        } else if (a->op == OP_QUERY) {
504            status = fb_command_response(usb, a->cmd, resp);
505            status = a->func(a, status, status ? fb_get_error() : resp);
506            if (status) break;
507        } else if (a->op == OP_NOTICE) {
508            fprintf(stderr,"%s\n",(char*)a->data);
509        } else if (a->op == OP_FORMAT) {
510            status = fb_format(a, usb, (int)a->data);
511            status = a->func(a, status, status ? fb_get_error() : "");
512            if (status) break;
513        } else {
514            die("bogus action");
515        }
516    }
517
518    fprintf(stderr,"finished. total time: %.3fs\n", (now() - start));
519    return status;
520}
521
522int fb_queue_is_empty(void)
523{
524    return (action_list == NULL);
525}
526