Skip to contentSkip to conversation

Replace strncpy with strscpy to ensure null-termination

PATCH In review kendrajmoore 2 participants 2 messages Mar 23, 2025 – Jun 8, 2025 Turbostat utility

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Replace strncpy with strscpy to ensure null-termination

From: Kendra Moore <[email protected]>

The field pcounter->name is used as a null-terminated string. Using strncpy() with ARRAY_SIZE - 1 does not guarantee null-termination and can lead to undefined behavior if the source is too long.

This patch replaces it with strscpy() which ensures null-termination and returns an error code if truncation occurs.

---
 tools/power/x86/turbostat/turbostat.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/power/x86/turbostat/turbostat.c +1 -1
index 8d5011a0bf60..8f24e18d3de0 100644
@@ -9345,7 +9345,7 @@ int pmt_add_counter(unsigned int guid, unsigned int seq, const char *name, enum
 	}
 
 	if (new_counter) {
-		strncpy(pcounter->name, name, ARRAY_SIZE(pcounter->name) - 1);
+		strscpy(pcounter->name, name, ARRAY_SIZE(pcounter->name));
 		pcounter->type = type;
 		pcounter->scope = scope;
 		pcounter->lsb = lsb;
Signature · 1 line
2.39.5
maintainer
#1 lore raw
Quoted 3 lines · kendrajmoore

--- a/tools/power/x86/turbostat/turbostat.c

+ strscpy(pcounter->name, name, ARRAY_SIZE(pcounter->name));

Nope -- strscpy() is kernel specific, not available to user space utilities.

Len Brown, Intel Open Source Technology Center