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 <u-boot/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
39void *zalloc(void *, unsigned, unsigned);
40void zfree(void *, void *, unsigned);
41
42void *zalloc(void *x, unsigned items, unsigned size)
43{
44 void *p;
45
46 size *= items;
47 size = (size + ZALLOC_ALIGNMENT - 1) & ~(ZALLOC_ALIGNMENT - 1);
48
49 p = malloc (size);
50
51 return (p);
52}
53
54void zfree(void *x, void *addr, unsigned nb)
55{
56 free (addr);
57}
58
59int gunzip(void *dst, int dstlen, unsigned char *src, unsigned long *lenp)
60{
61 int i, flags;
62
63
64 i = 10;
65 flags = src[3];
66 if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
67 puts ("Error: Bad gzipped data\n");
68 return (-1);
69 }
70 if ((flags & EXTRA_FIELD) != 0)
71 i = 12 + src[10] + (src[11] << 8);
72 if ((flags & ORIG_NAME) != 0)
73 while (src[i++] != 0)
74 ;
75 if ((flags & COMMENT) != 0)
76 while (src[i++] != 0)
77 ;
78 if ((flags & HEAD_CRC) != 0)
79 i += 2;
80 if (i >= *lenp) {
81 puts ("Error: gunzip out of data in header\n");
82 return (-1);
83 }
84
85 return zunzip(dst, dstlen, src, lenp, 1, i);
86}
87
88
89
90
91int zunzip(void *dst, int dstlen, unsigned char *src, unsigned long *lenp,
92 int stoponerr, int offset)
93{
94 z_stream s;
95 int r;
96
97 s.zalloc = zalloc;
98 s.zfree = zfree;
99
100 r = inflateInit2(&s, -MAX_WBITS);
101 if (r != Z_OK) {
102 printf ("Error: inflateInit2() returned %d\n", r);
103 return -1;
104 }
105 s.next_in = src + offset;
106 s.avail_in = *lenp - offset;
107 s.next_out = dst;
108 s.avail_out = dstlen;
109 r = inflate(&s, Z_FINISH);
110 if ((r != Z_STREAM_END) && (stoponerr==1)) {
111 printf ("Error: inflate() returned %d\n", r);
112 inflateEnd(&s);
113 return (-1);
114 }
115 *lenp = s.next_out - (unsigned char *) dst;
116 inflateEnd(&s);
117
118 return 0;
119}
120