• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 24642716378

18 Apr 2026 10:29PM UTC coverage: 70.661% (-1.2%) from 71.872%
24642716378

push

github

web-flow
iovec-wrapper: fix memleak, rename functions for consistency, and introduce several helper functions (#41689)

227 of 237 new or added lines in 4 files covered. (95.78%)

3483 existing lines in 82 files now uncovered.

76021 of 107585 relevant lines covered (70.66%)

4993286.11 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.55
/src/basic/string-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdio.h>
4

5
#include "alloc-util.h"
6
#include "escape.h"
7
#include "extract-word.h"
8
#include "glyph-util.h"
9
#include "gunicode.h"
10
#include "locale-util.h"
11
#include "log.h"
12
#include "memory-util.h"
13
#include "memstream-util.h"
14
#include "path-util.h"
15
#include "string-util.h"
16
#include "strv.h"
17
#include "terminal-util.h"
18
#include "utf8.h"
19

20
char* first_word(const char *s, const char *word) {
3,712,905✔
21
        assert(s);
3,712,905✔
22
        assert(word);
3,712,905✔
23

24
        /* Checks if the string starts with the specified word, either followed by NUL or by whitespace.
25
         * Returns a pointer to the NUL or the first character after the whitespace. */
26

27
        if (isempty(word))
3,712,905✔
28
                return (char*) s;
29

30
        const char *p = startswith(s, word);
3,712,904✔
31
        if (!p)
3,712,904✔
32
                return NULL;
33
        if (*p == '\0')
129,267✔
34
                return (char*) p;
35

36
        const char *nw = skip_leading_chars(p, WHITESPACE);
129,266✔
37
        if (p == nw)
129,266✔
38
                return NULL;
1✔
39

40
        return (char*) nw;
41
}
42

43
char* strextendn(char **x, const char *s, size_t l) {
30,195✔
44
        assert(x);
30,195✔
45
        assert(s || l == 0);
30,195✔
46

47
        if (l > 0)
30,195✔
48
                l = strnlen(s, l); /* ignore trailing noise */
29,865✔
49

50
        if (l > 0 || !*x) {
30,195✔
51
                size_t q;
30,037✔
52
                char *m;
30,037✔
53

54
                q = strlen_ptr(*x);
30,037✔
55
                m = realloc(*x, q + l + 1);
30,037✔
56
                if (!m)
30,037✔
57
                        return NULL;
58

59
                *mempcpy_typesafe(m + q, s, l) = 0;
30,037✔
60

61
                *x = m;
30,037✔
62
        }
63

64
        return *x;
30,195✔
65
}
66

67
char* strstrip(char *s) {
6,757,234✔
68
        if (!s)
6,757,234✔
69
                return NULL;
70

71
        /* Drops trailing whitespace. Modifies the string in place. Returns pointer to first non-space character */
72

73
        return delete_trailing_chars(skip_leading_chars(s, WHITESPACE), WHITESPACE);
6,753,877✔
74
}
75

76
char* delete_chars(char *s, const char *bad) {
9✔
77
        char *f, *t;
9✔
78

79
        /* Drops all specified bad characters, regardless where in the string */
80

81
        if (!s)
9✔
82
                return NULL;
83

84
        if (!bad)
9✔
85
                bad = WHITESPACE;
×
86

87
        for (f = s, t = s; *f; f++) {
131✔
88
                if (strchr(bad, *f))
122✔
89
                        continue;
67✔
90

91
                *(t++) = *f;
55✔
92
        }
93

94
        *t = 0;
9✔
95

96
        return s;
9✔
97
}
98

99
char* delete_trailing_chars(char *s, const char *bad) {
8,379,239✔
100
        char *c = s;
8,379,239✔
101

102
        /* Drops all specified bad characters, at the end of the string */
103

104
        if (!s)
8,379,239✔
105
                return NULL;
106

107
        if (!bad)
8,379,239✔
108
                bad = WHITESPACE;
86,757✔
109

110
        for (char *p = s; *p; p++)
297,438,180✔
111
                if (!strchr(bad, *p))
289,058,941✔
112
                        c = p + 1;
277,173,936✔
113

114
        *c = 0;
8,379,239✔
115

116
        return s;
8,379,239✔
117
}
118

119
char* truncate_nl_full(char *s, size_t *ret_len) {
2,912,579✔
120
        size_t n;
2,912,579✔
121

122
        assert(s);
2,912,579✔
123

124
        n = strcspn(s, NEWLINE);
2,912,579✔
125
        s[n] = '\0';
2,912,579✔
126
        if (ret_len)
2,912,579✔
127
                *ret_len = n;
6✔
128
        return s;
2,912,579✔
129
}
130

131
char ascii_tolower(char x) {
50,879,334✔
132

133
        if (x >= 'A' && x <= 'Z')
50,879,334✔
134
                return x - 'A' + 'a';
3,498,953✔
135

136
        return x;
137
}
138

139
char ascii_toupper(char x) {
332,359✔
140

141
        if (x >= 'a' && x <= 'z')
332,359✔
142
                return x - 'a' + 'A';
202,863✔
143

144
        return x;
145
}
146

147
char* ascii_strlower(char *s) {
28,862✔
148
        assert(s);
28,862✔
149

150
        for (char *p = s; *p; p++)
184,477✔
151
                *p = ascii_tolower(*p);
155,615✔
152

153
        return s;
28,862✔
154
}
155

156
char* ascii_strupper(char *s) {
23,734✔
157
        assert(s);
23,734✔
158

159
        for (char *p = s; *p; p++)
355,963✔
160
                *p = ascii_toupper(*p);
332,229✔
161

162
        return s;
23,734✔
163
}
164

165
char* ascii_strlower_n(char *s, size_t n) {
1,795,979✔
166
        if (n <= 0)
1,795,979✔
167
                return s;
168

169
        for (size_t i = 0; i < n; i++)
15,041,400✔
170
                s[i] = ascii_tolower(s[i]);
13,245,760✔
171

172
        return s;
173
}
174

175
int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
2,503,364✔
176

177
        assert(a);
2,503,364✔
178
        assert(b);
2,503,364✔
179

180
        for (; n > 0; a++, b++, n--) {
20,646,043✔
181
                int x, y;
18,734,478✔
182

183
                x = (int) (uint8_t) ascii_tolower(*a);
18,734,478✔
184
                y = (int) (uint8_t) ascii_tolower(*b);
18,734,478✔
185

186
                if (x != y)
18,734,478✔
187
                        return x - y;
591,799✔
188
        }
189

190
        return 0;
191
}
192

193
int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
1,078,279✔
194
        int r;
1,078,279✔
195

196
        r = ascii_strcasecmp_n(a, b, MIN(n, m));
1,078,279✔
197
        if (r != 0)
1,078,279✔
198
                return r;
199

200
        return CMP(n, m);
948,266✔
201
}
202

203
bool chars_intersect(const char *a, const char *b) {
12,238✔
204
        /* Returns true if any of the chars in a are in b. */
205
        for (const char *p = a; *p; p++)
175,988✔
206
                if (strchr(b, *p))
163,763✔
207
                        return true;
208

209
        return false;
210
}
211

