Skip to contentSkip to conversation

netlink: Remove implicit 32-bit trunction in nla_memcmp

PATCH In review Ian Rogers 2 participants 2 messages Dec 9, 2025 – Dec 10, 2025 Library code

lore
Share & tools
lore

Ian Rogers

author
#0 lore raw

PATCH 1/1 netlink: Remove implicit 32-bit trunction in nla_memcmp

64-bit truncation to 32-bit can result in the sign of the truncated value changing. The nla_memcmp function subtracts a 16-bit nla_len from a size_t size and so this shouldn't occur, but the code looks hazardous so change it to make the comparisons explicit and avoid a truncated subtract.

---
 lib/nlattr.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
lib/nlattr.c +4 -4
index be9c576b6e2d..6e1c40dd11e3 100644
@@ -854,12 +854,12 @@ EXPORT_SYMBOL(nla_memcpy);
 int nla_memcmp(const struct nlattr *nla, const void *data,
 			     size_t size)
 {
-	int d = nla_len(nla) - size;
+	u16 l = nla_len(nla);
 
-	if (d == 0)
-		d = memcmp(nla_data(nla), data, size);
+	if (l == size)
+		return memcmp(nla_data(nla), data, size);
 
-	return d;
+	return l > size ? 1 : -1;
 }
 EXPORT_SYMBOL(nla_memcmp);
 
Signature · 1 line
2.52.0.223.gf5cc29aaa4-goog
#1 lore raw
Quoted 16 lines · On Tue, 9 Dec 2025 14:41:58 -0800 Ian Rogers <[email protected]> wrote:

64-bit truncation to 32-bit can result in the sign of the truncated value changing. The nla_memcmp function subtracts a 16-bit nla_len from a size_t size and so this shouldn't occur, but the code looks hazardous so change it to make the comparisons explicit and avoid a truncated subtract.

---
 lib/nlattr.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
lib/nlattr.c +0 -0
index be9c576b6e2d..6e1c40dd11e3 100644

lib/nlattr.c EXPORT_SYMBOL(nla_memcpy); · line 857

Quoted 5 lines
lib/nlattr.c +1 -1
@@ -854,12 +854,12 @@ EXPORT_SYMBOL(nla_memcpy);
 int nla_memcmp(const struct nlattr *nla, const void *data,
 			     size_t size)
 {
-	int d = nla_len(nla) - size;
+	u16 l = nla_len(nla);

Don't use u16 for locals.
Generates unnecessarily bad code.

David

Quoted 11 lines
lib/nlattr.c +3 -3
-	if (d == 0)
-		d = memcmp(nla_data(nla), data, size);
+	if (l == size)
+		return memcmp(nla_data(nla), data, size);
 
-	return d;
+	return l > size ? 1 : -1;
 }
 EXPORT_SYMBOL(nla_memcmp);