tizen 2.0
[external/module-init-tools.git] / zlibsupport.c
1 /* Support for compressed modules.  Willy Tarreau <willy@meta-x.org>
2  * did the support for modutils, Andrey Borzenkov <arvidjaar@mail.ru>
3  * ported it to module-init-tools, and I said it was too ugly to live
4  * and rewrote it 8).
5  *
6  * (C) 2003 Rusty Russell, IBM Corporation.
7  */
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <fcntl.h>
11 #include <errno.h>
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <sys/mman.h>
15
16 #include "zlibsupport.h"
17 #include "logging.h"
18 #include "testing.h"
19
20 #ifdef CONFIG_USE_ZLIB
21 #include <zlib.h>
22
23 void *grab_contents(gzFile *gzfd, unsigned long *size)
24 {
25         unsigned int max = 16384;
26         void *buffer = NOFAIL(malloc(max));
27         int ret;
28
29         *size = 0;
30         while ((ret = gzread(gzfd, buffer + *size, max - *size)) > 0) {
31                 *size += ret;
32                 if (*size == max)
33                         buffer = NOFAIL(realloc(buffer, max *= 2));
34         }
35         if (ret < 0) {
36                 free(buffer);
37                 buffer = NULL;
38         }
39
40         return buffer;
41 }
42
43 /* gzopen handles uncompressed files transparently. */
44 void *grab_file(const char *filename, unsigned long *size)
45 {
46         gzFile gzfd;
47         void *buffer;
48
49         errno = 0;
50         gzfd = gzopen(filename, "rb");
51         if (!gzfd) {
52                 if (errno == ENOMEM)
53                         fatal("Memory allocation failure in gzopen\n");
54                 return NULL;
55         }
56         buffer = grab_contents(gzfd, size);
57         gzclose(gzfd);
58         return buffer;
59 }
60
61 void release_file(void *data, unsigned long size)
62 {
63         free(data);
64 }
65 #else /* ... !CONFIG_USE_ZLIB */
66
67 void *grab_fd(int fd, unsigned long *size)
68 {
69         struct stat st;
70         void *map;
71         int ret;
72
73         ret = fstat(fd, &st);
74         if (ret < 0)
75                 return NULL;
76         *size = st.st_size;
77         map = mmap(0, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
78         if (map == MAP_FAILED)
79                 map = NULL;
80         return map;
81 }
82
83 void *grab_file(const char *filename, unsigned long *size)
84 {
85         int fd;
86         void *map;
87
88         fd = open(filename, O_RDONLY, 0);
89         if (fd < 0)
90                 return NULL;
91         map = grab_fd(fd, size);
92         close(fd);
93         return map;
94 }
95
96 void release_file(void *data, unsigned long size)
97 {
98         munmap(data, size);
99 }
100 #endif