depmod: fix tabs in help output
[module-init-tools.git] / zlibsupport.c
blob597820ecd4e956e0b1e8f1054538fbfeb66941e2
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 <errno.h>
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <sys/mman.h>
16 #include "zlibsupport.h"
17 #include "logging.h"
18 #include "testing.h"
20 #ifdef CONFIG_USE_ZLIB
21 #include <zlib.h>
23 void *grab_contents(gzFile *gzfd, unsigned long *size)
25 unsigned int max = 16384;
26 void *buffer = NOFAIL(malloc(max));
27 int ret;
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));
35 if (ret < 0) {
36 free(buffer);
37 buffer = NULL;
40 return buffer;
43 /* gzopen handles uncompressed files transparently. */
44 void *grab_file(const char *filename, unsigned long *size)
46 gzFile gzfd;
47 void *buffer;
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;
56 buffer = grab_contents(gzfd, size);
57 gzclose(gzfd);
58 return buffer;
61 void release_file(void *data, unsigned long size)
63 free(data);
65 #else /* ... !CONFIG_USE_ZLIB */
67 void *grab_fd(int fd, unsigned long *size)
69 struct stat st;
70 void *map;
71 int ret;
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;
83 void *grab_file(const char *filename, unsigned long *size)
85 int fd;
86 void *map;
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;
96 void release_file(void *data, unsigned long size)
98 munmap(data, size);
100 #endif