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