]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
memory-util: avoid passing invalid pointer to memcmp() when length == 16
authorMike Yuan <me@yhndnzj.com>
Wed, 25 Mar 2026 17:30:14 +0000 (18:30 +0100)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Wed, 25 Mar 2026 20:49:04 +0000 (21:49 +0100)
If length is exactly 16, the loop would finish with length == 0,
but we'd carry on to the memcmp() check, where the 'p + 16' passed
would be invalid memory. memcmp() demands valid pointers even if
size is specified to 0, hence let's catch this ourselves.

src/fundamental/memory-util-fundamental.c

index 02b55251fdb2896acad223c98ca2ac924586a16e..1a64fbe514ff885704f12f762c96f545602f9e74 100644 (file)
@@ -3,6 +3,8 @@
 #include "memory-util-fundamental.h"
 
 bool memeqbyte(uint8_t byte, const void *data, size_t length) {
+        assert(data || length == 0);
+
         /* Does the buffer consist entirely of the same specific byte value?
          * Copied from https://github.com/systemd/casync/, copied in turn from
          * https://github.com/rustyrussell/ccan/blob/master/ccan/mem/mem.c#L92,
@@ -12,12 +14,12 @@ bool memeqbyte(uint8_t byte, const void *data, size_t length) {
         const uint8_t *p = data;
 
         /* Check first 16 bytes manually */
-        for (size_t i = 0; i < 16; i++, length--) {
-                if (length == 0)
-                        return true;
+        for (size_t i = 0; i < 16 && length > 0; i++, length--)
                 if (p[i] != byte)
                         return false;
-        }
+
+        if (length == 0)
+                return true;
 
         /* Now we know first 16 bytes match, memcmp() with self.  */
         return memcmp(data, p + 16, length) == 0;