1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24#include <common.h>
25#include <watchdog.h>
26#include <command.h>
27#include <image.h>
28#include <malloc.h>
29#include <zlib.h>
30
31#define ZALLOC_ALIGNMENT 16
32#define HEAD_CRC 2
33#define EXTRA_FIELD 4
34#define ORIG_NAME 8
35#define COMMENT 0x10
36#define RESERVED 0xe0
37#define DEFLATED 8
38
39int gunzip(void *, int, unsigned char *, unsigned long *);
40void *zalloc(void *, unsigned, unsigned);
41void zfree(void *, void *, unsigned);
42
43void *zalloc(void *x, unsigned items, unsigned size)
44{
45 void *p;
46
47 size *= items;
48 size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
49
50 p = malloc (size);
51
52 return (p);
53}
54
55void zfree(void *x, void *addr, unsigned nb)
56{
57 free (addr);
58}
59
60int gunzip(void *dst, int dstlen, unsigned char *src, unsigned long *lenp)
61{
62 z_stream s;
63 int r, i, flags;
64
65
66 i = 10;
67 flags = src[3];
68 if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
69 puts ("Error: Bad gzipped data\n");
70 return (-1);
71 }
72 if ((flags & EXTRA_FIELD) != 0)
73 i = 12 + src[10] + (src[11] << 8);
74 if ((flags & ORIG_NAME) != 0)
75 while (src[i++] != 0)
76 ;
77 if ((flags & COMMENT) != 0)
78 while (src[i++] != 0)
79 ;
80 if ((flags & HEAD_CRC) != 0)
81 i += 2;
82 if (i >= *lenp) {
83 puts ("Error: gunzip out of data in header\n");
84 return (-1);
85 }
86
87 s.zalloc = zalloc;
88 s.zfree = zfree;
89#if defined(CONFIG_HW_WATCHDOG) || defined(CONFIG_WATCHDOG)
90 s.outcb = (cb_func)WATCHDOG_RESET;
91#else
92 s.outcb = Z_NULL;
93#endif
94
95 r = inflateInit2(&s, -MAX_WBITS);
96 if (r != Z_OK) {
97 printf ("Error: inflateInit2() returned %d\n", r);
98 return (-1);
99 }
100 s.next_in = src + i;
101 s.avail_in = *lenp - i;
102 s.next_out = dst;
103 s.avail_out = dstlen;
104 r = inflate(&s, Z_FINISH);
105 if (r != Z_STREAM_END) {
106 printf ("Error: inflate() returned %d\n", r);
107 inflateEnd(&s);
108 return (-1);
109 }
110 *lenp = s.next_out - (unsigned char *) dst;
111 inflateEnd(&s);
112
113 return (0);
114}
115