]> www.infradead.org Git - users/jedix/linux-maple.git/commitdiff
libbpf: Fix undefined behavior in {get,put}_unaligned_be32()
authorEric Biggers <ebiggers@kernel.org>
Mon, 6 Oct 2025 01:20:37 +0000 (18:20 -0700)
committerAndrii Nakryiko <andrii@kernel.org>
Mon, 6 Oct 2025 16:16:29 +0000 (09:16 -0700)
These violate aliasing rules and may be miscompiled unless
-fno-strict-aliasing is used.  Replace them with the standard memcpy()
solution.  Note that compilers know how to optimize this properly.

Fixes: 4a1c9e544b8d ("libbpf: remove linux/unaligned.h dependency for libbpf_sha256()")
Signed-off-by: Eric Biggers <ebiggers@kernel.org>
Signed-off-by: Andrii Nakryiko <andrii@kernel.org>
Acked-by: Yonghong Song <yonghong.song@linux.dev>
Link: https://lore.kernel.org/bpf/20251006012037.159295-1-ebiggers@kernel.org
tools/lib/bpf/libbpf_utils.c

index 5d66bc6ff0982e5e52bea174eea5da2f3e006f23..ac3beae54cf67f8931d6a8507c77a6b3b325377e 100644 (file)
@@ -148,16 +148,20 @@ const char *libbpf_errstr(int err)
        }
 }
 
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wpacked"
-#pragma GCC diagnostic ignored "-Wattributes"
-struct __packed_u32 { __u32 __val; } __attribute__((packed));
-#pragma GCC diagnostic pop
-
-#define get_unaligned_be32(p) be32_to_cpu((((struct __packed_u32 *)(p))->__val))
-#define put_unaligned_be32(v, p) do {                                                  \
-       ((struct __packed_u32 *)(p))->__val = cpu_to_be32(v);                           \
-} while (0)
+static inline __u32 get_unaligned_be32(const void *p)
+{
+       __be32 val;
+
+       memcpy(&val, p, sizeof(val));
+       return be32_to_cpu(val);
+}
+
+static inline void put_unaligned_be32(__u32 val, void *p)
+{
+       __be32 be_val = cpu_to_be32(val);
+
+       memcpy(p, &be_val, sizeof(be_val));
+}
 
 #define SHA256_BLOCK_LENGTH 64
 #define Ch(x, y, z) (((x) & (y)) ^ (~(x) & (z)))