212
bool string_has_cc(const char *p, const char *ok) {
13,975,980✔
213
        assert(p);
13,975,980✔
214

215
        /*
216
         * Check if a string contains control characters. If 'ok' is
217
         * non-NULL it may be a string containing additional CCs to be
218
         * considered OK.
219
         */
220

221
        for (const char *t = p; *t; t++) {
252,547,885✔
222
                if (ok && strchr(ok, *t))
238,571,927✔
223
                        continue;
8✔
224

225
                if (char_is_cc(*t))
238,571,919✔
226
                        return true;
227
        }
228

229
        return false;
230
}
231

232
static int write_ellipsis(char *buf, bool unicode) {
4,364✔
233
        const char *s = glyph_full(GLYPH_ELLIPSIS, unicode);
4,364✔
234
        assert(strlen(s) == 3);
4,364✔
235
        memcpy(buf, s, 3);
4,364✔
236
        return 3;
4,364✔
237
}
238

239
static size_t ansi_sequence_length(const char *s, size_t len) {
6,334✔
240
        assert(s);
6,334✔
241

242
        if (len < 2)
6,334✔
243
                return 0;
244

245
        if (s[0] != 0x1B)  /* ASCII 27, aka ESC, aka Ctrl-[ */
6,242✔
246
                return 0;  /* Not the start of a sequence */
247

248
        if (s[1] == 0x5B) { /* [, start of CSI sequence */
903✔
249
                size_t i = 2;
902✔
250

251
                if (i == len)
902✔
252
                        return 0;
253

254
                while (s[i] >= 0x30 && s[i] <= 0x3F) /* Parameter bytes */
9,245✔
255
                        if (++i == len)
8,343✔
256
                                return 0;
257
                while (s[i] >= 0x20 && s[i] <= 0x2F) /* Intermediate bytes */
902✔
258
                        if (++i == len)
×
259
                                return 0;
260
                if (s[i] >= 0x40 && s[i] <= 0x7E) /* Final byte */
902✔
261
                        return i + 1;
902✔
262
                return 0;  /* Bad sequence */
263

264
        } else if (s[1] >= 0x40 && s[1] <= 0x5F) /* other non-CSI Fe sequence */
1✔
265
                return 2;
×
266

267
        return 0;  /* Bad escape? */
268
}
269

270
static bool string_has_ansi_sequence(const char *s, size_t len) {
7,894✔
271
        const char *t = s;
7,894✔
272

273
        while ((t = memchr(t, 0x1B, len - (t - s)))) {
7,895✔
274
                if (ansi_sequence_length(t, len - (t - s)) > 0)
154✔
275
                        return true;
276
                t++;
1✔
277
        }
278
        return false;
279
}
280

281
static size_t previous_ansi_sequence(const char *s, size_t length, const char **ret_where) {
265✔
282

283
        assert(s);
265✔
284
        assert(ret_where);
265✔
285

286
        /* Locate the previous ANSI sequence and save its start in *ret_where and return length. */
287

288
        for (size_t i = length - 2; i > 0; i--) {  /* -2 because at least two bytes are needed */
3,442✔
289
                size_t slen = ansi_sequence_length(s + (i - 1), length - (i - 1));
3,440✔
290
                if (slen == 0)
3,440✔
291
                        continue;
3,177✔
292

293
                *ret_where = s + (i - 1);
263✔
294
                return slen;
263✔
295
        }
296

297
        *ret_where = NULL;
2✔
298
        return 0;
2✔
299
}
300

301
static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4,344✔
302
        size_t x, need_space, suffix_len;
4,344✔
303
        char *t;
4,344✔
304

305
        assert(s);
4,344✔
306
        assert(percent <= 100);
4,344✔
307
        assert(new_length != SIZE_MAX);
4,344✔
308

309
        if (old_length <= new_length)
4,344✔
310
                return strndup(s, old_length);
1,769✔
311

312
        /* Special case short ellipsations */
313
        switch (new_length) {
2,575✔
314

315
        case 0:
×
316
                return strdup("");
×
317

318
        case 1:
65✔
319
                if (is_locale_utf8())
65✔
320
                        return strdup("…");
65✔
321
                else
322
                        return strdup(".");
×
323

324
        case 2:
35✔
325
                if (!is_locale_utf8())
35✔
326
                        return strdup("..");
×
327
                break;
328
        }
329

330
        /* Calculate how much space the ellipsis will take up. If we are in UTF-8 mode we only need space for one
331
         * character ("…"), otherwise for three characters ("..."). Note that in both cases we need 3 bytes of storage,
332
         * either for the UTF-8 encoded character or for three ASCII characters. */
333
        need_space = is_locale_utf8() ? 1 : 3;
2,510✔
334

335
        t = new(char, new_length+3);
2,510✔
336
        if (!t)
2,510✔
337
                return NULL;
338

339
        assert(new_length >= need_space);
2,510✔
340

341
        x = ((new_length - need_space) * percent + 50) / 100;
2,510✔
342
        assert(x <= new_length - need_space);
2,510✔
343

344
        write_ellipsis(mempcpy(t, s, x), /* unicode= */ false);
2,510✔
345
        suffix_len = new_length - x - need_space;
2,510✔
346
        memcpy(t + x + 3, s + old_length - suffix_len, suffix_len);
2,510✔
347
        *(t + x + 3 + suffix_len) = '\0';
2,510✔
348

349
        return t;
2,510✔
350
}
351

352
char* ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
8,065✔
353
        size_t x, k, len, len2;
8,065✔
354
        const char *i, *j;
8,065✔
355
        int r;
8,065✔
356

357
        /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
358
         * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
359
         * strings.
360
         *
361
         * Ellipsation is done in a locale-dependent way:
362
         * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
363
         * 2. Otherwise, a unicode ellipsis is used ("…")
364
         *
365
         * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
366
         * the current locale is UTF-8.
367
         */
368

369
        assert(s);
8,065✔
370
        assert(percent <= 100);
8,065✔
371

372
        if (new_length == SIZE_MAX)
8,065✔
373
                return strndup(s, old_length);
×
374

375
        if (new_length == 0)
8,065✔
376
                return strdup("");
171✔
377

378
        bool has_ansi_seq = string_has_ansi_sequence(s, old_length);
7,894✔
379

380
        /* If no multibyte characters or ANSI sequences, use ascii_ellipsize_mem for speed */
381
        if (!has_ansi_seq && ascii_is_valid_n(s, old_length))
7,894✔
382
                return ascii_ellipsize_mem(s, old_length, new_length, percent);
4,344✔
383

384
        x = (new_length - 1) * percent / 100;
3,550✔
385
        assert(x <= new_length - 1);
3,550✔
386

387
        k = 0;
388
        for (i = s; i < s + old_length; ) {
49,782✔
389
                size_t slen = has_ansi_seq ? ansi_sequence_length(i, old_length - (i - s)) : 0;
48,590✔
390
                if (slen > 0) {
1,011✔
391
                        i += slen;
224✔
392
                        continue;  /* ANSI sequences don't take up any space in output */
224✔
393
                }
394

395
                char32_t c;
48,366✔
396
                r = utf8_encoded_to_unichar(i, &c);
48,366✔
397
                if (r < 0)
48,366✔
398
                        return NULL;
×
399

400
                int w = unichar_iswide(c) ? 2 : 1;
48,366✔
401
                if (k + w > x)
48,366✔
402
                        break;
403

404
                k += w;
46,008✔
405
                i += r;
46,008✔
406
        }
