ref: 33a89b7ea8db4d9a6fcc802aa85264e13a4ebbaf
parent: c9276272abc65b2a06d13d1b351d2c52417270d9
author: Jean-Marc Valin <jmvalin@jmvalin.ca>
date: Sat Mar 2 19:14:55 EST 2024
Add checks when loading blob data
--- a/dnn/lpcnet_demo.c
+++ b/dnn/lpcnet_demo.c
@@ -52,15 +52,26 @@
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) {@@ -67,11 +78,24 @@
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;
}
--- a/src/opus_demo.c
+++ b/src/opus_demo.c
@@ -58,15 +58,26 @@
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 @@
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;
}
--
⑨