[PATCH] lib: fwts_battery: add helper to build battery path name

Colin King colin.king at canonical.com
Tue Jul 28 15:53:11 UTC 2020


From: Colin Ian King <colin.king at canonical.com>

The current method of building a battery pathname may cause truncation
and gcc-10 generates build errors because of this. Add a helper that
builds the module path that uses the BSD strlcat for safe string
concatenation with known (and ignored) truncation since we know that
the module path name can't exceed PATH_MAX size.

Signed-off-by: Colin Ian King <colin.king at canonical.com>
---
 src/lib/src/fwts_battery.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/src/lib/src/fwts_battery.c b/src/lib/src/fwts_battery.c
index 3005b533..ef93e75d 100644
--- a/src/lib/src/fwts_battery.c
+++ b/src/lib/src/fwts_battery.c
@@ -187,6 +187,19 @@ static int fwts_battery_get_capacity_proc_fs(fwts_framework *fw,
 	return FWTS_OK;
 }
 
+static inline void fwts_battery_path(
+	char *path,
+	const size_t path_len,
+	const char *power_supply,
+	const char *name)
+{
+	(void)strlcpy(path, power_supply, path_len);
+	(void)strlcat(path, "/", path_len);
+	(void)strlcat(path, name, path_len);
+	(void)strlcat(path, "/", path_len);
+	(void)strlcat(path, "type", path_len);
+}
+
 static int fwts_battery_get_count_sys_fs(DIR *dir, uint32_t *count)
 {
 	struct dirent *entry;
@@ -197,7 +210,7 @@ static int fwts_battery_get_count_sys_fs(DIR *dir, uint32_t *count)
 		entry = readdir(dir);
 		if (entry && strlen(entry->d_name) > 2) {
 			/* Check that type field matches the expected type */
-			snprintf(path, sizeof(path), "%s/%s/type", FWTS_SYS_CLASS_POWER_SUPPLY, entry->d_name);
+			fwts_battery_path(path, sizeof(path), FWTS_SYS_CLASS_POWER_SUPPLY, entry->d_name);
 			if ((data = fwts_get(path)) != NULL) {
 				if (strstr(data, "Battery") != NULL)
 					(*count)++;
-- 
2.27.0




More information about the fwts-devel mailing list