]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
string-util: check for short input in previous_ansi_sequence()
authorLuca Boccassi <luca.boccassi@gmail.com>
Wed, 24 Jun 2026 12:46:04 +0000 (13:46 +0100)
committerLuca Boccassi <luca.boccassi@gmail.com>
Wed, 24 Jun 2026 13:48:04 +0000 (14:48 +0100)
ellipsize_mem() scans backwards for ANSI escape sequences and calls
previous_ansi_sequence(s, t - s, ...) as t walks down toward s. When
t reaches s + 1 the helper is invoked with length == 1 and computes
'length - 2', which wraps to SIZE_MAX - 1.

Follow-up for cb558ab222f0dbda3afd985c2190f35693963ffa

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

index 125d468d47632c0d4a798a16f03bdc081b8ea18e..acd4bd87cf26d793af1f23192300a421827dc5c5 100644 (file)
@@ -285,6 +285,12 @@ static size_t previous_ansi_sequence(const char *s, size_t length, const char **
 
         /* Locate the previous ANSI sequence and save its start in *ret_where and return length. */
 
+        if (length < 2) {
+                /* Need at least two bytes for an ANSI sequence */
+                *ret_where = NULL;
+                return 0;
+        }
+
         for (size_t i = length - 2; i > 0; i--) {  /* -2 because at least two bytes are needed */
                 size_t slen = ansi_sequence_length(s + (i - 1), length - (i - 1));
                 if (slen == 0)
index 51f63963a9657eeb94b53c64ef40e4180ca808cb..970421c7abb261f4200c1a381a421844404c01b5 100644 (file)
@@ -9,6 +9,17 @@
 #include "strv.h"
 #include "tests.h"
 
+TEST(ellipsize_mem_ansi_short) {
+        _cleanup_free_ char *a = ellipsize_mem("X\x1b[m", 4, 1, 50);
+        assert_se(a);
+
+        _cleanup_free_ char *b = ellipsize_mem(" \x1b[A", 4, 1, 0);
+        assert_se(b);
+
+        _cleanup_free_ char *c = ellipsize_mem("\x1b[m", 3, 1, 50);
+        assert_se(c);
+}
+
 TEST(xsprintf) {
         char buf[5];