407

408
        const char *ansi_start = s + old_length;
3,550✔
409
        size_t ansi_len = 0;
3,550✔
410

411
        for (const char *t = j = s + old_length; t > i && k < new_length; ) {
13,219✔
412
                char32_t c;
9,755✔
413
                int w;
9,755✔
414
                const char *tt;
9,755✔
415

416
                if (has_ansi_seq && ansi_start >= t)
9,755✔
417
                        /* Figure out the previous ANSI sequence, if any */
418
                        ansi_len = previous_ansi_sequence(s, t - s, &ansi_start);
265✔
419

420
                /* If the sequence extends all the way to the current position, skip it. */
421
                if (has_ansi_seq && ansi_len > 0 && ansi_start + ansi_len == t) {
9,755✔
422
                        t = ansi_start;
112✔
423
                        continue;
112✔
424
                }
425

426
                tt = utf8_prev_char(t);
9,643✔
427
                r = utf8_encoded_to_unichar(tt, &c);
9,643✔
428
                if (r < 0)
9,643✔
429
                        return NULL;
×
430

431
                w = unichar_iswide(c) ? 2 : 1;
9,643✔
432
                if (k + w > new_length)
9,643✔
433
                        break;
434

435
                k += w;
9,557✔
436
                j = t = tt;  /* j should always point to the first "real" character */
9,557✔
437
        }
438

439
        /* We don't actually need to ellipsize */
440
        if (i >= j)
3,550✔
441
                return memdup_suffix0(s, old_length);
1,720✔
442

443
        if (k >= new_length) {
1,830✔
444
                /* Make space for ellipsis, if required and possible. We know that the edge character is not
445
                 * part of an ANSI sequence (because then we'd skip it). If the last character we looked at
446
                 * was wide, we don't need to make space. */
447
                if (j < s + old_length)
1,744✔
448
                        j = utf8_next_char(j);
1,744✔
449
                else if (i > s)
×
450
                        i = utf8_prev_char(i);
×
451
        }
452

453
        len = i - s;
1,830✔
454
        len2 = s + old_length - j;
1,830✔
455

456
        /* If we have ANSI, allow the same length as the source string + ellipsis. It'd be too involved to
457
         * figure out what exact space is needed. Strings with ANSI sequences are most likely to be fairly
458
         * short anyway. */
459
        size_t alloc_len = has_ansi_seq ? old_length + 3 + 1 : len + 3 + len2 + 1;
1,830✔
460

461
        char *e = new(char, alloc_len);
1,830✔
462
        if (!e)
1,830✔
463
                return NULL;
464

465
        memcpy_safe(e, s, len);
1,830✔
466
        write_ellipsis(e + len, /* unicode= */ true);
1,830✔
467

468
        char *dst = e + len + 3;
1,830✔
469

470
        if (has_ansi_seq)
1,830✔
471
                /* Copy over any ANSI sequences in full */
472
                for (const char *p = s + len; p < j; ) {
1,864✔
473
                        size_t slen = ansi_sequence_length(p, j - p);
1,729✔
474
                        if (slen > 0) {
1,729✔
475
                                dst = mempcpy(dst, p, slen);
262✔
476
                                p += slen;
262✔
477
                        } else
478
                                p = utf8_next_char(p);
1,467✔
479
                }
480

481
        memcpy_safe(dst, j, len2);
1,830✔
482
        dst[len2] = '\0';
1,830✔
483

484
        return e;
1,830✔
485
}
486

487
char* cellescape(char *buf, size_t len, const char *s) {
44,703✔
488
        /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
489
         * characters are copied as they are, everything else is escaped. The result
490
         * is different then if escaping and ellipsization was performed in two
491
         * separate steps, because each sequence is either stored in full or skipped.
492
         *
493
         * This function should be used for logging about strings which expected to
494
         * be plain ASCII in a safe way.
495
         *
496
         * An ellipsis will be used if s is too long. It was always placed at the
497
         * very end.
498
         */
499

500
        size_t i = 0, last_char_width[4] = {}, k = 0;
44,703✔
501

502
        assert(buf);
44,703✔
503
        assert(len > 0); /* at least a terminating NUL */
44,703✔
504
        assert(s);
44,703✔
505

506
        for (;;) {
983,193✔
507
                char four[4];
513,948✔
508
                int w;
513,948✔
509

510
                if (*s == 0) /* terminating NUL detected? then we are done! */
513,948✔
511
                        goto done;
44,667✔
512

513
                w = cescape_char(*s, four);
469,281✔
514
                if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
469,281✔
515
                                      * ellipsize at the previous location */
516
                        break;
517

518
                /* OK, there was space, let's add this escaped character to the buffer */
519
                memcpy(buf + i, four, w);
469,245✔
520
                i += w;
469,245✔
521

522
                /* And remember its width in the ring buffer */
523
                last_char_width[k] = w;
469,245✔
524
                k = (k + 1) % 4;
469,245✔
525

526
                s++;
469,245✔
527
        }
528

529
        /* Ellipsation is necessary. This means we might need to truncate the string again to make space for 4
530
         * characters ideally, but the buffer is shorter than that in the first place take what we can get */
531
        for (size_t j = 0; j < ELEMENTSOF(last_char_width); j++) {
81✔
532

533
                if (i + 4 <= len) /* nice, we reached our space goal */
81✔
534
                        break;
535

536
                k = k == 0 ? 3 : k - 1;
57✔
537
                if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
57✔
538
                        break;
539

540
                assert(i >= last_char_width[k]);
45✔
541
                i -= last_char_width[k];
45✔
542
        }
543

544
        if (i + 4 <= len) /* yay, enough space */
36✔
545
                i += write_ellipsis(buf + i, /* unicode= */ false);
24✔
546
        else if (i + 3 <= len) { /* only space for ".." */
12✔
547
                buf[i++] = '.';
4✔
548
                buf[i++] = '.';
4✔
549
        } else if (i + 2 <= len) /* only space for a single "." */
8✔
550
                buf[i++] = '.';
4✔
551
        else
552
                assert(i + 1 <= len);
4✔
553

554
done:
4✔
555
        buf[i] = '\0';
44,703✔
556
        return buf;
44,703✔
557
}
558

559
char* strshorten(char *s, size_t l) {
360,242✔
560
        assert(s);
360,242✔
561

562
        if (l >= SIZE_MAX-1) /* Would not change anything */
360,242✔
563
                return s;
564

565
        if (strnlen(s, l+1) > l)
360,240✔
566
                s[l] = 0;
110✔
567

568
        return s;
569
}
570

571
int strgrowpad0(char **s, size_t l) {
26✔
572
        size_t sz;
26✔
573

574
        assert(s);
26✔
575

576
        if (*s) {
26✔
577
                sz = strlen(*s) + 1;
26✔
578
                if (sz >= l) /* never shrink */
26✔
579
                        return 0;
580
        } else
581
                sz = 0;
582

583
        char *q = realloc(*s, l);
26✔
584
        if (!q)
26✔
585
                return -ENOMEM;
586

587
        *s = q;
26✔
588

589
        memzero(*s + sz, l - sz);
26✔
590
        return 0;
591
}
592

