]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
macro: account for negative values in DECIMAL_STR_WIDTH()
authorFrantisek Sumsal <frantisek@sumsal.cz>
Sun, 13 Mar 2022 13:45:03 +0000 (14:45 +0100)
committerFrantisek Sumsal <frantisek@sumsal.cz>
Sun, 13 Mar 2022 18:25:18 +0000 (19:25 +0100)
With negative numbers we wouldn't account for the minus sign, thus
returning a string with one character too short, triggering buffer
overflows in certain situations.

src/basic/macro.h

index aa04039e804f11171c2cee07fe3bfae0a19f5a8b..9e62f9c71c8dafcf9a5a7a39c989cd60dce0ed70 100644 (file)
@@ -319,13 +319,13 @@ static inline int __coverity_check_and_return__(int condition) {
              sizeof(type) <= 4 ? 10U :                                  \
              sizeof(type) <= 8 ? 20U : sizeof(int[-2*(sizeof(type) > 8)])))
 
-#define DECIMAL_STR_WIDTH(x)                            \
-        ({                                              \
-                typeof(x) _x_ = (x);                    \
-                size_t ans = 1;                         \
-                while ((_x_ /= 10) != 0)                \
-                        ans++;                          \
-                ans;                                    \
+#define DECIMAL_STR_WIDTH(x)                                      \
+        ({                                                        \
+                typeof(x) _x_ = (x);                              \
+                size_t ans = IS_SIGNED_INTEGER_TYPE(_x_) ? 2 : 1; \
+                while ((_x_ /= 10) != 0)                          \
+                        ans++;                                    \
+                ans;                                              \
         })
 
 #define SWAP_TWO(x, y) do {                        \