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

systemd / systemd / 23966986054

03 Apr 2026 09:22PM UTC coverage: 72.107% (-0.3%) from 72.362%
23966986054

push

github

daandemeyer
fd-util: Add missing assert()

1 of 1 new or added line in 1 file covered. (100.0%)

7891 existing lines in 120 files now uncovered.

318256 of 441368 relevant lines covered (72.11%)

1186882.96 hits per line

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

91.43
/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,334,434✔
21
        assert(s);
3,334,434✔
22
        assert(word);
3,334,434✔
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,334,434✔
28
                return (char*) s;
29

30
        const char *p = startswith(s, word);
3,334,433✔
31
        if (!p)
3,334,433✔
32
                return NULL;
33
        if (*p == '\0')
117,277✔
34
                return (char*) p;
35

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

40
        return (char*) nw;
41
}
42

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

47
        if (l > 0)
29,197✔
48
                l = strnlen(s, l); /* ignore trailing noise */
28,871✔
49

50
        if (l > 0 || !*x) {
29,197✔
51
                size_t q;
29,041✔
52
                char *m;
29,041✔
53

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

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

61
                *x = m;
29,041✔
62
        }
63

64
        return *x;
29,197✔
65
}
66

67
char* strstrip(char *s) {
6,459,586✔
68
        if (!s)
6,459,586✔
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,456,232✔
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,052,200✔
100
        char *c = s;
8,052,200✔
101

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

104
        if (!s)
8,052,200✔
105
                return NULL;
106

107
        if (!bad)
8,052,200✔
108
                bad = WHITESPACE;
85,295✔
109

110
        for (char *p = s; *p; p++)
287,771,632✔
111
                if (!strchr(bad, *p))
279,719,432✔
112
                        c = p + 1;
268,026,182✔
113

114
        *c = 0;
8,052,200✔
115

116
        return s;
8,052,200✔
117
}
118

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

122
        assert(s);
2,899,329✔
123

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

131
char ascii_tolower(char x) {
51,026,664✔
132

133
        if (x >= 'A' && x <= 'Z')
51,026,664✔
134
                return x - 'A' + 'a';
3,523,993✔
135

136
        return x;
137
}
138

139
char ascii_toupper(char x) {
330,322✔
140

141
        if (x >= 'a' && x <= 'z')
330,322✔
142
                return x - 'a' + 'A';
201,483✔
143

144
        return x;
145
}
146

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

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

153
        return s;
28,831✔
154
}
155

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

159
        for (char *p = s; *p; p++)
353,870✔
160
                *p = ascii_toupper(*p);
330,192✔
161

162
        return s;
23,678✔
163
}
164

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

169
        for (size_t i = 0; i < n; i++)
14,821,408✔
170
                s[i] = ascii_tolower(s[i]);
13,032,185✔
171

172
        return s;
173
}
174

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

177
        assert(a);
2,530,056✔
178
        assert(b);
2,530,056✔
179

180
        for (; n > 0; a++, b++, n--) {
20,852,270✔
181
                int x, y;
18,914,832✔
182

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

186
                if (x != y)
18,914,832✔
187
                        return x - y;
592,618✔
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,071,766✔
194
        int r;
1,071,766✔
195

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

200
        return CMP(n, m);
946,849✔
201
}
202

203
bool chars_intersect(const char *a, const char *b) {
11,647✔
204
        /* Returns true if any of the chars in a are in b. */
205
        for (const char *p = a; *p; p++)
168,352✔
206
                if (strchr(b, *p))
156,718✔
207
                        return true;
208

209
        return false;
210
}
211

212
bool string_has_cc(const char *p, const char *ok) {
13,783,619✔
213
        assert(p);
13,783,619✔
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++) {
249,301,095✔
222
                if (ok && strchr(ok, *t))
235,517,498✔
223
                        continue;
8✔
224

225
                if (char_is_cc(*t))
235,517,490✔
226
                        return true;
227
        }
228

229
        return false;
230
}
231

