1*4882a593Smuzhiyun #include <linux/zutil.h>
2*4882a593Smuzhiyun #include <linux/errno.h>
3*4882a593Smuzhiyun #include <linux/slab.h>
4*4882a593Smuzhiyun #include <linux/vmalloc.h>
5*4882a593Smuzhiyun
6*4882a593Smuzhiyun /* Utility function: initialize zlib, unpack binary blob, clean up zlib,
7*4882a593Smuzhiyun * return len or negative error code.
8*4882a593Smuzhiyun */
zlib_inflate_blob(void * gunzip_buf,unsigned int sz,const void * buf,unsigned int len)9*4882a593Smuzhiyun int zlib_inflate_blob(void *gunzip_buf, unsigned int sz,
10*4882a593Smuzhiyun const void *buf, unsigned int len)
11*4882a593Smuzhiyun {
12*4882a593Smuzhiyun const u8 *zbuf = buf;
13*4882a593Smuzhiyun struct z_stream_s *strm;
14*4882a593Smuzhiyun int rc;
15*4882a593Smuzhiyun
16*4882a593Smuzhiyun rc = -ENOMEM;
17*4882a593Smuzhiyun strm = kmalloc(sizeof(*strm), GFP_KERNEL);
18*4882a593Smuzhiyun if (strm == NULL)
19*4882a593Smuzhiyun goto gunzip_nomem1;
20*4882a593Smuzhiyun strm->workspace = kmalloc(zlib_inflate_workspacesize(), GFP_KERNEL);
21*4882a593Smuzhiyun if (strm->workspace == NULL)
22*4882a593Smuzhiyun goto gunzip_nomem2;
23*4882a593Smuzhiyun
24*4882a593Smuzhiyun /* gzip header (1f,8b,08... 10 bytes total + possible asciz filename)
25*4882a593Smuzhiyun * expected to be stripped from input
26*4882a593Smuzhiyun */
27*4882a593Smuzhiyun strm->next_in = zbuf;
28*4882a593Smuzhiyun strm->avail_in = len;
29*4882a593Smuzhiyun strm->next_out = gunzip_buf;
30*4882a593Smuzhiyun strm->avail_out = sz;
31*4882a593Smuzhiyun
32*4882a593Smuzhiyun rc = zlib_inflateInit2(strm, -MAX_WBITS);
33*4882a593Smuzhiyun if (rc == Z_OK) {
34*4882a593Smuzhiyun rc = zlib_inflate(strm, Z_FINISH);
35*4882a593Smuzhiyun /* after Z_FINISH, only Z_STREAM_END is "we unpacked it all" */
36*4882a593Smuzhiyun if (rc == Z_STREAM_END)
37*4882a593Smuzhiyun rc = sz - strm->avail_out;
38*4882a593Smuzhiyun else
39*4882a593Smuzhiyun rc = -EINVAL;
40*4882a593Smuzhiyun zlib_inflateEnd(strm);
41*4882a593Smuzhiyun } else
42*4882a593Smuzhiyun rc = -EINVAL;
43*4882a593Smuzhiyun
44*4882a593Smuzhiyun kfree(strm->workspace);
45*4882a593Smuzhiyun gunzip_nomem2:
46*4882a593Smuzhiyun kfree(strm);
47*4882a593Smuzhiyun gunzip_nomem1:
48*4882a593Smuzhiyun return rc; /* returns Z_OK (0) if successful */
49*4882a593Smuzhiyun }
50