Fix read_file in case file size if > SSIZE_MAX

This commit is contained in:
Nils O. Selåsdal
2014-03-13 23:07:57 +01:00
parent 633635851d
commit c2fe3e5dc7
+16 -11
View File
@@ -1,10 +1,11 @@
#include <stdlib.h> #include <stdlib.h>
#include <fcntl.h> #include <limits.h>
#include <unistd.h> #include <fcntl.h>
#include <errno.h> #include <unistd.h>
#include <sys/types.h> #include <errno.h>
#include <sys/stat.h> #include <sys/types.h>
#include "ucore/read_file.h" #include <sys/stat.h>
#include "ucore/read_file.h"
#define CHUNK_SZ 1024 #define CHUNK_SZ 1024
@@ -27,17 +28,21 @@ uc_read_file(const char *f, size_t *length, size_t max)
} }
if ((statb.st_mode & S_IFMT) == S_IFREG) { if ((statb.st_mode & S_IFMT) == S_IFREG) {
if ((size_t)statb.st_size > max) { if (statb.st_size > (off_t)max) {
errno = EMSGSIZE; errno = EMSGSIZE;
goto out_close; goto out_close;
} }
alloc_sz = (size_t) statb.st_size + 1; // + 1 to avoid one realloc if (statb.st_size > SSIZE_MAX) {
s = malloc((size_t) alloc_sz + 1); //+1 for nul terminator //otherwise we cannot detect the return value of read()
alloc_sz = SSIZE_MAX;
} else {
alloc_sz = statb.st_size;
}
} else { } else {
alloc_sz = CHUNK_SZ; alloc_sz = CHUNK_SZ;
s = malloc(alloc_sz + 1); //+1 for nul terminator
} }
s = malloc(alloc_sz + 1); //+1 for nul terminator
if (s == NULL) { if (s == NULL) {
goto out_close; goto out_close;
} }