593
char* strreplace(const char *text, const char *old_string, const char *new_string) {
4,816✔
594
        size_t l, old_len, new_len;
4,816✔
595
        char *t, *ret = NULL;
4,816✔
596
        const char *f;
4,816✔
597

598
        assert(old_string);
4,816✔
599
        assert(new_string);
4,816✔
600

601
        if (!text)
4,816✔
602
                return NULL;
4,816✔
603

604
        old_len = strlen(old_string);
4,815✔
605
        new_len = strlen(new_string);
4,815✔
606

607
        l = strlen(text);
4,815✔
608
        if (!GREEDY_REALLOC(ret, l+1))
4,815✔
609
                return NULL;
610

611
        f = text;
4,815✔
612
        t = ret;
4,815✔
613
        while (*f) {
166,146✔
614
                size_t d, nl;
161,331✔
615

616
                if (!startswith(f, old_string)) {
161,331✔
617
                        *(t++) = *(f++);
159,127✔
618
                        continue;
159,127✔
619
                }
620

621
                d = t - ret;
2,204✔
622
                nl = l - old_len + new_len;
2,204✔
623

624
                if (!GREEDY_REALLOC(ret, nl + 1))
2,204✔
625
                        return mfree(ret);
×
626

627
                l = nl;
2,204✔
628
                t = ret + d;
2,204✔
629

630
                t = stpcpy(t, new_string);
2,204✔
631
                f += old_len;
2,204✔
632
        }
633

634
        *t = 0;
4,815✔
635
        return ret;
4,815✔
636
}
637

638
static void advance_offsets(
406✔
639
                ssize_t diff,
640
                size_t offsets[2], /* note: we can't use [static 2] here, since this may be NULL */
641
                size_t shift[static 2],
642
                size_t size) {
643

644
        if (!offsets)
406✔
645
                return;
646

647
        assert(shift);
396✔
648

649
        if ((size_t) diff < offsets[0])
396✔
650
                shift[0] += size;
×
651
        if ((size_t) diff < offsets[1])
396✔
652
                shift[1] += size;
×
653
}
654

655
char* strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
170,924✔
656
        const char *begin = NULL;
170,924✔
657
        enum {
170,924✔
658
                STATE_OTHER,
659
                STATE_ESCAPE,
660
                STATE_CSI,
661
                STATE_OSC,
662
                STATE_OSC_CLOSING,
663
        } state = STATE_OTHER;
170,924✔
664
        _cleanup_(memstream_done) MemStream m = {};
170,924✔
665
        size_t isz, shift[2] = {}, n_carriage_returns = 0;
170,924✔
666
        FILE *f;
170,924✔
667

668
        assert(ibuf);
170,924✔
669
        assert(*ibuf);
170,924✔
670
        POINTER_MAY_BE_NULL(_isz);
170,924✔
671

672
        /* This does three things:
673
         *
674
         * 1. Replaces TABs by 8 spaces
675
         * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
676
         * 3. Strips ANSI operating system sequences (OSC), i.e. ESC ']' … ST sequences
677
         * 4. Strip trailing \r characters (since they would "move the cursor", but have no
678
         *    other effect).
679
         *
680
         * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
681
         * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
682
         * supposed to suppress the most basic formatting noise, but nothing else.
683
         *
684
         * Why care for OSC sequences? Well, to undo what terminal_urlify() and friends generate. */
685

686
        isz = _isz ? *_isz : strlen(*ibuf);
170,924✔
687

688
        /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
689
         * created f here and it doesn't leave our scope. */
690
        f = memstream_init(&m);
170,924✔
691
        if (!f)
170,924✔
692
                return NULL;
693

694
        for (const char *i = *ibuf; i < *ibuf + isz + 1; i++) {
20,444,101✔
695

696
                bool eot = i >= *ibuf + isz;
20,273,177✔
697

698
                switch (state) {
20,273,177✔
699

700
                case STATE_OTHER:
20,272,926✔
701
                        if (eot)
20,272,926✔
702
                                break;
703

704
                        if (*i == '\r') {
20,102,002✔
705
                                n_carriage_returns++;
7✔
706
                                break;
7✔
707
                        } else if (*i == '\n')
20,101,995✔
708
                                /* Ignore carriage returns before new line */
709
                                n_carriage_returns = 0;
23✔
710
                        for (; n_carriage_returns > 0; n_carriage_returns--)
20,101,997✔
711
                                fputc('\r', f);
2✔
712

713
                        if (*i == '\x1B')
20,101,995✔
714
                                state = STATE_ESCAPE;
715
                        else if (*i == '\t') {
20,101,961✔
716
                                fputs("        ", f);
401✔
717
                                advance_offsets(i - *ibuf, highlight, shift, 7);
401✔
718
                        } else
719
                                fputc(*i, f);
20,101,560✔
720

721
                        break;
722

723
                case STATE_ESCAPE:
34✔
724
                        assert(n_carriage_returns == 0);
34✔
725

726
                        if (eot) {
34✔
727
                                fputc('\x1B', f);
×
728
                                advance_offsets(i - *ibuf, highlight, shift, 1);
×
729
                                break;
730
                        } else if (*i == '[') { /* ANSI CSI */
34✔
731
                                state = STATE_CSI;
31✔
732
                                begin = i + 1;
31✔
733
                        } else if (*i == ']') { /* ANSI OSC */
3✔
734
                                state = STATE_OSC;
3✔
735
                                begin = i + 1;
3✔
736
                        } else {
737
                                fputc('\x1B', f);
×
738
                                fputc(*i, f);
×
739
                                advance_offsets(i - *ibuf, highlight, shift, 1);
×
740
                                state = STATE_OTHER;
×
741
                        }
742

743
                        break;
744

745
                case STATE_CSI:
191✔
746
                        assert(n_carriage_returns == 0);
191✔
747

748
                        if (eot || !strchr(DIGITS ";:m", *i)) { /* EOT or invalid chars in sequence */
191✔
749
                                fputc('\x1B', f);
5✔
750
                                fputc('[', f);
5✔
751
                                advance_offsets(i - *ibuf, highlight, shift, 2);
5✔
752
                                state = STATE_OTHER;
5✔
753
                                i = begin-1;
5✔
754
                        } else if (*i == 'm')
186✔
755
                                state = STATE_OTHER;
26✔
756

757
                        break;
758

759
                case STATE_OSC:
24✔
760
                        assert(n_carriage_returns == 0);
24✔
761

762
                        /* There are three kinds of OSC terminators: \x07, \x1b\x5c or \x9c. We only support
763
                         * the first two, because the last one is a valid UTF-8 codepoint and hence creates
764
                         * an ambiguity (many Terminal emulators refuse to support it as well). */
765
                        if (eot || (!IN_SET(*i, '\x07', '\x1b') && !osc_char_is_valid(*i))) { /* EOT or invalid chars in sequence */
24✔
766
                                fputc('\x1B', f);
×
767
                                fputc(']', f);
×
768
                                advance_offsets(i - *ibuf, highlight, shift, 2);
×
769
                                state = STATE_OTHER;
×
770
                                i = begin-1;
×
771
                        } else if (*i == '\x07') /* Single character ST */
24✔
772
                                state = STATE_OTHER;
773
                        else if (*i == '\x1B')
23✔
774
                                state = STATE_OSC_CLOSING;
2✔
775

776
                        break;
777

778
                case STATE_OSC_CLOSING:
2✔
779
                        if (eot || *i != '\x5c') { /* EOT or incomplete two-byte ST in sequence */
2✔
780
                                fputc('\x1B', f);
×
781
                                fputc(']', f);
×
782
                                advance_offsets(i - *ibuf, highlight, shift, 2);
×
783
                                state = STATE_OTHER;
×
784
                                i = begin-1;
×
785
                        } else if (*i == '\x5c')
786
                                state = STATE_OTHER;
787

788
                        break;
789
                }
790
        }
