Subject: [PATCH AUTOSEL 4.9 079/141] tools lib api fs: Fix gcc9 stringop-truncation compilation error

From: Sasha Levin <[email-masked]>
Date: Fri, 14 Feb 2020 11:20:19 -0500

From: Andrey Zhizhikin <[email-masked]>

[ Upstream commit 6794200fa3c9c3e6759dae099145f23e4310f4f7 ]

GCC9 introduced string hardening mechanisms, which exhibits the error
during fs api compilation:

error: '__builtin_strncpy' specified bound 4096 equals destination size
[-Werror=stringop-truncation]

This comes when the length of copy passed to strncpy is is equal to
destination size, which could potentially lead to buffer overflow.

There is a need to mitigate this potential issue by limiting the size of
destination by 1 and explicitly terminate the destination with NULL.

Signed-off-by: Andrey Zhizhikin <[email-masked]>
Reviewed-by: Petr Mladek <[email-masked]>
Acked-by: Jiri Olsa <[email-masked]>
Cc: Alexei Starovoitov <[email-masked]>
Cc: Andrii Nakryiko <[email-masked]>
Cc: Daniel Borkmann <[email-masked]>
Cc: Kefeng Wang <[email-masked]>
Cc: Martin KaFai Lau <[email-masked]>
Cc: Petr Mladek <[email-masked]>
Cc: Sergey Senozhatsky <[email-masked]>
Cc: Song Liu <[email-masked]>
Cc: Yonghong Song <[email-masked]>
Cc: [email-masked]
Cc: [email-masked]
Link: http://lore.kernel.org/lkml/[email-masked]
Signed-off-by: Arnaldo Carvalho de Melo <[email-masked]>
Signed-off-by: Sasha Levin <[email-masked]>
---
 tools/lib/api/fs/fs.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/tools/lib/api/fs/fs.c b/tools/lib/api/fs/fs.c
index f99f49e4a31e6..21e714cf0126c 100644
--- a/tools/lib/api/fs/fs.c
+++ b/tools/lib/api/fs/fs.c
@@ -194,6 +194,7 @@ static bool fs__env_override(struct fs *fs)
 	size_t name_len = strlen(fs->name);
 	/* name + "_PATH" + '\0' */
 	char upper_name[name_len + 5 + 1];
+
 	memcpy(upper_name, fs->name, name_len);
 	mem_toupper(upper_name, name_len);
 	strcpy(&upper_name[name_len], "_PATH");
@@ -203,7 +204,8 @@ static bool fs__env_override(struct fs *fs)
 		return false;
 
 	fs->found = true;
-	strncpy(fs->path, override_path, sizeof(fs->path));
+	strncpy(fs->path, override_path, sizeof(fs->path) - 1);
+	fs->path[sizeof(fs->path) - 1] = '\0';
 	return true;
 }
 
-- 
2.20.1