aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJean-Marc Valin <jmvalin@jmvalin.ca>2024-03-03 00:14:55 -0500
committerJean-Marc Valin <jmvalin@jmvalin.ca>2024-03-03 00:30:30 -0500
commit33a89b7ea8db4d9a6fcc802aa85264e13a4ebbaf (patch)
treeb3a442be46892c9bf489ad3c983a9a287978d857
parentc9276272abc65b2a06d13d1b351d2c52417270d9 (diff)
downloadlibopus-33a89b7ea8db4d9a6fcc802aa85264e13a4ebbaf.tar.gz
Add checks when loading blob data
-rw-r--r--dnn/lpcnet_demo.c30
-rw-r--r--src/opus_demo.c28
2 files changed, 51 insertions, 7 deletions
diff --git a/dnn/lpcnet_demo.c b/dnn/lpcnet_demo.c
index 8e3acdd7..59651f3e 100644
--- a/dnn/lpcnet_demo.c
+++ b/dnn/lpcnet_demo.c
@@ -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;
}
diff --git a/src/opus_demo.c b/src/opus_demo.c
index 365cb965..1ea8454a 100644
--- a/src/opus_demo.c
+++ b/src/opus_demo.c
@@ -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;
}