232
static int write_ellipsis(char *buf, bool unicode) {
4,538✔
233
        const char *s = glyph_full(GLYPH_ELLIPSIS, unicode);
4,538✔
234
        assert(strlen(s) == 3);
4,538✔
235
        memcpy(buf, s, 3);
4,538✔
236
        return 3;
4,538✔
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✔
UNCOV
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✔
UNCOV
265
                return 2;
×
266

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

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

273
        while ((t = memchr(t, 0x1B, len - (t - s)))) {
8,025✔
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,476✔
302
        size_t x, need_space, suffix_len;
4,476✔
303
        char *t;
4,476✔
304

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

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

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

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

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

324
        case 2:
35✔
325
                if (!is_locale_utf8())
35✔
UNCOV
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,686✔
334

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

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

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

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

349
        return t;
2,686✔
350
}
351

352
char* ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
8,195✔
353
        size_t x, k, len, len2;
8,195✔
354
        const char *i, *j;
8,195✔
355
        int r;
8,195✔
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,195✔
370
        assert(percent <= 100);
8,195✔
371

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

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

378
        bool has_ansi_seq = string_has_ansi_sequence(s, old_length);
8,024✔
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))
8,024✔
382
                return ascii_ellipsize_mem(s, old_length, new_length, percent);
4,476✔
383

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

387
        k = 0;
388
        for (i = s; i < s + old_length; ) {
49,692✔
389
                size_t slen = has_ansi_seq ? ansi_sequence_length(i, old_length - (i - s)) : 0;
48,500✔
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,276✔
396
                r = utf8_encoded_to_unichar(i, &c);
48,276✔
397
                if (r < 0)
48,276✔
UNCOV
398
                        return NULL;
×
399

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

404
                k += w;
45,920✔
405
                i += r;
45,920✔
406
        }
407

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

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

416
                if (has_ansi_seq && ansi_start >= t)
9,743✔
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,743✔
422
                        t = ansi_start;
112✔
423
                        continue;
112✔
424
                }
425

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

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

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

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

443
        if (k >= new_length) {
1,828✔
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,742✔
448
                        j = utf8_next_char(j);
1,742✔
UNCOV
449
                else if (i > s)
×
UNCOV
450
                        i = utf8_prev_char(i);
×
451
        }
452

453
        len = i - s;
1,828✔
454
        len2 = s + old_length - j;
1,828✔
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,828✔
460

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

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

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

470
        if (has_ansi_seq)
1,828✔
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,828✔
482
        dst[len2] = '\0';
1,828✔
483

484
        return e;
1,828✔
485
}
486

487
char* cellescape(char *buf, size_t len, const char *s) {
42,496✔
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;
42,496✔
501

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

506
        for (;;) {
934,462✔
507
                char four[4];
488,479✔
508
                int w;
488,479✔
509

510
                if (*s == 0) /* terminating NUL detected? then we are done! */
488,479✔
511
                        goto done;
42,460✔
512

513
                w = cescape_char(*s, four);
446,019✔
514
                if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
446,019✔
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);
445,983✔
520
                i += w;
445,983✔
521

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

526
                s++;
445,983✔
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';
42,496✔
556
        return buf;
42,496✔
557
}
558

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

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

565
        if (strnlen(s, l+1) > l)
357,555✔
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,595✔
594
        size_t l, old_len, new_len;
4,595✔
595
        char *t, *ret = NULL;
4,595✔
596
        const char *f;
4,595✔
597

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

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

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

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

611
        f = text;
4,594✔
612
        t = ret;
