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