]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
fileio: read_virtual_file() don't tweak buffer for returning it when we aren't return...
authorLennart Poettering <lennart@poettering.net>
Fri, 21 May 2021 15:33:32 +0000 (17:33 +0200)
committerLennart Poettering <lennart@poettering.net>
Fri, 21 May 2021 19:54:43 +0000 (21:54 +0200)
Let's avoid some redundant work.

Moreover, let' not check for NUL bytes in the buffer if we don't return
the buffer.

src/basic/fileio.c

index 778e74d22c90342e2e3877f2728fdad3a48fcbf3..cd6f2f7a77e3ed72cc8eefd6847edfcce0e0b707 100644 (file)
@@ -478,28 +478,30 @@ int read_virtual_file(const char *filename, size_t max_size, char **ret_contents
                 buf = mfree(buf);
         }
 
-        if (n < size) {
-                char *p;
+        if (ret_contents) {
 
-                /* Return rest of the buffer to libc */
-                p = realloc(buf, n + 1);
-                if (!p)
-                        return -ENOMEM;
-                buf = p;
-        }
-
-        if (ret_size)
-                *ret_size = n;
-        else if (memchr(buf, 0, n))
                 /* Safety check: if the caller doesn't want to know the size of what we just read it will
                  * rely on the trailing NUL byte. But if there's an embedded NUL byte, then we should refuse
                  * operation as otherwise there'd be ambiguity about what we just read. */
-                return -EBADMSG;
+                if (!ret_size && memchr(buf, 0, n))
+                        return -EBADMSG;
 
-        buf[n] = 0;
+                if (n < size) {
+                        char *p;
 
-        if (ret_contents)
+                        /* Return rest of the buffer to libc */
+                        p = realloc(buf, n + 1);
+                        if (!p)
+                                return -ENOMEM;
+                        buf = p;
+                }
+
+                buf[n] = 0;
                 *ret_contents = TAKE_PTR(buf);
+        }
+
+        if (ret_size)
+                *ret_size = n;
 
         return !truncated;
 }