791

792
        char *obuf;
170,924✔
793
        if (memstream_finalize(&m, &obuf, _isz) < 0)
170,924✔
794
                return NULL;
795

796
        free_and_replace(*ibuf, obuf);
170,924✔
797

798
        if (highlight) {
170,924✔
799
                highlight[0] += shift[0];
170,897✔
800
                highlight[1] += shift[1];
170,897✔
801
        }
802

803
        return *ibuf;
170,924✔
804
}
805

806
char* strextendv_with_separator(char **x, const char *separator, va_list ap) {
23,930,561✔
807
        _cleanup_free_ char *buffer = NULL;
23,930,561✔
808
        size_t f, l, l_separator;
23,930,561✔
809
        bool need_separator;
23,930,561✔
810
        char *nr, *p;
23,930,561✔
811

812
        if (!x)
23,930,561✔
813
                x = &buffer;
22,561,737✔
814

815
        l = f = strlen_ptr(*x);
23,930,561✔
816

817
        need_separator = !isempty(*x);
23,930,561✔
818
        l_separator = strlen_ptr(separator);
23,930,561✔
819

820
        va_list aq;
23,930,561✔
821
        va_copy(aq, ap);
23,930,561✔
822
        for (const char *t;;) {
90,850,368✔
823
                size_t n;
90,850,368✔
824

825
                t = va_arg(aq, const char *);
90,850,368✔
826
                if (!t)
90,850,368✔
827
                        break;
828
                if (t == POINTER_MAX)
66,919,807✔
829
                        continue;
3✔
830

831
                n = strlen(t);
66,919,804✔
832

833
                if (need_separator)
66,919,804✔
834
                        n += l_separator;
43,765,164✔
835

836
                if (n >= SIZE_MAX - l) {
66,919,804✔
837
                        va_end(aq);
×
838
                        return NULL;
×
839
                }
840

841
                l += n;
66,919,804✔
842
                need_separator = true;
66,919,804✔
843
        }
844
        va_end(aq);
23,930,561✔
845

846
        need_separator = !isempty(*x);
23,930,561✔
847

848
        nr = realloc(*x, GREEDY_ALLOC_ROUND_UP(l+1));
23,930,561✔
849
        if (!nr)
23,930,561✔
850
                return NULL;
851

852
        *x = nr;
23,930,561✔
853
        p = nr + f;
23,930,561✔
854

855
        for (;;) {
90,850,368✔
856
                const char *t;
90,850,368✔
857

858
                t = va_arg(ap, const char *);
90,850,368✔
859
                if (!t)
90,850,368✔
860
                        break;
861
                if (t == POINTER_MAX)
66,919,807✔
862
                        continue;
3✔
863

864
                if (need_separator && separator)
66,919,804✔
865
                        p = stpcpy(p, separator);
162,401✔
866

867
                p = stpcpy(p, t);
66,919,804✔
868

869
                need_separator = true;
66,919,804✔
870
        }
871

872
        assert(p == nr + l);
23,930,561✔
873
        *p = 0;
23,930,561✔
874

875
        /* If no buffer to extend was passed in return the start of the buffer */
876
        if (buffer)
23,930,561✔
877
                return TAKE_PTR(buffer);
22,561,737✔
878

879
        /* Otherwise we extended the buffer: return the end */
880
        return p;
881
}
882

883
char* strextend_with_separator_internal(char **x, const char *separator, ...) {
23,877,473✔
884
        va_list ap;
23,877,473✔
885
        char *ret;
23,877,473✔
886

887
        va_start(ap, separator);
23,877,473✔
888
        ret = strextendv_with_separator(x, separator, ap);
23,877,473✔
889
        va_end(ap);
23,877,473✔
890

891
        return ret;
23,877,473✔
892
}
893

894
int strextendf_with_separator(char **x, const char *separator, const char *format, ...) {
18,535✔
895
        size_t m, a, l_separator;
18,535✔
896
        va_list ap;
18,535✔
897
        int l;
18,535✔
898

899
        /* Appends a formatted string to the specified string. Don't use this in inner loops, since then
900
         * we'll spend a tonload of time in determining the length of the string passed in, over and over
901
         * again. */
902

903
        assert(x);
18,535✔
904
        assert(format);
18,535✔
905

906
        l_separator = isempty(*x) ? 0 : strlen_ptr(separator);
32,196✔
907

908
        /* Let's try to use the allocated buffer, if there's room at the end still. Otherwise let's extend by 64 chars. */
909
        if (*x) {
18,535✔
910
                m = strlen(*x);
13,661✔
911
                a = MALLOC_SIZEOF_SAFE(*x);
13,661✔
912
                assert(a >= m + 1);
13,661✔
913
        } else
914
                m = a = 0;
915

916
        if (a - m < 17 + l_separator) { /* if there's less than 16 chars space, then enlarge the buffer first */
18,535✔
917
                char *n;
11,334✔
918

919
                if (_unlikely_(l_separator > SIZE_MAX - 64)) /* overflow check #1 */
11,334✔
920
                        return -ENOMEM;
18,535✔
921
                if (_unlikely_(m > SIZE_MAX - 64 - l_separator)) /* overflow check #2 */
11,334✔
922
                        return -ENOMEM;
923

924
                n = realloc(*x, m + 64 + l_separator);
11,334✔
925
                if (!n)
11,334✔
926
                        return -ENOMEM;
927

928
                *x = n;
11,334✔
929
                a = MALLOC_SIZEOF_SAFE(*x);
11,334✔
930
        }
931

932
        /* Now, let's try to format the string into it */
933
        memcpy_safe(*x + m, separator, l_separator);
18,535✔
934
        va_start(ap, format);
18,535✔
935
        l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
18,535✔
936
        va_end(ap);
18,535✔
937

938
        assert(l >= 0);
18,535✔
939

940
        if ((size_t) l < a - m - l_separator) {
18,535✔
941
                char *n;
18,026✔
942

943
                /* Nice! This worked. We are done. But first, let's return the extra space we don't
944
                 * need. This should be a cheap operation, since we only lower the allocation size here,
945
                 * never increase. */
946
                n = realloc(*x, m + (size_t) l + l_separator + 1);
18,026✔
947
                if (n)
18,026✔
948
                        *x = n;
18,026✔
949
        } else {
950
                char *n;
509✔
951

952
                /* Wasn't enough. Then let's allocate exactly what we need. */
953

954
                if (_unlikely_((size_t) l > SIZE_MAX - (l_separator + 1))) /* overflow check #1 */
509✔
955
                        goto oom;
×
956
                if (_unlikely_(m > SIZE_MAX - ((size_t) l + l_separator + 1))) /* overflow check #2 */
509✔
957
                        goto oom;
×
958

959
                a = m + (size_t) l + l_separator + 1;
509✔
960
                n = realloc(*x, a);
509✔
961
                if (!n)
509✔
962
                        goto oom;
×
963
                *x = n;
509✔
964

965
                va_start(ap, format);
509✔
966
                l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
509✔
967
                va_end(ap);
509✔
968

969
                assert((size_t) l < a - m - l_separator);
509✔
970
        }
971

972
        return 0;
973

974
oom:
×
975
        /* truncate the bytes added after memcpy_safe() again */
976
        (*x)[m] = 0;
×
977
        return -ENOMEM;
×
978
}
979

