]> git.kaiwu.me - haproxy.git/commitdiff
BUG/MEDIUM: log/tools: fix cbor binary integer encoding regression with x86_64 systems
authorAurelien DARRAGON <adarragon@haproxy.com>
Thu, 19 Nov 2026 21:32:11 +0000 (22:32 +0100)
committerAurelien DARRAGON <adarragon@haproxy.com>
Thu, 19 Nov 2026 21:42:31 +0000 (22:42 +0100)
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.

src/tools.c

index 668fcfc00e717c5cf9cac4568ed64cea6c066f5d..83a28cc31df8a9f783ad0069c2fce39f7c13ca9f 100644 (file)
@@ -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 <value>, to revert all the bytes
+        * from <value> 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