4,594✔
613
        while (*f) {
160,911✔
614
                size_t d, nl;
156,317✔
615

616
                if (!startswith(f, old_string)) {
156,317✔
617
                        *(t++) = *(f++);
154,113✔
618
                        continue;
154,113✔
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✔
UNCOV
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,594✔
635
        return ret;
4,594✔
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✔
UNCOV
650
                shift[0] += size;
×
651
        if ((size_t) diff < offsets[1])
396✔
UNCOV
652
                shift[1] += size;
×
653
}
654

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

668
        assert(ibuf);
171,484✔
669
        assert(*ibuf);
171,484✔
670

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

685
        isz = _isz ? *_isz : strlen(*ibuf);
171,484✔
686

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

693
        for (const char *i = *ibuf; i < *ibuf + isz + 1; i++) {
20,437,830✔
694

695
                bool eot = i >= *ibuf + isz;
20,266,346✔
696

697
                switch (state) {
20,266,346✔
698

699
                case STATE_OTHER:
20,266,095✔
700
                        if (eot)
20,266,095✔
701
                                break;
702

703
                        if (*i == '\r') {
20,094,611✔
704
                                n_carriage_returns++;
7✔
705
                                break;
7✔
706
                        } else if (*i == '\n')
20,094,604✔
707
                                /* Ignore carriage returns before new line */
708
                                n_carriage_returns = 0;
34✔
709
                        for (; n_carriage_returns > 0; n_carriage_returns--)
20,094,606✔
710
                                fputc('\r', f);
2✔
711

712
                        if (*i == '\x1B')
20,094,604✔
713
                                state = STATE_ESCAPE;
714
                        else if (*i == '\t') {
20,094,570✔
715
                                fputs("        ", f);
401✔
716
                                advance_offsets(i - *ibuf, highlight, shift, 7);
401✔
717
                        } else
718
                                fputc(*i, f);
20,094,169✔
719

720
                        break;
721

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

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

742
                        break;
743

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

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

756
                        break;
757

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

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

775
                        break;
776

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

787
                        break;
788
                }
789
        }
790

791
        char *obuf;
171,484✔
792
        if (memstream_finalize(&m, &obuf, _isz) < 0)
171,484✔
793
                return NULL;
794

795
        free_and_replace(*ibuf, obuf);
171,484✔
796

797
        if (highlight) {
171,484✔
798
                highlight[0] += shift[0];
171,457✔
799
                highlight[1] += shift[1];
171,457✔
800
        }
801

802
        return *ibuf;
171,484✔
803
}
804

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

811
        if (!x)
23,064,826✔
812
                x = &buffer;
21,771,337✔
813

814
        l = f = strlen_ptr(*x);
23,064,826✔
815

816
        need_separator = !isempty(*x);
23,064,826✔
817
        l_separator = strlen_ptr(separator);
23,064,826✔
818

819
        va_list aq;
23,064,826✔
820
        va_copy(aq, ap);
23,064,826✔
821
        for (const char *t;;) {
87,677,405✔
822
                size_t n;
87,677,405✔
823

824
                t = va_arg(aq, const char *);
87,677,405✔
825
                if (!t)
87,677,405✔
826
                        break;
827
                if (t == POINTER_MAX)
64,612,579✔
828
                        continue;
3✔
829

830
                n = strlen(t);
64,612,576✔
831

832
                if (need_separator)
64,612,576✔
833
                        n += l_separator;
42,280,380✔
834

835
                if (n >= SIZE_MAX - l) {
64,612,576✔
UNCOV
836
                        va_end(aq);
×
UNCOV
837
                        return NULL;
×
838
                }
839

840
                l += n;
64,612,576✔
841
                need_separator = true;
64,612,576✔
842
        }
843
        va_end(aq);
23,064,826✔
844

845
        need_separator = !isempty(*x);
23,064,826✔
846

847
        nr = realloc(*x, GREEDY_ALLOC_ROUND_UP(l+1));
23,064,826✔
848
        if (!nr)
23,064,826✔
849
                return NULL;
850

851
        *x = nr;
23,064,826✔
852
        p = nr + f;
23,064,826✔
853

854
        for (;;) {
87,677,405✔
855
                const char *t;
87,677,405✔
856

857
                t = va_arg(ap, const char *);
87,677,405✔
858
                if (!t)
87,677,405✔
859
                        break;
860
                if (t == POINTER_MAX)
64,612,579✔
861
                        continue;
3✔
862

863
                if (need_separator && separator)
64,612,576✔
864
                        p = stpcpy(p, separator);
159,553✔
865

866
                p = stpcpy(p, t);
64,612,576✔
867

868
                need_separator = true;
64,612,576✔
869
        }
870

871
        assert(p == nr + l);
23,064,826✔
872
        *p = 0;
23,064,826✔
873

874
        /* If no buffer to extend was passed in return the start of the buffer */
875
        if (buffer)
23,064,826✔
876
                return TAKE_PTR(buffer);
