Add checks when loading blob data

This commit is contained in:
Jean-Marc Valin 2024-03-03 00:14:55 -05:00
parent c9276272ab
commit 33a89b7ea8
No known key found for this signature in database
GPG key ID: 5E5DD9A36F9189C8
2 changed files with 51 additions and 7 deletions

View file

@ -52,26 +52,50 @@ void *load_blob(const char *filename, int *len) {
int fd;
void *data;
struct stat st;
stat(filename, &st);
if (stat(filename, &st)) {
*len = 0;
return NULL;
}
*len = st.st_size;
fd = open(filename, O_RDONLY);
if (fd<0) {
*len = 0;
return NULL;
}
data = mmap(NULL, *len, PROT_READ, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) {
*len = 0;
data = NULL;
}
close(fd);
return data;
}
void free_blob(void *blob, int len) {
munmap(blob, len);
if (blob) munmap(blob, len);
}
# else
void *load_blob(const char *filename, int *len) {
FILE *file;
void *data;
file = fopen(filename, "r");
if (file == NULL)
{
perror("could not open blob file");
*len = 0;
return NULL;
}
fseek(file, 0L, SEEK_END);
*len = ftell(file);
fseek(file, 0L, SEEK_SET);
if (*len <= 0) return NULL;
if (*len <= 0) {
*len = 0;
return NULL;
}
data = malloc(*len);
if (!data) {
*len = 0;
return NULL;
}
*len = fread(data, 1, *len, file);
return data;
}

View file

@ -58,15 +58,26 @@ void *load_blob(const char *filename, int *len) {
int fd;
void *data;
struct stat st;
stat(filename, &st);
if (stat(filename, &st)) {
*len = 0;
return NULL;
}
*len = st.st_size;
fd = open(filename, O_RDONLY);
if (fd<0) {
*len = 0;
return NULL;
}
data = mmap(NULL, *len, PROT_READ, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) {
*len = 0;
data = NULL;
}
close(fd);
return data;
}
void free_blob(void *blob, int len) {
munmap(blob, len);
if (blob) munmap(blob, len);
}
# else
void *load_blob(const char *filename, int *len) {
@ -75,13 +86,22 @@ void *load_blob(const char *filename, int *len) {
file = fopen(filename, "r");
if (file == NULL)
{
perror("could not open blob file\n");
perror("could not open blob file");
*len = 0;
return NULL;
}
fseek(file, 0L, SEEK_END);
*len = ftell(file);
fseek(file, 0L, SEEK_SET);
if (*len <= 0) return NULL;
if (*len <= 0) {
*len = 0;
return NULL;
}
data = malloc(*len);
if (!data) {
*len = 0;
return NULL;
}
*len = fread(data, 1, *len, file);
return data;
}