980
char* strrep(const char *s, size_t n) {
12✔
981
        char *ret, *p;
12✔
982
        size_t l;
12✔
983

984
        assert(s);
12✔
985

986
        l = strlen(s);
12✔
987
        if (!MUL_ASSIGN_SAFE(&l, n))
12✔
988
                return NULL;
12✔
989
        if (!INC_SAFE(&l, 1))
11✔
990
                return NULL;
991

992
        p = ret = malloc(l);
11✔
993
        if (!ret)
11✔
994
                return NULL;
995

996
        for (size_t i = 0; i < n; i++)
40,337✔
997
                p = stpcpy(p, s);
40,326✔
998

999
        *p = 0;
11✔
1000
        return ret;
11✔
1001
}
1002

1003
int split_pair(const char *s, const char *sep, char **ret_first, char **ret_second) {
1,606✔
1004
        assert(s);
1,606✔
1005
        assert(!isempty(sep));
1,606✔
1006
        assert(ret_first);
1,606✔
1007
        assert(ret_second);
1,606✔
1008

1009
        const char *x = strstr(s, sep);
1,606✔
1010
        if (!x)
1,606✔
1011
                return -EINVAL;
1,606✔
1012

1013
        _cleanup_free_ char *a = strndup(s, x - s);
266✔
1014
        if (!a)
266✔
1015
                return -ENOMEM;
1016

1017
        _cleanup_free_ char *b = strdup(x + strlen(sep));
266✔
1018
        if (!b)
266✔
1019
                return -ENOMEM;
1020

1021
        *ret_first = TAKE_PTR(a);
266✔
1022
        *ret_second = TAKE_PTR(b);
266✔
1023
        return 0;
266✔
1024
}
1025

1026
int free_and_strdup(char **p, const char *s) {
2,213,717✔
1027
        char *t;
2,213,717✔
1028

1029
        assert(p);
2,213,717✔
1030

1031
        /* Replaces a string pointer with a strdup()ed new string,
1032
         * possibly freeing the old one. */
1033

1034
        if (streq_ptr(*p, s))
2,213,717✔
1035
                return 0;
2,213,717✔
1036

1037
        if (s) {
1,759,733✔
1038
                t = strdup(s);
1,751,646✔
1039
                if (!t)
1,751,646✔
1040
                        return -ENOMEM;
1041
        } else
1042
                t = NULL;
1043

1044
        free_and_replace(*p, t);
1,759,733✔
1045

1046
        return 1;
1,759,733✔
1047
}
1048

1049
int free_and_strdup_warn(char **p, const char *s) {
65,192✔
1050
        int r;
65,192✔
1051

1052
        r = free_and_strdup(p, s);
65,192✔
1053
        if (r < 0)
65,192✔
UNCOV
1054
                return log_oom();
×
1055
        return r;
1056
}
1057

1058
int free_and_strndup(char **p, const char *s, size_t l) {
71,245✔
1059
        char *t;
71,245✔
1060

1061
        assert(p);
71,245✔
1062
        assert(s || l == 0);
71,245✔
1063

1064
        /* Replaces a string pointer with a strndup()ed new string,
1065
         * freeing the old one. */
1066

1067
        if (!*p && !s)
71,245✔
1068
                return 0;
71,245✔
1069

1070
        if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
71,245✔
1071
                return 0;
1072

1073
        if (s) {
33,205✔
1074
                t = strndup(s, l);
33,264✔
1075
                if (!t)
33,264✔
1076
                        return -ENOMEM;
1077
        } else
1078
                t = NULL;
1079

1080
        free_and_replace(*p, t);
33,265✔
1081
        return 1;
33,265✔
1082
}
1083

1084
int strdup_to_full(char **ret, const char *src) {
811,487✔
1085
        if (!src) {
811,487✔
1086
                if (ret)
278,058✔
1087
                        *ret = NULL;
278,057✔
1088

1089
                return 0;
278,058✔
1090
        } else {
1091
                if (ret) {
533,429✔
1092
                        char *t = strdup(src);
533,427✔
1093
                        if (!t)
533,427✔
1094
                                return -ENOMEM;
1095
                        *ret = t;
533,427✔
1096
                }
1097

1098
                return 1;
533,429✔
1099
        }
1100
};
1101

1102
bool string_is_safe(const char *p) {
205,360✔
1103
        if (!p)
205,360✔
1104
                return false;
1105

1106
        /* Checks if the specified string contains no quotes or control characters */
1107

1108
        for (const char *t = p; *t; t++) {
2,424,258✔
1109
                if (*t > 0 && *t < ' ') /* no control characters */
2,218,911✔
1110
                        return false;
1111

1112
                if (strchr(QUOTES "\\\x7f", *t))
2,218,903✔
1113
                        return false;
1114
        }
1115

1116
        return true;
1117
}
1118

UNCOV
1119
bool string_is_safe_ascii(const char *p) {
×
UNCOV
1120
        return ascii_is_valid(p) && string_is_safe(p);
×
1121
}
1122

1123
char* str_realloc(char *p) {
44,544✔
1124
        /* Reallocate *p to actual size. Ignore failure, and return the original string on error. */
1125

1126
        if (!p)
44,544✔
1127
                return NULL;
1128

1129
        return realloc(p, strlen(p) + 1) ?: p;
44,544✔
1130
}
1131

1132
char* string_erase(char *x) {
119✔
1133
        if (!x)
119✔
1134
                return NULL;
1135

1136
        /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1137
         * used them. */
1138
        explicit_bzero_safe(x, strlen(x));
119✔
1139
        return x;
119✔
1140
}
1141

1142
int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
300✔
1143
        const char *p = s, *e = s;
300✔
1144
        bool truncation_applied = false;
300✔
1145
        char *copy;
300✔
1146
        size_t n = 0;
300✔
1147

1148
        assert(s);
300✔
1149
        assert(ret);
300✔
1150

1151
        /* Truncate after the specified number of lines. Returns > 0 if a truncation was applied or == 0 if
1152
         * there were fewer lines in the string anyway. Trailing newlines on input are ignored, and not
1153
         * generated either. */
1154

1155
        for (;;) {
530✔
1156
                size_t k;
415✔
1157

1158
                k = strcspn(p, "\n");
415✔
1159

1160
                if (p[k] == 0) {
415✔
1161
                        if (k == 0) /* final empty line */
268✔
1162
                                break;
1163

1164
                        if (n >= n_lines) /* above threshold */
243✔
1165
                                break;
1166

1167
                        e = p + k; /* last line to include */
226✔
1168
                        break;
226✔
1169
                }
1170

1171
                assert(p[k] == '\n');
147✔
1172

1173
                if (n >= n_lines)
147✔
1174
                        break;
1175

1176
                if (k > 0)
115✔
1177
                        e = p + k;
92✔
1178

1179
                p += k + 1;
115✔
1180
                n++;
115✔
1181
        }