21,771,337✔
877

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

882
char* strextend_with_separator_internal(char **x, const char *separator, ...) {
23,013,212✔
883
        va_list ap;
23,013,212✔
884
        char *ret;
23,013,212✔
885

886
        va_start(ap, separator);
23,013,212✔
887
        ret = strextendv_with_separator(x, separator, ap);
23,013,212✔
888
        va_end(ap);
23,013,212✔
889

890
        return ret;
23,013,212✔
891
}
892

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

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

902
        assert(x);
17,698✔
903
        assert(format);
17,698✔
904

905
        l_separator = isempty(*x) ? 0 : strlen_ptr(separator);
30,833✔
906

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

915
        if (a - m < 17 + l_separator) { /* if there's less than 16 chars space, then enlarge the buffer first */
17,698✔
916
                char *n;
10,878✔
917

918
                if (_unlikely_(l_separator > SIZE_MAX - 64)) /* overflow check #1 */
10,878✔
919
                        return -ENOMEM;
17,698✔
920
                if (_unlikely_(m > SIZE_MAX - 64 - l_separator)) /* overflow check #2 */
10,878✔
921
                        return -ENOMEM;
922

923
                n = realloc(*x, m + 64 + l_separator);
10,878✔
924
                if (!n)
10,878✔
925
                        return -ENOMEM;
926

927
                *x = n;
10,878✔
928
                a = MALLOC_SIZEOF_SAFE(*x);
10,878✔
929
        }
930

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

937
        assert(l >= 0);
17,698✔
938

939
        if ((size_t) l < a - m - l_separator) {
17,698✔
940
                char *n;
17,200✔
941

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

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

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

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

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

968
                assert((size_t) l < a - m - l_separator);
498✔
969
        }
970

971
        return 0;
972

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

979
char* strrep(const char *s, unsigned n) {
11✔
980
        char *r, *p;
11✔
981
        size_t l;
11✔
982

983
        assert(s);
11✔
984

985
        l = strlen(s);
11✔
986
        p = r = malloc(l * n + 1);
11✔
987
        if (!r)
11✔
988
                return NULL;
989

990
        for (unsigned i = 0; i < n; i++)
40,337✔
991
                p = stpcpy(p, s);
40,326✔
992

993
        *p = 0;
11✔
994
        return r;
11✔
995
}
996

997
int split_pair(const char *s, const char *sep, char **ret_first, char **ret_second) {
1,564✔
998
        assert(s);
1,564✔
999
        assert(!isempty(sep));
1,564✔
1000
        assert(ret_first);
1,564✔
1001
        assert(ret_second);
1,564✔
1002

1003
        const char *x = strstr(s, sep);
1,564✔
1004
        if (!x)
1,564✔
1005
                return -EINVAL;
1,564✔
1006

1007
        _cleanup_free_ char *a = strndup(s, x - s);
262✔
1008
        if (!a)
262✔
1009
                return -ENOMEM;
1010

1011
        _cleanup_free_ char *b = strdup(x + strlen(sep));
262✔
1012
        if (!b)
262✔
1013
                return -ENOMEM;
1014

1015
        *ret_first = TAKE_PTR(a);
262✔
1016
        *ret_second = TAKE_PTR(b);
262✔
1017
        return 0;
262✔
1018
}
1019

1020
int free_and_strdup(char **p, const char *s) {
2,041,669✔
1021
        char *t;
2,041,669✔
1022

1023
        assert(p);
2,041,669✔
1024

1025
        /* Replaces a string pointer with a strdup()ed new string,
1026
         * possibly freeing the old one. */
1027

1028
        if (streq_ptr(*p, s))
2,041,669✔
1029
                return 0;
2,041,669✔
1030

1031
        if (s) {
1,597,133✔
1032
                t = strdup(s);
1,589,043✔
1033
                if (!t)
1,589,043✔
1034
                        return -ENOMEM;
1035
        } else
1036
                t = NULL;
1037

1038
        free_and_replace(*p, t);
1,597,133✔
1039

1040
        return 1;
1,597,133✔
1041
}
1042

