]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
string-util: allow taking SIZE_MAX as size to shorten to
authorLennart Poettering <lennart@poettering.net>
Wed, 6 Mar 2024 08:43:09 +0000 (09:43 +0100)
committerLuca Boccassi <luca.boccassi@gmail.com>
Wed, 6 Mar 2024 13:24:15 +0000 (13:24 +0000)
This is useful for two reasons:

1. it addresses a potential overflow in a graceful way

2. Gives callers the ability to just pass SIZE_MAX for a NOP

Prompted by: #31341

src/basic/string-util.c
src/test/test-string-util.c

index 2aac588118c1902d19aa68d69bf79c2917655e16..c1e7e6e62248b4cb371af8ced124890854150b56 100644 (file)
@@ -620,6 +620,9 @@ char *cellescape(char *buf, size_t len, const char *s) {
 char* strshorten(char *s, size_t l) {
         assert(s);
 
+        if (l >= SIZE_MAX-1) /* Would not change anything */
+                return s;
+
         if (strnlen(s, l+1) > l)
                 s[l] = 0;
 
index e78e299ed293c2d753589e49ac18b9278a6d1f7a..92f1083a4c5047b2958fea1f17dfcef216ae91fc 100644 (file)
@@ -299,8 +299,13 @@ TEST(ascii_strlower) {
 TEST(strshorten) {
         char s[] = "foobar";
 
+        assert_se(strlen(strshorten(s, SIZE_MAX)) == 6);
+        assert_se(strlen(strshorten(s, SIZE_MAX-1)) == 6);
+        assert_se(strlen(strshorten(s, SIZE_MAX-2)) == 6);
         assert_se(strlen(strshorten(s, 6)) == 6);
+        assert_se(strlen(strshorten(s, 7)) == 6);
         assert_se(strlen(strshorten(s, 12)) == 6);
+        assert_se(strlen(strshorten(s, 5)) == 5);
         assert_se(strlen(strshorten(s, 2)) == 2);
         assert_se(strlen(strshorten(s, 0)) == 0);
 }