1182

1183
        /* e points after the last character we want to keep */
1184
        if (isempty(e))
300✔
1185
                copy = strdup(s);
230✔
1186
        else {
1187
                if (!in_charset(e, "\n")) /* We only consider things truncated if we remove something that
70✔
1188
                                           * isn't a new-line or a series of them */
1189
                        truncation_applied = true;
42✔
1190

1191
                copy = strndup(s, e - s);
70✔
1192
        }
1193
        if (!copy)
300✔
1194
                return -ENOMEM;
1195

1196
        *ret = copy;
300✔
1197
        return truncation_applied;
300✔
1198
}
1199

1200
int string_extract_line(const char *s, size_t i, char **ret) {
205,014✔
1201
        const char *p = s;
205,014✔
1202
        size_t c = 0;
205,014✔
1203

1204
        assert(ret);
205,014✔
1205

1206
        /* Extract the i'nth line from the specified string. Returns > 0 if there are more lines after that,
1207
         * and == 0 if we are looking at the last line or already beyond the last line. As special
1208
         * optimization, if the first line is requested and the string only consists of one line we return
1209
         * NULL, indicating the input string should be used as is, and avoid a memory allocation for a very
1210
         * common case. */
1211

1212
        for (;;) {
392,162✔
1213
                const char *q;
298,588✔
1214

1215
                q = strchr(p, '\n');
298,588✔
1216
                if (i == c) {
298,588✔
1217
                        /* The line we are looking for! */
1218

1219
                        if (q) {
201,447✔
1220
                                char *m;
3,701✔
1221

1222
                                m = strndup(p, q - p);
3,701✔
1223
                                if (!m)
3,701✔
1224
                                        return -ENOMEM;
1225

1226
                                *ret = m;
3,701✔
1227
                                return !isempty(q + 1); /* More coming? */
7,402✔
1228
                        } else
1229
                                /* Tell the caller to use the input string if equal */
1230
                                return strdup_to(ret, p != s ? p : NULL);
393,820✔
1231
                }
1232

1233
                if (!q)
97,141✔
1234
                        /* No more lines, return empty line */
1235
                        return strdup_to(ret, "");
3,567✔
1236

1237
                p = q + 1;
93,574✔
1238
                c++;
93,574✔
1239
        }
1240
}
1241

1242
int string_contains_word_strv(const char *string, const char *separators, char * const *words, const char **ret_word) {
71✔
1243
        /* In the default mode with no separators specified, we split on whitespace and coalesce separators. */
1244
        const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
71✔
1245
        const char *found = NULL;
71✔
1246
        int r;
196✔
1247

1248
        for (;;) {
321✔
1249
                _cleanup_free_ char *w = NULL;
125✔
1250

1251
                r = extract_first_word(&string, &w, separators, flags);
196✔
1252
                if (r < 0)
196✔
UNCOV
1253
                        return r;
×
1254
                if (r == 0)
196✔
1255
                        break;
1256

1257
                found = strv_find(words, w);
146✔
1258
                if (found)
146✔
1259
                        break;
1260
        }
1261

1262
        if (ret_word)
71✔
1263
                *ret_word = found;
7✔
1264
        return !!found;
71✔
1265
}
1266

1267
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
8,890✔
1268
        if (!s1 && !s2)
8,890✔
1269
                return true;
1270
        if (!s1 || !s2)
8,889✔
1271
                return false;
1272

1273
        if (!ok)
8,887✔
1274
                ok = WHITESPACE;
13✔
1275

1276
        for (; *s1 && *s2; s1++, s2++)
16,766✔
1277
                if (*s1 != *s2)
10,157✔
1278
                        break;
1279

1280
        return in_charset(s1, ok) && in_charset(s2, ok);
11,171✔
1281
}
1282

1283
char* string_replace_char(char *str, char old_char, char new_char) {
680,492✔
1284
        assert(str);
680,492✔
1285
        assert(old_char != '\0');
680,492✔
1286
        assert(new_char != '\0');
680,492✔
1287
        assert(old_char != new_char);
680,492✔
1288

1289
        for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
685,779✔
1290
                *p = new_char;
5,287✔
1291

1292
        return str;
680,492✔
1293
}
1294

