]>
git.ipfire.org Git - thirdparty/kmod.git/blob - libkmod/libkmod-file.c
99ff3f2abe9c10e428de60bfb09c5ea9e46c3aab
2 * libkmod - interface to kernel module operations
4 * Copyright (C) 2011 ProFUSION embedded systems
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25 #include <sys/types.h>
31 #include "libkmod-private.h"
47 #define READ_STEP (4 * 1024 * 1024)
49 static bool check_zlib(struct kmod_file
*file
)
51 uint8_t magic
[2] = {0, 0}, zlibmagic
[2] = {0x1f, 0x8b};
52 size_t done
= 0, todo
= 2;
54 ssize_t r
= read(file
->fd
, magic
+ done
, todo
);
60 else if (errno
== EAGAIN
|| errno
== EINTR
)
65 lseek(file
->fd
, 0, SEEK_SET
);
66 return memcmp(magic
, zlibmagic
, 2) == 0;
68 lseek(file
->fd
, 0, SEEK_SET
);
72 static int zlib_file_open(struct kmod_file
*file
)
75 off_t did
= 0, total
= 0;
76 unsigned char *p
= NULL
;
79 file
->gzf
= gzdopen(file
->fd
, "rb");
80 if (file
->gzf
== NULL
) {
89 void *tmp
= realloc(p
, total
+ READ_STEP
);
98 r
= gzread(file
->gzf
, p
+ did
, total
- did
);
118 static int reg_file_open(struct kmod_file
*file
)
123 if (fstat(file
->fd
, &st
) < 0) {
128 file
->size
= st
.st_size
;
129 file
->memory
= mmap(0, file
->size
, PROT_READ
, MAP_PRIVATE
, file
->fd
, 0);
130 if (file
->memory
== MAP_FAILED
) {
141 struct kmod_file
*kmod_file_open(const char *filename
)
143 struct kmod_file
*file
= calloc(1, sizeof(struct kmod_file
));
149 file
->fd
= open(filename
, O_RDONLY
|O_CLOEXEC
);
156 if (check_zlib(file
))
157 err
= zlib_file_open(file
);
160 err
= reg_file_open(file
);
172 void *kmod_file_get_contents(const struct kmod_file
*file
)
177 off_t
kmod_file_get_size(const struct kmod_file
*file
)
182 void kmod_file_unref(struct kmod_file
*file
)
185 if (file
->gzf
!= NULL
) {
190 munmap(file
->memory
, file
->size
);