From 82420bc21d3e5946289f367f70099ecaae8a3d06 Mon Sep 17 00:00:00 2001 From: Caleb Sander Date: Fri, 13 Oct 2023 22:35:43 -0600 Subject: [PATCH] nbft: Avoid unaligned pointer dereferences Avoid casting byte-aligned pointers to pointers with higher alignment. Loading or storing values with higher alignment is undefined behavior, since some processors don't allow unaligned memory accesses and compilers may assume pointers of different types don't alias. Perform an explicit memcpy() in two places, which an optimizing compiler can easily replace with a single load/store on supported architectures. While we're touching this code, also use IN6_IS_ADDR_V4MAPPED() instead of hand-rolling it. Signed-off-by: Caleb Sander --- src/nvme/nbft.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/nvme/nbft.c b/src/nvme/nbft.c index a1e17cd8..300703b6 100644 --- a/src/nvme/nbft.c +++ b/src/nvme/nbft.c @@ -33,17 +33,15 @@ static __u8 csum(const __u8 *buffer, ssize_t length) static void format_ip_addr(char *buf, size_t buflen, __u8 *addr) { - struct in6_addr *addr_ipv6; + struct in6_addr addr_ipv6; - addr_ipv6 = (struct in6_addr *)addr; - if (addr_ipv6->s6_addr32[0] == 0 && - addr_ipv6->s6_addr32[1] == 0 && - ntohl(addr_ipv6->s6_addr32[2]) == 0xffff) + memcpy(&addr_ipv6, addr, sizeof(addr_ipv6)); + if (IN6_IS_ADDR_V4MAPPED(&addr_ipv6)) /* ipv4 */ - inet_ntop(AF_INET, &(addr_ipv6->s6_addr32[3]), buf, buflen); + inet_ntop(AF_INET, &addr_ipv6.s6_addr32[3], buf, buflen); else /* ipv6 */ - inet_ntop(AF_INET6, addr_ipv6, buf, buflen); + inet_ntop(AF_INET6, &addr_ipv6, buf, buflen); } static bool in_heap(struct nbft_header *header, struct nbft_heap_obj obj) -- 2.50.1