Karel Zak 18b0e4
From f6fffc1a89e57b7d5dd4adf1ee6b2146e58ec411 Mon Sep 17 00:00:00 2001
Karel Zak 18b0e4
From: Karel Zak <kzak@redhat.com>
Karel Zak 18b0e4
Date: Thu, 17 Mar 2022 12:18:03 +0100
Karel Zak 18b0e4
Subject: lib/path: make ul_path_read_buffer() more robust [coverity scan]
Karel Zak 18b0e4
Karel Zak 18b0e4
Make sure we never call buf[rc - 1] for rc=0.
Karel Zak 18b0e4
Karel Zak 18b0e4
Upstream: http://github.com/util-linux/util-linux/commit/ea459dcf95d0bb04c816b71d2b85fbcd8cfc5ee4
Karel Zak 18b0e4
Addresses: https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=2109459
Karel Zak 18b0e4
Signed-off-by: Karel Zak <kzak@redhat.com>
Karel Zak 18b0e4
---
Karel Zak 18b0e4
 lib/path.c | 17 ++++++++++-------
Karel Zak 18b0e4
 1 file changed, 10 insertions(+), 7 deletions(-)
Karel Zak 18b0e4
Karel Zak 18b0e4
diff --git a/lib/path.c b/lib/path.c
Karel Zak 18b0e4
index 21f9bd1c4..ab034e110 100644
Karel Zak 18b0e4
--- a/lib/path.c
Karel Zak 18b0e4
+++ b/lib/path.c
Karel Zak 18b0e4
@@ -666,14 +666,17 @@ int ul_path_readf_string(struct path_cxt *pc, char **str, const char *path, ...)
Karel Zak 18b0e4
 int ul_path_read_buffer(struct path_cxt *pc, char *buf, size_t bufsz, const char *path)
Karel Zak 18b0e4
 {
Karel Zak 18b0e4
 	int rc = ul_path_read(pc, buf, bufsz - 1, path);
Karel Zak 18b0e4
-	if (rc < 0)
Karel Zak 18b0e4
-		return rc;
Karel Zak 18b0e4
 
Karel Zak 18b0e4
-	/* Remove tailing newline (usual in sysfs) */
Karel Zak 18b0e4
-	if (rc > 0 && *(buf + rc - 1) == '\n')
Karel Zak 18b0e4
-		buf[--rc] = '\0';
Karel Zak 18b0e4
-	else
Karel Zak 18b0e4
-		buf[rc - 1] = '\0';
Karel Zak 18b0e4
+	if (rc == 0)
Karel Zak 18b0e4
+		buf[0] = '\0';
Karel Zak 18b0e4
+
Karel Zak 18b0e4
+	else if (rc > 0) {
Karel Zak 18b0e4
+		/* Remove tailing newline (usual in sysfs) */
Karel Zak 18b0e4
+		if (*(buf + rc - 1) == '\n')
Karel Zak 18b0e4
+			buf[--rc] = '\0';
Karel Zak 18b0e4
+		else
Karel Zak 18b0e4
+			buf[rc - 1] = '\0';
Karel Zak 18b0e4
+	}
Karel Zak 18b0e4
 
Karel Zak 18b0e4
 	return rc;
Karel Zak 18b0e4
 }
Karel Zak 18b0e4
-- 
Karel Zak 18b0e4
2.36.1
Karel Zak 18b0e4