ff6046
From 6bb1d52f0554f687ef27de46c0b9daac9d256d60 Mon Sep 17 00:00:00 2001
ff6046
From: Lennart Poettering <lennart@poettering.net>
ff6046
Date: Wed, 10 Oct 2018 11:34:30 +0200
ff6046
Subject: [PATCH] tree-wide: various ubsan zero size memory fixes
ff6046
ff6046
Fixes: #10346
ff6046
(cherry picked from commit 65f95765d05ddcd9e5849b68c379afa7e87d1248)
ff6046
ff6046
Resolves: #1683319
ff6046
---
ff6046
 src/basic/bitmap.c        | 2 +-
ff6046
 src/basic/util.h          | 8 +++++++-
ff6046
 src/test/test-hexdecoct.c | 2 +-
ff6046
 3 files changed, 9 insertions(+), 3 deletions(-)
ff6046
ff6046
diff --git a/src/basic/bitmap.c b/src/basic/bitmap.c
ff6046
index c17c6a7a02..a4cd6451b0 100644
ff6046
--- a/src/basic/bitmap.c
ff6046
+++ b/src/basic/bitmap.c
ff6046
@@ -206,7 +206,7 @@ bool bitmap_equal(Bitmap *a, Bitmap *b) {
ff6046
                 return true;
ff6046
 
ff6046
         common_n_bitmaps = MIN(a->n_bitmaps, b->n_bitmaps);
ff6046
-        if (memcmp(a->bitmaps, b->bitmaps, sizeof(uint64_t) * common_n_bitmaps) != 0)
ff6046
+        if (memcmp_safe(a->bitmaps, b->bitmaps, sizeof(uint64_t) * common_n_bitmaps) != 0)
ff6046
                 return false;
ff6046
 
ff6046
         c = a->n_bitmaps > b->n_bitmaps ? a : b;
ff6046
diff --git a/src/basic/util.h b/src/basic/util.h
ff6046
index b68ef25ed8..4659a21b06 100644
ff6046
--- a/src/basic/util.h
ff6046
+++ b/src/basic/util.h
ff6046
@@ -134,7 +134,13 @@ static inline int memcmp_safe(const void *s1, const void *s2, size_t n) {
ff6046
 
ff6046
 int on_ac_power(void);
ff6046
 
ff6046
-#define memzero(x,l) (memset((x), 0, (l)))
ff6046
+#define memzero(x,l)                                            \
ff6046
+        ({                                                      \
ff6046
+                size_t _l_ = (l);                               \
ff6046
+                void *_x_ = (x);                                \
ff6046
+                _l_ == 0 ? _x_ : memset(_x_, 0, _l_);           \
ff6046
+        })
ff6046
+
ff6046
 #define zero(x) (memzero(&(x), sizeof(x)))
ff6046
 
ff6046
 static inline void *mempset(void *s, int c, size_t n) {
ff6046
diff --git a/src/test/test-hexdecoct.c b/src/test/test-hexdecoct.c
ff6046
index da9f3008bb..a972ddcef7 100644
ff6046
--- a/src/test/test-hexdecoct.c
ff6046
+++ b/src/test/test-hexdecoct.c
ff6046
@@ -84,7 +84,7 @@ static void test_unhexmem_one(const char *s, size_t l, int retval) {
ff6046
                         l = strlen(s);
ff6046
 
ff6046
                 assert_se(hex = hexmem(mem, len));
ff6046
-                answer = strndupa(s, l);
ff6046
+                answer = strndupa(s ?: "", l);
ff6046
                 assert_se(streq(delete_chars(answer, WHITESPACE), hex));
ff6046
         }
ff6046
 }