1043
int free_and_strdup_warn(char **p, const char *s) {
62,714✔
1044
        int r;
62,714✔
1045

1046
        r = free_and_strdup(p, s);
62,714✔
1047
        if (r < 0)
62,714✔
UNCOV
1048
                return log_oom();
×
1049
        return r;
1050
}
1051

1052
int free_and_strndup(char **p, const char *s, size_t l) {
69,909✔
1053
        char *t;
69,909✔
1054

1055
        assert(p);
69,909✔
1056
        assert(s || l == 0);
69,909✔
1057

1058
        /* Replaces a string pointer with a strndup()ed new string,
1059
         * freeing the old one. */
1060

1061
        if (!*p && !s)
69,909✔
1062
                return 0;
69,909✔
1063

1064
        if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
69,909✔
1065
                return 0;
1066

1067
        if (s) {
32,613✔
1068
                t = strndup(s, l);
32,672✔
1069
                if (!t)
32,672✔
1070
                        return -ENOMEM;
1071
        } else
1072
                t = NULL;
1073

1074
        free_and_replace(*p, t);
32,673✔
1075
        return 1;
32,673✔
1076
}
1077

1078
int strdup_to_full(char **ret, const char *src) {
729,813✔
1079
        if (!src) {
729,813✔
1080
                if (ret)
276,659✔
1081
                        *ret = NULL;
276,658✔
1082

1083
                return 0;
276,659✔
1084
        } else {
1085
                if (ret) {
453,154✔
1086
                        char *t = strdup(src);
453,152✔
1087
                        if (!t)
453,152✔
1088
                                return -ENOMEM;
1089
                        *ret = t;
453,152✔
1090
                }
1091

1092
                return 1;
453,154✔
1093
        }
1094
};
1095

1096
bool string_is_safe(const char *p) {
197,200✔
1097
        if (!p)
197,200✔
1098
                return false;
1099

1100
        /* Checks if the specified string contains no quotes or control characters */
1101

1102
        for (const char *t = p; *t; t++) {
2,308,168✔
1103
                if (*t > 0 && *t < ' ') /* no control characters */
2,110,981✔
1104
                        return false;
1105

1106
                if (strchr(QUOTES "\\\x7f", *t))
2,110,973✔
1107
                        return false;
1108
        }
1109

1110
        return true;
1111
}
1112

UNCOV
1113
bool string_is_safe_ascii(const char *p) {
×
UNCOV
1114
        return ascii_is_valid(p) && string_is_safe(p);
×
1115
}
1116

1117
char* str_realloc(char *p) {
42,100✔
1118
        /* Reallocate *p to actual size. Ignore failure, and return the original string on error. */
1119

1120
        if (!p)
42,100✔
1121
                return NULL;
1122

1123
        return realloc(p, strlen(p) + 1) ?: p;
42,100✔
1124
}
1125

1126
char* string_erase(char *x) {
119✔
1127
        if (!x)
119✔
1128
                return NULL;
1129

1130
        /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1131
         * used them. */
1132
        explicit_bzero_safe(x, strlen(x));
119✔
1133
        return x;
119✔
1134
}
1135

1136
int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
300✔
1137
        const char *p = s, *e = s;
300✔
1138
        bool truncation_applied = false;
300✔
1139
        char *copy;
300✔
1140
        size_t n = 0;
300✔
1141

1142
        assert(s);
300✔
1143
        assert(ret);
300✔
1144

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

1149
        for (;;) {
530✔
1150
                size_t k;
415✔
1151

1152
                k = strcspn(p, "\n");
415✔
1153

1154
                if (p[k] == 0) {
415✔
1155
                        if (k == 0) /* final empty line */
268✔
1156
                                break;
1157

1158
                        if (n >= n_lines) /* above threshold */
243✔
1159
                                break;
1160

1161
                        e = p + k; /* last line to include */
226✔
1162
                        break;
226✔
1163
                }
1164

1165
                assert(p[k] == '\n');
147✔
1166

1167
                if (n >= n_lines)
147✔
1168
                        break;
1169

1170
                if (k > 0)
115✔
1171
                        e = p + k;
92✔
1172

1173
                p += k + 1;
115✔
1174
                n++;
115✔
1175
        }
1176

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

1185
                copy = strndup(s, e - s);