1295
int make_cstring(const void *s, size_t n, MakeCStringMode mode, char **ret) {
2,546✔
1296
        char *b;
2,546✔
1297

1298
        assert(s || n == 0);
2,546✔
1299
        assert(mode >= 0);
2,546✔
1300
        assert(mode < _MAKE_CSTRING_MODE_MAX);
2,546✔
1301

1302
        /* Converts a sized character buffer into a NUL-terminated NUL string, refusing if there are embedded
1303
         * NUL bytes. Whether to expect a trailing NUL byte can be specified via 'mode' */
1304

1305
        if (n == 0) {
2,546✔
1306
                if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
20✔
1307
                        return -EINVAL;
1308

1309
                if (!ret)
19✔
1310
                        return 0;
1311

1312
                b = new0(char, 1);
19✔
1313
        } else {
1314
                const uint8_t *nul;
2,526✔
1315

1316
                nul = memchr(s, 0, n);
2,526✔
1317
                if (nul) {
2,526✔
1318
                        if (nul < (const uint8_t*) s + n - 1 || /* embedded NUL? */
15✔
1319
                            mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
1320
                                return -EINVAL;
1321

1322
                        n--;
1323
                } else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
2,511✔
1324
                        return -EINVAL;
1325

1326
                if (!ret)
2,515✔
1327
                        return 0;
1328

1329
                b = memdup_suffix0(s, n);
2,515✔
1330
        }
1331
        if (!b)
2,534✔
1332
                return -ENOMEM;
1333

1334
        *ret = b;
2,534✔
1335
        return 0;
2,534✔
1336
}
1337

1338
size_t strspn_from_end(const char *str, const char *accept) {
644,596✔
1339
        size_t n = 0;
644,596✔
1340

1341
        if (isempty(str))
644,596✔
1342
                return 0;
1343

1344
        if (isempty(accept))
644,593✔
1345
                return 0;
1346

1347
        for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
1,264,194✔
1348
                n++;
619,602✔
1349

1350
        return n;
1351
}
1352

UNCOV
1353
char* strdupspn(const char *a, const char *accept) {
×
UNCOV
1354
        if (isempty(a) || isempty(accept))
×
UNCOV
1355
                return strdup("");
×
1356

1357
        return strndup(a, strspn(a, accept));
×
1358
}
1359

1360
char* strdupcspn(const char *a, const char *reject) {
38,423✔
1361
        if (isempty(a))
38,423✔
UNCOV
1362
                return strdup("");
×
1363
        if (isempty(reject))
38,423✔
UNCOV
1364
                return strdup(a);
×
1365

1366
        return strndup(a, strcspn(a, reject));
38,423✔
1367
}
1368

1369
char* find_line_startswith_internal(const char *haystack, const char *needle) {
2,417✔
1370
        assert(haystack);
2,417✔
1371
        assert(needle);
2,417✔
1372

1373
        /* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
1374
         * first character after it */
1375

1376
        char *p = (char*) strstr(haystack, needle);
2,417✔
1377
        if (!p)
2,417✔
1378
                return NULL;
1379

1380
        if (p > haystack)
513✔
1381
                while (p[-1] != '\n') {
38✔
1382
                        p = strstr(p + 1, needle);
9✔
1383
                        if (!p)
9✔
1384
                                return NULL;
1385
                }
1386

1387
        return p + strlen(needle);
512✔
1388
}
1389

UNCOV
1390
char* find_line_internal(const char *haystack, const char *needle) {
×
UNCOV
1391
        assert(haystack);
×
1392
        assert(needle);
×
1393

1394
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1395
         * beginning of the line */
1396

1397
        char *p = (char*) find_line_startswith(haystack, needle);
×
UNCOV
1398
        if (!p)
×
1399
                return NULL;
1400

UNCOV
1401
        if (*p == 0 || strchr(NEWLINE, *p))
×
1402
                return p - strlen(needle);
×
1403

1404
        return NULL;
1405
}
1406

UNCOV
1407
char* find_line_after_internal(const char *haystack, const char *needle) {
×
UNCOV
1408
        assert(haystack);
×
1409
        assert(needle);
×
1410

1411
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1412
         * next line after it */
1413

UNCOV
1414
        char *p = (char*) find_line_startswith(haystack, needle);
×
1415
        if (!p)
×
1416
                return NULL;
1417

UNCOV
1418
        if (*p == 0)
×
1419
                return p;
UNCOV
1420
        if (strchr(NEWLINE, *p))
×
UNCOV
1421
                return p + 1;
×
1422

1423
        return NULL;
1424
}
1425

1426
bool version_is_valid(const char *s) {
19,087✔
1427
        if (isempty(s))
19,087✔
1428
                return false;
1429

1430
        if (!filename_part_is_valid(s))
19,085✔
1431
                return false;
1432

1433
        /* This is a superset of the characters used by semver. We additionally allow "," and "_". */
1434
        if (!in_charset(s, ALPHANUMERICAL ".,_-+"))
19,085✔
UNCOV
1435
                return false;
×
1436

1437
        return true;
1438
}
1439

1440
bool version_is_valid_versionspec(const char *s) {
94✔
1441
        if (!filename_part_is_valid(s))
94✔
1442
                return false;
1443

1444
        if (!in_charset(s, ALPHANUMERICAL "-.~^"))
94✔
UNCOV
1445
                return false;
×
1446

1447
        return true;
1448
}
1449

1450
ssize_t strlevenshtein(const char *x, const char *y) {
114✔
1451
        _cleanup_free_ size_t *t0 = NULL, *t1 = NULL, *t2 = NULL;
228✔
1452
        size_t xl, yl;
114✔
1453

1454
        /* This is inspired from the Linux kernel's Levenshtein implementation */
1455

1456
        if (streq_ptr(x, y))
114✔
1457
                return 0;
1458

1459
        xl = strlen_ptr(x);
110✔
1460
        if (xl > SSIZE_MAX)
109✔
1461
                return -E2BIG;
1462

1463
        yl = strlen_ptr(y);
110✔
1464
        if (yl > SSIZE_MAX)
109✔
1465
                return -E2BIG;
1466

1467
        if (isempty(x))
110✔
1468
                return yl;
3✔
1469
        if (isempty(y))
107✔
1470
                return xl;
1✔
1471

1472
        t0 = new0(size_t, yl + 1);
106✔
1473
        if (!t0)
106✔
1474
                return -ENOMEM;
1475
        t1 = new0(size_t, yl + 1);
106✔
1476
        if (!t1)
106✔
1477
                return -ENOMEM;
1478
        t2 = new0(size_t, yl + 1);
106✔
1479
        if (!t2)
106✔
1480
                return -ENOMEM;
1481

1482
        for (size_t i = 0; i <= yl; i++)
1,113✔
1483
                t1[i] = i;
1,007✔
1484

1485
        for (size_t i = 0; i < xl; i++) {
627✔
1486
                t2[0] = i + 1;
521✔
1487

1488
                for (size_t j = 0; j < yl; j++) {
5,378✔
1489
                        /* Substitution */
1490
                        t2[j+1] = t1[j] + (x[i] != y[j]);
4,857✔
1491

1492
                        /* Swap */
1493
                        if (i > 0 && j > 0 && x[i-1] == y[j] && x[i] == y[j-1] && t2[j+1] > t0[j-1] + 1)
4,857✔
1494
                                t2[j+1] = t0[j-1] + 1;
10✔
1495

1496
                        /* Deletion */
1497
                        if (t2[j+1] > t1[j+1] + 1)
4,857✔
1498
                                t2[j+1] = t1[j+1] + 1;
176✔
1499

1500
                        /* Insertion */
1501
                        if (t2[j+1] > t2[j] + 1)
4,857✔
1502
                                t2[j+1] = t2[j] + 1;
687✔
1503
                }
1504

1505
                size_t *dummy = t0;
1506
                t0 = t1;
1507
                t1 = t2;
1508
                t2 = dummy;
1509
        }
1510

1511
        return t1[yl];
106✔
1512
}
1513

1514
char* strrstr_internal(const char *haystack, const char *needle) {
25,251✔
1515
        /* Like strstr() but returns the last rather than the first occurrence of "needle" in "haystack". */
1516

1517
        if (!haystack || !needle)
25,251✔
1518
                return NULL;
1519

1520
        /* Special case: for the empty string we return the very last possible occurrence, i.e. *after* the
1521
         * last char, not before. */
1522
        if (needle[0] == 0)
25,248✔
1523
                return (char*) strchr(haystack, 0);
2✔
1524

1525
        /* Special case: for single character strings, just use optimized strrchr() */
1526
        if (needle[1] == 0)
25,246✔
1527
                return (char*) strrchr(haystack, needle[0]);
3✔
1528

1529
        for (const char *p = strstr(haystack, needle), *q; p; p = q) {
25,249✔
1530
                q = strstr(p + 1, needle);
18✔
1531
                if (!q)
18✔
1532
                        return (char*) p;
1533
        }
1534
        return NULL;
1535
}
1536

1537
char* strrstr_no_case_internal(const char *haystack, const char *needle) {
19✔
1538
        if (!haystack || !needle)
19✔
1539
                return NULL;
1540

1541
        for (const char *p = strchr(haystack, 0); p > haystack; p--)
69✔
1542
                if (startswith_no_case(p, needle))
63✔
1543
                        return (char*) p;
1544

1545
        return startswith_no_case(haystack, needle) ? (char*) haystack : NULL;
6✔
1546
}
1547

1548
size_t str_common_prefix(const char *a, const char *b) {
16✔
1549
        assert(a);
16✔
1550
        assert(b);
16✔
1551

1552
        /* Returns the length of the common prefix of the two specified strings, or SIZE_MAX in case the
1553
         * strings are fully identical. */
1554

1555
        for (size_t n = 0;; n++) {
39✔
1556
                char c = a[n];
55✔
1557
                if (c != b[n])
55✔
1558
                        return n;
1559
                if (c == 0)
42✔
1560
                        return SIZE_MAX;
1561
        }
1562
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc