From: Aurelien DARRAGON Date: Thu, 19 Nov 2026 21:32:11 +0000 (+0100) Subject: BUG/MEDIUM: log/tools: fix cbor binary integer encoding regression with x86_64 systems X-Git-Url: https://git.kaiwu.me/web/%22data:,//%22%22?a=commitdiff_plain;h=f1ab8bbf6fd5f0ce825ece36cd58c78cb445a506;p=haproxy.git BUG/MEDIUM: log/tools: fix cbor binary integer encoding regression with x86_64 systems A regression was introduced in commit c1abbb11f ("OPTIM: log/tools: switch from function pointer design to dual mode HEX/BIN design for CBOR encoding"). Indeed, it was assumed that for x86_64 systems that the byte order for uint64_t was already correct and that the value could be written as-is. This is totally wrong, because x86_64 is little endian while CBOR is big endian. Because of this mistake, values greater than 24 were written in reverse/incorrect order when using cbor_encode_uint64_prefix_bin(). To fix the issue, instead of completely ditching the fast-path, let's leverage htons, htonl and my_htonll for 2, 4 and 8 bytes value respectively (since the value length is known under the function), as they are less expensive than writing the value 1 byte at a time. Many thanks to Dragan Dosen and Martin Mirchev for having reported the issue. No backport needed. --- diff --git a/src/tools.c b/src/tools.c index 668fcfc00..83a28cc31 100644 --- a/src/tools.c +++ b/src/tools.c @@ -2271,10 +2271,26 @@ char *cbor_encode_uint64_prefix_bin(char *start, char *stop, uint64_t value, return NULL; #if defined(__x86_64__) - /* we can actually assume the bits are already in proper order - * so let's directly write them as-is on the wire to save CPU - * time. + /* x86_64 is little endian while CBOR expects big endian, so + * let's invert bit order, hopefully we can leverage hton{s,l}, + * given the number of bytes in , to revert all the bytes + * from at once which is less costly than writing 1 byte + * at a time. */ + switch (nb_bytes) { + case 2: + value = htons(value); + break; + case 4: + value = htonl(value); + break; + case 8: + value = my_htonll(value); + break; + default: + /* nothing to do */ + break; + } memcpy(start, &value, nb_bytes); start += nb_bytes; #else