70✔
1186
        }
1187
        if (!copy)
300✔
1188
                return -ENOMEM;
1189

1190
        *ret = copy;
300✔
1191
        return truncation_applied;
300✔
1192
}
1193

1194
int string_extract_line(const char *s, size_t i, char **ret) {
207,809✔
1195
        const char *p = s;
207,809✔
1196
        size_t c = 0;
207,809✔
1197

1198
        assert(ret);
207,809✔
1199

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

1206
        for (;;) {
393,993✔
1207
                const char *q;
300,901✔
1208

1209
                q = strchr(p, '\n');
300,901✔
1210
                if (i == c) {
300,901✔
1211
                        /* The line we are looking for! */
1212

1213
                        if (q) {
204,555✔
1214
                                char *m;
3,388✔
1215

1216
                                m = strndup(p, q - p);
3,388✔
1217
                                if (!m)
3,388✔
1218
                                        return -ENOMEM;
1219

1220
                                *ret = m;
3,388✔
1221
                                return !isempty(q + 1); /* More coming? */
6,776✔
1222
                        } else
1223
                                /* Tell the caller to use the input string if equal */
1224
                                return strdup_to(ret, p != s ? p : NULL);
400,883✔
1225
                }
1226

1227
                if (!q)
96,346✔
1228
                        /* No more lines, return empty line */
1229
                        return strdup_to(ret, "");
3,254✔
1230

1231
                p = q + 1;
93,092✔
1232
                c++;
93,092✔
1233
        }
1234
}
1235

1236
int string_contains_word_strv(const char *string, const char *separators, char * const *words, const char **ret_word) {
71✔
1237
        /* In the default mode with no separators specified, we split on whitespace and coalesce separators. */
1238
        const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
71✔
1239
        const char *found = NULL;
71✔
1240
        int r;
196✔
1241

1242
        for (;;) {
321✔
1243
                _cleanup_free_ char *w = NULL;
125✔
1244

1245
                r = extract_first_word(&string, &w, separators, flags);
196✔
1246
                if (r < 0)
196✔
UNCOV
1247
                        return r;
×
1248
                if (r == 0)
196✔
1249
                        break;
1250

1251
                found = strv_find(words, w);
146✔
1252
                if (found)
146✔
1253
                        break;
1254
        }
1255

1256
        if (ret_word)
71✔
1257
                *ret_word = found;
7✔
1258
        return !!found;
71✔
1259
}
1260

1261
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
8,802✔
1262
        if (!s1 && !s2)
8,802✔
1263
                return true;
1264
        if (!s1 || !s2)
8,801✔
1265
                return false;
1266

1267
        if (!ok)
8,799✔
1268
                ok = WHITESPACE;
13✔
1269

1270
        for (; *s1 && *s2; s1++, s2++)
16,626✔
1271
                if (*s1 != *s2)
10,019✔
1272
                        break;
1273

1274
        return in_charset(s1, ok) && in_charset(s2, ok);
10,997✔
1275
}
1276

1277
char* string_replace_char(char *str, char old_char, char new_char) {
666,926✔
1278
        assert(str);
666,926✔
1279
        assert(old_char != '\0');
666,926✔
1280
        assert(new_char != '\0');
666,926✔
1281
        assert(old_char != new_char);
666,926✔
1282

1283
        for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
672,097✔
1284
                *p = new_char;
5,171✔
1285

1286
        return str;
666,926✔
1287
}
1288

1289
int make_cstring(const char *s, size_t n, MakeCStringMode mode, char **ret) {
2,413✔
1290
        char *b;
2,413✔
1291

1292
        assert(s || n == 0);
2,413✔
1293
        assert(mode >= 0);
2,413✔
1294
        assert(mode < _MAKE_CSTRING_MODE_MAX);
2,413✔
1295

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

1299
        if (n == 0) {
2,413✔
1300
                if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
20✔
1301
                        return -EINVAL;
1302

1303
                if (!ret)
19✔
1304
                        return 0;
1305

1306
                b = new0(char, 1);
19✔
1307
        } else {
1308
                const char *nul;
2,393✔
1309

1310
                nul = memchr(s, 0, n);
2,393✔
1311
                if (nul) {
2,393✔
1312
                        if (nul < s + n - 1 || /* embedded NUL? */
15✔
1313
                            mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
1314
                                return -EINVAL;
1315

1316
                        n--;
1317
                } else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
2,378✔
1318
                        return -EINVAL;
1319

1320
                if (!ret)
2,382✔
1321
                        return 0;
1322

1323
                b = memdup_suffix0(s, n);
2,382✔
1324
        }
1325
        if (!b)
2,401✔
1326
                return -ENOMEM;
1327

1328
        *ret = b;
2,401✔
1329
        return 0;
2,401✔
1330
}
1331

1332
size_t strspn_from_end(const char *str, const char *accept) {
631,433✔
1333
        size_t n = 0;
631,433✔
1334

1335
        if (isempty(str))
631,433✔
1336
                return 0;
1337

1338
        if (isempty(accept))
631,430✔
1339
                return 0;
1340

1341
        for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
1,239,491✔
1342
                n++;
608,062✔
1343

1344
        return n;
1345
}
1346

UNCOV
1347
char* strdupspn(const char *a, const char *accept) {
×
1348
        if (isempty(a) || isempty(accept))
×
UNCOV
1349
                return strdup("");
×
1350

UNCOV
1351
        return strndup(a, strspn(a, accept));
×
1352
}
1353

1354
char* strdupcspn(const char *a, const char *reject) {
37,553✔
1355
        if (isempty(a))
37,553✔
UNCOV
1356
                return strdup("");
×
1357
        if (isempty(reject))
37,553✔
UNCOV
1358
                return strdup(a);
×
1359

1360
        return strndup(a, strcspn(a, reject));
37,553✔
1361
}
1362

1363
char* find_line_startswith_internal(const char *haystack, const char *needle) {
2,399✔
1364
        assert(haystack);
2,399✔
1365
        assert(needle);
2,399✔
1366

1367
        /* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
1368
         * first character after it */
1369

1370
        char *p = (char*) strstr(haystack, needle);
2,399✔
1371
        if (!p)
2,399✔
1372
                return NULL;
1373

1374
        if (p > haystack)
507✔
1375
                while (p[-1] != '\n') {
38✔
1376
                        p = strstr(p + 1, needle);
9✔
1377
                        if (!p)
9✔
1378
                                return NULL;
1379
                }
1380

1381
        return p + strlen(needle);
506✔
1382
}
1383

UNCOV
1384
char* find_line_internal(const char *haystack, const char *needle) {
×
1385
        assert(haystack);
×
1386
        assert(needle);
×
1387

1388
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1389
         * beginning of the line */
1390

1391
        char *p = (char*) find_line_startswith(haystack, needle);
×
1392
        if (!p)
×
1393
                return NULL;
1394

UNCOV
1395
        if (*p == 0 || strchr(NEWLINE, *p))
×
UNCOV
1396
                return p - strlen(needle);
×
1397

1398
        return NULL;
1399
}
1400

UNCOV
1401
char* find_line_after_internal(const char *haystack, const char *needle) {
×
1402
        assert(haystack);
×
UNCOV
1403
        assert(needle);
×
1404

1405
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1406
         * next line after it */
1407

UNCOV
1408
        char *p = (char*) find_line_startswith(haystack, needle);
×
UNCOV
1409
        if (!p)
×
1410
                return NULL;
1411

UNCOV
1412
        if (*p == 0)
×
1413
                return p;
UNCOV
1414
        if (strchr(NEWLINE, *p))
×
UNCOV
1415
                return p + 1;
×
1416

1417
        return NULL;
1418
}
1419

1420
bool version_is_valid(const char *s) {
19,087✔
1421
        if (isempty(s))
19,087✔
1422
                return false;
1423

1424
        if (!filename_part_is_valid(s))
19,085✔
1425
                return false;
1426

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

1431
        return true;
1432
}
1433

1434
bool version_is_valid_versionspec(const char *s) {
94✔
1435
        if (!filename_part_is_valid(s))
94✔
1436
                return false;
1437

1438
        if (!in_charset(s, ALPHANUMERICAL "-.~^"))
94✔
UNCOV
1439
                return false;
×
1440

1441
        return true;
1442
}
1443

1444
ssize_t strlevenshtein(const char *x, const char *y) {
114✔
1445
        _cleanup_free_ size_t *t0 = NULL, *t1 = NULL, *t2 = NULL;
228✔
1446
        size_t xl, yl;
114✔
1447

1448
        /* This is inspired from the Linux kernel's Levenshtein implementation */
1449

1450
        if (streq_ptr(x, y))
114✔
1451
                return 0;
1452

1453
        xl = strlen_ptr(x);
110✔
1454
        if (xl > SSIZE_MAX)
109✔
1455
                return -E2BIG;
1456

1457
        yl = strlen_ptr(y);
110✔
1458
        if (yl > SSIZE_MAX)
109✔
1459
                return -E2BIG;
1460

1461
        if (isempty(x))
110✔
1462
                return yl;
3✔
1463
        if (isempty(y))
107✔
1464
                return xl;
1✔
1465

1466
        t0 = new0(size_t, yl + 1);
106✔
1467
        if (!t0)
106✔
1468
                return -ENOMEM;
1469
        t1 = new0(size_t, yl + 1);
106✔
1470
        if (!t1)
106✔
1471
                return -ENOMEM;
1472
        t2 = new0(size_t, yl + 1);
106✔
1473
        if (!t2)
106✔
1474
                return -ENOMEM;
1475

1476
        for (size_t i = 0; i <= yl; i++)
1,113✔
1477
                t1[i] = i;
1,007✔
1478

1479
        for (size_t i = 0; i < xl; i++) {
627✔
1480
                t2[0] = i + 1;
521✔
1481

1482
                for (size_t j = 0; j < yl; j++) {
5,378✔
1483
                        /* Substitution */
1484
                        t2[j+1] = t1[j] + (x[i] != y[j]);
4,857✔
1485

1486
                        /* Swap */
1487
                        if (i > 0 && j > 0 && x[i-1] == y[j] && x[i] == y[j-1] && t2[j+1] > t0[j-1] + 1)
4,857✔
1488
                                t2[j+1] = t0[j-1] + 1;
10✔
1489

1490
                        /* Deletion */
1491
                        if (t2[j+1] > t1[j+1] + 1)
4,857✔
1492
                                t2[j+1] = t1[j+1] + 1;
176✔
1493

1494
                        /* Insertion */
1495
                        if (t2[j+1] > t2[j] + 1)
4,857✔
1496
                                t2[j+1] = t2[j] + 1;
687✔
1497
                }
1498

1499
                size_t *dummy = t0;
1500
                t0 = t1;
1501
                t1 = t2;
1502
                t2 = dummy;
1503
        }
1504

1505
        return t1[yl];
106✔
1506
}
1507

1508
char* strrstr_internal(const char *haystack, const char *needle) {
25,246✔
1509
        /* Like strstr() but returns the last rather than the first occurrence of "needle" in "haystack". */
1510

1511
        if (!haystack || !needle)
25,246✔
1512
                return NULL;
1513

1514
        /* Special case: for the empty string we return the very last possible occurrence, i.e. *after* the
1515
         * last char, not before. */
1516
        if (*needle == 0)
25,243✔
1517
                return (char*) strchr(haystack, 0);
2✔
1518

1519
        for (const char *p = strstr(haystack, needle), *q; p; p = q) {
25,251✔
1520
                q = strstr(p + 1, needle);
25✔
1521
                if (!q)
25✔
1522
                        return (char *) p;
1523
        }
1524
        return NULL;
1525
}
1526

1527
size_t str_common_prefix(const char *a, const char *b) {
16✔
1528
        assert(a);
16✔
1529
        assert(b);
16✔
1530

1531
        /* Returns the length of the common prefix of the two specified strings, or SIZE_MAX in case the
1532
         * strings are fully identical. */
1533

1534
        for (size_t n = 0;; n++) {
39✔
1535
                char c = a[n];
55✔
1536
                if (c != b[n])
55✔
1537
                        return n;
1538
                if (c == 0)
42✔
1539
                        return SIZE_MAX;
1540
        }
1541
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc