summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>2021-03-25 11:58:35 +0100
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>2021-03-26 15:46:44 +0100
commitca79564309e87f1cd92f7c79a03fccb792cca274 (patch)
treef237e32b35549b66cdd93081b88a38be3ae3e2e6
parent91a96a564f5fc0dbad15f1c23a0fbda157a03558 (diff)
downloadsystemd-ca79564309e87f1cd92f7c79a03fccb792cca274.tar.gz
basic/fileio: simplify calculation of buffer size in read_full_virtual_file()
We'd first assign a value up to SSIZE_MAX, and then immediately check if we have a value bigger than READ_FULL_BYTES_MAX. This wasn't exactly wrong, but a bit roundabout. Let's immediately assign the value from the appropriate range or error out. Coverity CID#1450973.
-rw-r--r--src/basic/fileio.c18
1 files changed, 11 insertions, 7 deletions
diff --git a/src/basic/fileio.c b/src/basic/fileio.c
index 6e42b60c3f..46ab5db79f 100644
--- a/src/basic/fileio.c
+++ b/src/basic/fileio.c
@@ -403,18 +403,22 @@ int read_full_virtual_file(const char *filename, char **ret_contents, size_t *re
return -EBADF;
/* Be prepared for files from /proc which generally report a file size of 0. */
+ assert_cc(READ_FULL_BYTES_MAX < SSIZE_MAX);
if (st.st_size > 0) {
- if (st.st_size > SSIZE_MAX) /* safety check in case off_t is 64bit and size_t 32bit */
+ if (st.st_size > READ_FULL_BYTES_MAX)
return -E2BIG;
size = st.st_size;
n_retries--;
- } else
- /* Double the buffer size (saturate in case of overflow) */
- size = size > SSIZE_MAX / 2 ? SSIZE_MAX : size * 2;
-
- if (size > READ_FULL_BYTES_MAX)
- return -E2BIG;
+ } else {
+ /* Double the buffer size */
+ if (size >= READ_FULL_BYTES_MAX)
+ return -E2BIG;
+ if (size > READ_FULL_BYTES_MAX / 2)
+ size = READ_FULL_BYTES_MAX; /* clamp to max */
+ else
+ size *= 2;
+ }
buf = malloc(size + 1);
if (!buf)