Add basic support for mini2440 board to barebox.
[barebox-mini2440.git] / lib / gunzip.c
blobc41568afd6eb30fdbaf0c3ac1e8f688fb0eb94c4
1 #include <common.h>
2 #include <zlib.h>
3 #include <malloc.h>
5 #define ZALLOC_ALIGNMENT 16
7 static void *zalloc(void *x, unsigned items, unsigned size)
9 void *p;
11 size *= items;
12 size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
14 p = malloc (size);
16 return (p);
19 static void zfree(void *x, void *addr, unsigned nb)
21 free (addr);
24 #define HEAD_CRC 2
25 #define EXTRA_FIELD 4
26 #define ORIG_NAME 8
27 #define COMMENT 0x10
28 #define RESERVED 0xe0
30 #define DEFLATED 8
32 int gunzip(void *dst, int dstlen, unsigned char *src, unsigned long *lenp)
34 z_stream s;
35 int r, i, flags;
37 /* skip header */
38 i = 10;
39 flags = src[3];
40 if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
41 puts ("Error: Bad gzipped data\n");
42 return (-1);
44 if ((flags & EXTRA_FIELD) != 0)
45 i = 12 + src[10] + (src[11] << 8);
46 if ((flags & ORIG_NAME) != 0)
47 while (src[i++] != 0)
49 if ((flags & COMMENT) != 0)
50 while (src[i++] != 0)
52 if ((flags & HEAD_CRC) != 0)
53 i += 2;
54 if (i >= *lenp) {
55 puts ("Error: gunzip out of data in header\n");
56 return (-1);
59 s.zalloc = zalloc;
60 s.zfree = zfree;
61 #if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
62 s.outcb = (cb_func)WATCHDOG_RESET;
63 #else
64 s.outcb = Z_NULL;
65 #endif /* CONFIG_HW_WATCHDOG */
67 r = inflateInit2(&s, -MAX_WBITS);
68 if (r != Z_OK) {
69 printf ("Error: inflateInit2() returned %d\n", r);
70 return (-1);
72 s.next_in = src + i;
73 s.avail_in = *lenp - i;
74 s.next_out = dst;
75 s.avail_out = dstlen;
76 r = inflate(&s, Z_FINISH);
77 if (r != Z_OK && r != Z_STREAM_END) {
78 printf ("Error: inflate() returned %d\n", r);
79 return (-1);
81 *lenp = s.next_out - (unsigned char *) dst;
82 inflateEnd(&s);
84 return (0);