index: fix copy/paste error
[mit.git] / zlibsupport.c
blob26b186d5e4b957dc8e804ed6f67df32888745612
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).
6 * (C) 2003 Rusty Russell, IBM Corporation.
7 */
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <fcntl.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <sys/mman.h>
15 #include "zlibsupport.h"
16 #include "testing.h"
18 #ifdef CONFIG_USE_ZLIB
19 #include <zlib.h>
21 void *grab_contents(gzFile *gzfd, unsigned long *size)
23 unsigned int max = 16384;
24 void *buffer = malloc(max);
25 int ret;
27 if (!buffer)
28 return NULL;
30 *size = 0;
31 while ((ret = gzread(gzfd, buffer + *size, max - *size)) > 0) {
32 *size += ret;
33 if (*size == max) {
34 void *p;
36 p = realloc(buffer, max *= 2);
37 if (!p)
38 goto out_err;
40 buffer = p;
43 if (ret < 0)
44 goto out_err;
46 return buffer;
48 out_err:
49 free(buffer);
50 return NULL;
53 void *grab_fd(int fd, unsigned long *size)
55 gzFile gzfd;
57 gzfd = gzdopen(fd, "rb");
58 if (!gzfd)
59 return NULL;
61 /* gzclose(gzfd) would close fd, which would drop locks.
62 Don't blame zlib: POSIX locking semantics are so horribly
63 broken that they should be ripped out. */
64 return grab_contents(gzfd, size);
67 /* gzopen handles uncompressed files transparently. */
68 void *grab_file(const char *filename, unsigned long *size)
70 gzFile gzfd;
71 void *buffer;
73 gzfd = gzopen(filename, "rb");
74 if (!gzfd)
75 return NULL;
76 buffer = grab_contents(gzfd, size);
77 gzclose(gzfd);
78 return buffer;
81 void release_file(void *data, unsigned long size)
83 free(data);
85 #else /* ... !CONFIG_USE_ZLIB */
87 void *grab_fd(int fd, unsigned long *size)
89 struct stat st;
90 void *map;
91 int ret;
93 ret = fstat(fd, &st);
94 if (ret < 0)
95 return NULL;
96 *size = st.st_size;
97 map = mmap(0, *size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
98 if (map == MAP_FAILED)
99 map = NULL;
100 return map;
103 void *grab_file(const char *filename, unsigned long *size)
105 int fd;
106 void *map;
108 fd = open(filename, O_RDONLY, 0);
109 if (fd < 0)
110 return NULL;
111 map = grab_fd(fd, size);
112 close(fd);
113 return map;
116 void release_file(void *data, unsigned long size)
118 munmap(data, size);
120 #endif