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

systemd / systemd / 27993746414

22 Jun 2026 09:22PM UTC coverage: 72.966% (+0.2%) from 72.75%
27993746414

push

github

web-flow
imds: expose imds info fields also as metrics (#42409)

32 of 110 new or added lines in 4 files covered. (29.09%)

7826 existing lines in 84 files now uncovered.

340224 of 466275 relevant lines covered (72.97%)

1291684.45 hits per line

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

91.89
/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) {
4,371,780✔
21
        assert(s);
4,371,780✔
22
        assert(word);
4,371,780✔
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))
4,371,780✔
28
                return (char*) s;
29

30
        const char *p = startswith(s, word);
4,371,779✔
31
        if (!p)
4,371,779✔
32
                return NULL;
33
        if (*p == '\0')
235,230✔
34
                return (char*) p;
35

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

40
        return (char*) nw;
41
}
42

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

47
        if (l > 0)
35,655✔
48
                l = strnlen(s, l); /* ignore trailing noise */
35,319✔
49

50
        if (l > 0 || !*x) {
35,655✔
51
                size_t q;
35,494✔
52
                char *m;
35,494✔
53

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

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

61
                *x = m;
35,494✔
62
        }
63

64
        return *x;
35,655✔
65
}
66

67
char* strstrip(char *s) {
9,575,007✔
68
        if (!s)
9,575,007✔
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);
9,572,313✔
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) {
11,145,308✔
100
        char *c = s;
11,145,308✔
101

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

104
        if (!s)
11,145,308✔
105
                return NULL;
106

107
        if (!bad)
11,145,308✔
108
                bad = WHITESPACE;
87,990✔
109

110
        for (char *p = s; *p; p++)
367,373,822✔
111
                if (!strchr(bad, *p))
356,228,514✔
112
                        c = p + 1;
342,058,434✔
113

114
        *c = 0;
11,145,308✔
115

116
        return s;
11,145,308✔
117
}
118

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

122
        assert(s);
2,838,495✔
123

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

131
char ascii_tolower(char x) {
50,500,393✔
132

133
        if (x >= 'A' && x <= 'Z')
50,500,393✔
134
                return x - 'A' + 'a';
3,469,036✔
135

136
        return x;
137
}
138

139
char ascii_toupper(char x) {
314,250✔
140

141
        if (x >= 'a' && x <= 'z')
314,250✔
142
                return x - 'a' + 'A';
190,665✔
143

144
        return x;
145
}
146

147
char* ascii_strlower(char *s) {
23,948✔
148
        assert(s);
23,948✔
149

150
        for (char *p = s; *p; p++)
155,194✔
151
                *p = ascii_tolower(*p);
131,246✔
152

153
        return s;
23,948✔
154
}
155

156
char* ascii_strupper(char *s) {
22,068✔
157
        assert(s);
22,068✔
158

159
        for (char *p = s; *p; p++)
336,188✔
160
                *p = ascii_toupper(*p);
314,120✔
161

162
        return s;
22,068✔
163
}
164

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

169
        for (size_t i = 0; i < n; i++)
14,839,303✔
170
                s[i] = ascii_tolower(s[i]);
13,045,110✔
171

172
        return s;
173
}
174

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

177
        assert(a);
2,494,054✔
178
        assert(b);
2,494,054✔
179

180
        for (; n > 0; a++, b++, n--) {
20,567,773✔
181
                int x, y;
18,657,396✔
182

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

186
                if (x != y)
18,657,396✔
187
                        return x - y;
583,677✔
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,081,407✔
194
        int r;
1,081,407✔
195

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

200
        return CMP(n, m);
954,714✔
201
}
202

203
bool chars_intersect(const char *a, const char *b) {
12,650✔
204
        /* Returns true if any of the chars in a are in b. */
205
        for (const char *p = a; *p; p++)
182,506✔
206
                if (strchr(b, *p))
169,878✔
207
                        return true;
208

209
        return false;
210
}
211

212
bool string_has_cc(const char *p, const char *ok) {
282,660✔
213
        assert(p);
282,660✔
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++) {
2,629,745✔
222
                if (ok && strchr(ok, *t))
2,347,101✔
223
                        continue;
8✔
224

225
                if (char_is_cc(*t))
2,347,093✔
226
                        return true;
227
        }
228

229
        return false;
230
}
231

232
static int write_ellipsis(char *buf, bool unicode) {
4,416✔
233
        const char *s = glyph_full(GLYPH_ELLIPSIS, unicode);
4,416✔
234
        assert(strlen(s) == 3);
4,416✔
235
        memcpy(buf, s, 3);
4,416✔
236
        return 3;
4,416✔
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,975✔
271
        const char *t = s;
7,975✔
272

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

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

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

312
        /* Special case short ellipsations */
313
        switch (new_length) {
2,624✔
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,559✔
334

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

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

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

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

349
        return t;
2,559✔
350
}
351

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

484
        return e;
1,833✔
485
}
486

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

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

506
        for (;;) {
1,212,773✔
507
                char four[4];
634,574✔
508
                int w;
634,574✔
509

510
                if (*s == 0) /* terminating NUL detected? then we are done! */
634,574✔
511
                        goto done;
56,339✔
512

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

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

526
                s++;
578,199✔
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';
56,375✔
556
        return buf;
56,375✔
557
}
558

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

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

565
        if (strnlen(s, l+1) > l)
313,476✔
566
                s[l] = 0;
115✔
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) {
7,416✔
594
        size_t l, old_len, new_len;
7,416✔
595
        char *t, *ret = NULL;
7,416✔
596
        const char *f;
7,416✔
597

598
        assert(old_string);
7,416✔
599
        assert(new_string);
7,416✔
600

601
        if (!text)
7,416✔
602
                return NULL;
7,416✔
603

604
        old_len = strlen(old_string);
7,415✔
605
        new_len = strlen(new_string);
7,415✔
606

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

611
        f = text;
7,415✔
612
        t = ret;
7,415✔
613
        while (*f) {
241,467✔
614
                size_t d, nl;
234,052✔
615

616
                if (!startswith(f, old_string)) {
234,052✔
617
                        *(t++) = *(f++);
231,688✔
618
                        continue;
231,688✔
619
                }
620

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

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

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

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

634
        *t = 0;
7,415✔
635
        return ret;
7,415✔
636
}
637

638
static void advance_offsets(
571✔
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)
571✔
645
                return;
646

647
        assert(shift);
561✔
648

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

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

668
        assert(ibuf);
256,688✔
669
        assert(*ibuf);
256,688✔
670
        POINTER_MAY_BE_NULL(_isz);
256,688✔
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);
256,688✔
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);
256,688✔
691
        if (!f)
256,688✔
692
                return NULL;
693

694
        for (const char *i = *ibuf; i < *ibuf + isz + 1; i++) {
30,614,865✔
695

696
                bool eot = i >= *ibuf + isz;
30,358,177✔
697

698
                switch (state) {
30,358,177✔
699

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

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

713
                        if (*i == '\x1B')
30,101,231✔
714
                                state = STATE_ESCAPE;
715
                        else if (*i == '\t') {
30,101,197✔
716
                                fputs("        ", f);
566✔
717
                                advance_offsets(i - *ibuf, highlight, shift, 7);
566✔
718
                        } else
719
                                fputc(*i, f);
30,100,631✔
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;
256,688✔
793
        if (memstream_finalize(&m, &obuf, _isz) < 0)
256,688✔
794
                return NULL;
795

796
        free_and_replace(*ibuf, obuf);
256,688✔
797

798
        if (highlight) {
256,688✔
799
                highlight[0] += shift[0];
256,661✔
800
                highlight[1] += shift[1];
256,661✔
801
        }
802

803
        return *ibuf;
256,688✔
804
}
805

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

812
        if (!x)
31,537,214✔
813
                x = &buffer;
29,409,993✔
814

815
        l = f = strlen_ptr(*x);
31,537,214✔
816

817
        need_separator = !isempty(*x);
31,537,214✔
818
        l_separator = strlen_ptr(separator);
31,537,214✔
819

820
        va_list aq;
31,537,214✔
821
        va_copy(aq, ap);
31,537,214✔
822
        for (const char *t;;) {
118,857,622✔
823
                size_t n;
118,857,622✔
824

825
                t = va_arg(aq, const char *);
118,857,622✔
826
                if (!t)
118,857,622✔
827
                        break;
828
                if (t == POINTER_MAX)
87,320,408✔
829
                        continue;
3✔
830

831
                n = strlen(t);
87,320,405✔
832

833
                if (need_separator)
87,320,405✔
834
                        n += l_separator;
56,990,348✔
835

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

841
                l += n;
87,320,405✔
842
                need_separator = true;
87,320,405✔
843
        }
844
        va_end(aq);
31,537,214✔
845

846
        need_separator = !isempty(*x);
31,537,214✔
847

848
        nr = realloc(*x, GREEDY_ALLOC_ROUND_UP(l+1));
31,537,214✔
849
        if (!nr)
31,537,214✔
850
                return NULL;
851

852
        *x = nr;
31,537,214✔
853
        p = nr + f;
31,537,214✔
854

855
        for (;;) {
118,857,622✔
856
                const char *t;
118,857,622✔
857

858
                t = va_arg(ap, const char *);
118,857,622✔
859
                if (!t)
118,857,622✔
860
                        break;
861
                if (t == POINTER_MAX)
87,320,408✔
862
                        continue;
3✔
863

864
                if (need_separator && separator)
87,320,405✔
865
                        p = stpcpy(p, separator);
165,594✔
866

867
                p = stpcpy(p, t);
87,320,405✔
868

869
                need_separator = true;
87,320,405✔
870
        }
871

872
        assert(p == nr + l);
31,537,214✔
873
        *p = 0;
31,537,214✔
874

875
        /* If no buffer to extend was passed in return the start of the buffer */
876
        if (buffer)
31,537,214✔
877
                return TAKE_PTR(buffer);
29,409,993✔
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, ...) {
31,477,717✔
884
        va_list ap;
31,477,717✔
885
        char *ret;
31,477,717✔
886

887
        va_start(ap, separator);
31,477,717✔
888
        ret = strextendv_with_separator(x, separator, ap);
31,477,717✔
889
        va_end(ap);
31,477,717✔
890

891
        return ret;
31,477,717✔
892
}
893

894
int strextendf_with_separator(char **x, const char *separator, const char *format, ...) {
22,963✔
895
        size_t m, a, l_separator;
22,963✔
896
        va_list ap;
22,963✔
897
        int l;
22,963✔
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);
22,963✔
904
        assert(format);
22,963✔
905

906
        l_separator = isempty(*x) ? 0 : strlen_ptr(separator);
39,733✔
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) {
22,963✔
910
                m = strlen(*x);
16,770✔
911
                a = MALLOC_SIZEOF_SAFE(*x);
16,770✔
912
                assert(a >= m + 1);
16,770✔
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 */
22,963✔
917
                char *n;
12,785✔
918

919
                if (_unlikely_(l_separator > SIZE_MAX - 64)) /* overflow check #1 */
12,785✔
920
                        return -ENOMEM;
22,963✔
921
                if (_unlikely_(m > SIZE_MAX - 64 - l_separator)) /* overflow check #2 */
12,785✔
922
                        return -ENOMEM;
923

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

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

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

938
        assert(l >= 0);
22,963✔
939

940
        if ((size_t) l < a - m - l_separator) {
22,963✔
941
                char *n;
22,443✔
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);
22,443✔
947
                if (n)
22,443✔
948
                        *x = n;
22,443✔
949
        } else {
950
                char *n;
520✔
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 */
520✔
955
                        goto oom;
×
956
                if (_unlikely_(m > SIZE_MAX - ((size_t) l + l_separator + 1))) /* overflow check #2 */
520✔
957
                        goto oom;
×
958

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

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

969
                assert((size_t) l < a - m - l_separator);
520✔
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) {
14✔
981
        char *ret, *p;
14✔
982
        size_t l;
14✔
983

984
        assert(s);
14✔
985

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

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

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

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

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

1007
        const char *x = strstr(s, sep);
1,687✔
1008
        if (!x)
1,687✔
1009
                return -EINVAL;
1,687✔
1010

1011
        _cleanup_free_ char *a = NULL;
308✔
1012
        if (ret_first) {
308✔
1013
                a = strndup(s, x - s);
306✔
1014
                if (!a)
306✔
1015
                        return -ENOMEM;
1016
        }
1017

1018
        _cleanup_free_ char *b = NULL;
308✔
1019
        if (ret_second) {
308✔
1020
                b = strdup(x + strlen(sep));
306✔
1021
                if (!b)
306✔
1022
                        return -ENOMEM;
1023
        }
1024

1025
        if (ret_first)
308✔
1026
                *ret_first = TAKE_PTR(a);
306✔
1027
        if (ret_second)
308✔
1028
                *ret_second = TAKE_PTR(b);
306✔
1029
        return 0;
1030
}
1031

1032
int free_and_strdup(char **p, const char *s) {
2,351,363✔
1033
        char *t;
2,351,363✔
1034

1035
        assert(p);
2,351,363✔
1036

1037
        /* Replaces a string pointer with a strdup()ed new string,
1038
         * possibly freeing the old one. */
1039

1040
        if (streq_ptr(*p, s))
2,351,363✔
1041
                return 0;
2,351,363✔
1042

1043
        if (s) {
1,887,348✔
1044
                t = strdup(s);
1,879,028✔
1045
                if (!t)
1,879,028✔
1046
                        return -ENOMEM;
1047
        } else
1048
                t = NULL;
1049

1050
        free_and_replace(*p, t);
1,887,348✔
1051

1052
        return 1;
1,887,348✔
1053
}
1054

1055
int free_and_strdup_warn(char **p, const char *s) {
95,165✔
1056
        int r;
95,165✔
1057

1058
        r = free_and_strdup(p, s);
95,165✔
1059
        if (r < 0)
95,165✔
UNCOV
1060
                return log_oom();
×
1061
        return r;
1062
}
1063

1064
int free_and_strndup(char **p, const char *s, size_t l) {
78,905✔
1065
        char *t;
78,905✔
1066

1067
        assert(p);
78,905✔
1068
        assert(s || l == 0);
78,905✔
1069

1070
        /* Replaces a string pointer with a strndup()ed new string,
1071
         * freeing the old one. */
1072

1073
        if (!*p && !s)
78,905✔
1074
                return 0;
78,905✔
1075

1076
        if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
78,905✔
1077
                return 0;
1078

1079
        if (s) {
36,989✔
1080
                t = strndup(s, l);
37,060✔
1081
                if (!t)
37,060✔
1082
                        return -ENOMEM;
1083
        } else
1084
                t = NULL;
1085

1086
        free_and_replace(*p, t);
37,061✔
1087
        return 1;
37,061✔
1088
}
1089

1090
int strdup_to_full(char **ret, const char *src) {
852,754✔
1091
        if (!src) {
852,754✔
1092
                if (ret)
307,061✔
1093
                        *ret = NULL;
307,060✔
1094

1095
                return 0;
1096
        } else {
1097
                if (ret) {
545,693✔
1098
                        char *t = strdup(src);
534,434✔
1099
                        if (!t)
534,434✔
1100
                                return -ENOMEM;
1101
                        *ret = t;
534,434✔
1102
                }
1103

1104
                return 1;
1105
        }
1106
};
1107

1108
bool string_is_safe(const char *p, StringSafeFlags flags) {
13,923,931✔
1109

1110
        /* Baseline checks are:
1111
         *   • No control characters (i.e. 0…31 + 127)
1112
         *   • UTF-8 valid (well, technically we skip this test if STRING_ASCII is set, since that is a tighter test)
1113
         */
1114

1115
        if (FLAGS_SET(flags, STRING_ALLOW_EMPTY) ? !p : isempty(p))
13,923,931✔
1116
                return false;
1117

1118
        if (!FLAGS_SET(flags, STRING_ASCII) && !utf8_is_valid(p))
27,846,778✔
1119
                return false;
1120

1121
        for (const char *t = p; *t; t++) {
260,666,232✔
1122
                /* never allow control characters, except for new line */
1123
                if ((*t > 0 && *t < ' ' && *t != '\n') || *t == 0x7f)
246,742,393✔
1124
                        return false;
1125

1126
                if (!FLAGS_SET(flags, STRING_ALLOW_NEWLINES) && *t == '\n')
246,742,368✔
1127
                        return false;
1128

1129
                if (!FLAGS_SET(flags, STRING_ALLOW_BACKSLASHES) && *t == '\\')
246,742,359✔
1130
                        return false;
1131

1132
                if (!FLAGS_SET(flags, STRING_ALLOW_QUOTES) && strchr(QUOTES, *t))
246,742,350✔
1133
                        return false;
1134

1135
                if (!FLAGS_SET(flags, STRING_ALLOW_GLOBS) && strchr(GLOB_CHARS, *t))
246,742,339✔
1136
                        return false;
1137

1138
                if (FLAGS_SET(flags, STRING_DISALLOW_WHITESPACE) && strchr(WHITESPACE, *t))
246,742,331✔
1139
                        return false;
1140

1141
                if (FLAGS_SET(flags, STRING_ASCII) && (uint8_t) *t >= 0x80)
246,742,326✔
1142
                        return false;
1143
        }
1144

1145
        if (FLAGS_SET(flags, STRING_FILENAME) && !filename_is_valid(p))
13,923,839✔
1146
                return false;
1147

1148
        if (FLAGS_SET(flags, STRING_FILENAME_PART) && !filename_part_is_valid(p))
13,923,827✔
1149
                return false;
7✔
1150

1151
        return true;
1152
}
1153

1154
char* str_realloc(char *p) {
56,705✔
1155
        /* Reallocate *p to actual size. Ignore failure, and return the original string on error. */
1156

1157
        if (!p)
56,705✔
1158
                return NULL;
1159

1160
        return realloc(p, strlen(p) + 1) ?: p;
56,705✔
1161
}
1162

1163
char* string_erase(char *x) {
124✔
1164
        if (!x)
124✔
1165
                return NULL;
1166

1167
        /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1168
         * used them. */
1169
        explicit_bzero_safe(x, strlen(x));
124✔
1170
        return x;
124✔
1171
}
1172

1173
int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
300✔
1174
        const char *p = s, *e = s;
300✔
1175
        bool truncation_applied = false;
300✔
1176
        char *copy;
300✔
1177
        size_t n = 0;
300✔
1178

1179
        assert(s);
300✔
1180
        assert(ret);
300✔
1181

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

1186
        for (;;) {
530✔
1187
                size_t k;
415✔
1188

1189
                k = strcspn(p, "\n");
415✔
1190

1191
                if (p[k] == 0) {
415✔
1192
                        if (k == 0) /* final empty line */
268✔
1193
                                break;
1194

1195
                        if (n >= n_lines) /* above threshold */
243✔
1196
                                break;
1197

1198
                        e = p + k; /* last line to include */
226✔
1199
                        break;
226✔
1200
                }
1201

1202
                assert(p[k] == '\n');
147✔
1203

1204
                if (n >= n_lines)
147✔
1205
                        break;
1206

1207
                if (k > 0)
115✔
1208
                        e = p + k;
92✔
1209

1210
                p += k + 1;
115✔
1211
                n++;
115✔
1212
        }
1213

1214
        /* e points after the last character we want to keep */
1215
        if (isempty(e))
300✔
1216
                copy = strdup(s);
230✔
1217
        else {
1218
                if (!in_charset(e, "\n")) /* We only consider things truncated if we remove something that
70✔
1219
                                           * isn't a new-line or a series of them */
1220
                        truncation_applied = true;
42✔
1221

1222
                copy = strndup(s, e - s);
70✔
1223
        }
1224
        if (!copy)
300✔
1225
                return -ENOMEM;
1226

1227
        *ret = copy;
300✔
1228
        return truncation_applied;
300✔
1229
}
1230

1231
int string_extract_line(const char *s, size_t i, char **ret) {
228,715✔
1232
        const char *p = s;
228,715✔
1233
        size_t c = 0;
228,715✔
1234

1235
        assert(ret);
228,715✔
1236

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

1243
        for (;;) {
416,413✔
1244
                const char *q;
322,564✔
1245

1246
                q = strchr(p, '\n');
322,564✔
1247
                if (i == c) {
322,564✔
1248
                        /* The line we are looking for! */
1249

1250
                        if (q) {
224,949✔
1251
                                char *m;
3,897✔
1252

1253
                                m = strndup(p, q - p);
3,897✔
1254
                                if (!m)
3,897✔
1255
                                        return -ENOMEM;
1256

1257
                                *ret = m;
3,897✔
1258
                                return !isempty(q + 1); /* More coming? */
7,794✔
1259
                        } else
1260
                                /* Tell the caller to use the input string if equal */
1261
                                return strdup_to(ret, p != s ? p : NULL);
440,280✔
1262
                }
1263

1264
                if (!q)
97,615✔
1265
                        /* No more lines, return empty line */
1266
                        return strdup_to(ret, "");
3,766✔
1267

1268
                p = q + 1;
93,849✔
1269
                c++;
93,849✔
1270
        }
1271
}
1272

1273
int string_contains_word_strv(const char *string, const char *separators, char * const *words, const char **ret_word) {
75✔
1274
        /* In the default mode with no separators specified, we split on whitespace and coalesce separators. */
1275
        const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
75✔
1276
        const char *found = NULL;
75✔
1277
        int r;
202✔
1278

1279
        for (;;) {
329✔
1280
                _cleanup_free_ char *w = NULL;
127✔
1281

1282
                r = extract_first_word(&string, &w, separators, flags);
202✔
1283
                if (r < 0)
202✔
UNCOV
1284
                        return r;
×
1285
                if (r == 0)
202✔
1286
                        break;
1287

1288
                found = strv_find(words, w);
148✔
1289
                if (found)
148✔
1290
                        break;
1291
        }
1292

1293
        if (ret_word)
75✔
1294
                *ret_word = found;
7✔
1295
        return !!found;
75✔
1296
}
1297

1298
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
8,827✔
1299
        if (!s1 && !s2)
8,827✔
1300
                return true;
1301
        if (!s1 || !s2)
8,826✔
1302
                return false;
1303

1304
        if (!ok)
8,824✔
1305
                ok = WHITESPACE;
13✔
1306

1307
        for (; *s1 && *s2; s1++, s2++)
16,885✔
1308
                if (*s1 != *s2)
10,284✔
1309
                        break;
1310

1311
        return in_charset(s1, ok) && in_charset(s2, ok);
11,053✔
1312
}
1313

1314
char* string_replace_char(char *str, char old_char, char new_char) {
622,490✔
1315
        assert(str);
622,490✔
1316
        assert(old_char != '\0');
622,490✔
1317
        assert(new_char != '\0');
622,490✔
1318
        assert(old_char != new_char);
622,490✔
1319

1320
        for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
627,898✔
1321
                *p = new_char;
5,408✔
1322

1323
        return str;
622,490✔
1324
}
1325

1326
int make_cstring(const void *s, size_t n, MakeCStringMode mode, char **ret) {
10,162✔
1327
        char *b;
10,162✔
1328

1329
        assert(s || n == 0);
10,162✔
1330
        assert(mode >= 0);
10,162✔
1331
        assert(mode < _MAKE_CSTRING_MODE_MAX);
10,162✔
1332

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

1336
        if (n == 0) {
10,162✔
1337
                if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
20✔
1338
                        return -EINVAL;
1339

1340
                if (!ret)
19✔
1341
                        return 0;
1342

1343
                b = new0(char, 1);
19✔
1344
        } else {
1345
                const uint8_t *nul;
10,142✔
1346

1347
                nul = memchr(s, 0, n);
10,142✔
1348
                if (nul) {
10,142✔
1349
                        if (nul < (const uint8_t*) s + n - 1 || /* embedded NUL? */
29✔
1350
                            mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
1351
                                return -EINVAL;
1352

1353
                        n--;
1354
                } else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
10,113✔
1355
                        return -EINVAL;
1356

1357
                if (!ret)
10,131✔
1358
                        return 0;
1359

1360
                b = memdup_suffix0(s, n);
10,131✔
1361
        }
1362
        if (!b)
10,150✔
1363
                return -ENOMEM;
1364

1365
        *ret = b;
10,150✔
1366
        return 0;
10,150✔
1367
}
1368

1369
size_t strspn_from_end(const char *str, const char *accept) {
588,016✔
1370
        size_t n = 0;
588,016✔
1371

1372
        if (isempty(str))
588,016✔
1373
                return 0;
1374

1375
        if (isempty(accept))
588,013✔
1376
                return 0;
1377

1378
        for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
1,136,795✔
1379
                n++;
548,783✔
1380

1381
        return n;
1382
}
1383

1384
char* strdupspn(const char *a, const char *accept) {
×
UNCOV
1385
        if (isempty(a) || isempty(accept))
×
1386
                return strdup("");
×
1387

UNCOV
1388
        return strndup(a, strspn(a, accept));
×
1389
}
1390

1391
char* strdupcspn(const char *a, const char *reject) {
40,824✔
1392
        if (isempty(a))
40,824✔
UNCOV
1393
                return strdup("");
×
1394
        if (isempty(reject))
40,824✔
UNCOV
1395
                return strdup(a);
×
1396

1397
        return strndup(a, strcspn(a, reject));
40,824✔
1398
}
1399

1400
char* find_line_startswith_internal(const char *haystack, const char *needle) {
3,444✔
1401
        assert(haystack);
3,444✔
1402
        assert(needle);
3,444✔
1403

1404
        /* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
1405
         * first character after it */
1406

1407
        char *p = (char*) strstr(haystack, needle);
3,444✔
1408
        if (!p)
3,444✔
1409
                return NULL;
1410

1411
        if (p > haystack)
792✔
1412
                while (p[-1] != '\n') {
66✔
1413
                        p = strstr(p + 1, needle);
9✔
1414
                        if (!p)
9✔
1415
                                return NULL;
1416
                }
1417

1418
        return p + strlen(needle);
791✔
1419
}
1420

UNCOV
1421
char* find_line_internal(const char *haystack, const char *needle) {
×
UNCOV
1422
        assert(haystack);
×
1423
        assert(needle);
×
1424

1425
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1426
         * beginning of the line */
1427

UNCOV
1428
        char *p = (char*) find_line_startswith(haystack, needle);
×
1429
        if (!p)
×
1430
                return NULL;
1431

UNCOV
1432
        if (*p == 0 || strchr(NEWLINE, *p))
×
UNCOV
1433
                return p - strlen(needle);
×
1434

1435
        return NULL;
1436
}
1437

UNCOV
1438
char* find_line_after_internal(const char *haystack, const char *needle) {
×
UNCOV
1439
        assert(haystack);
×
1440
        assert(needle);
×
1441

1442
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1443
         * next line after it */
1444

UNCOV
1445
        char *p = (char*) find_line_startswith(haystack, needle);
×
UNCOV
1446
        if (!p)
×
1447
                return NULL;
1448

UNCOV
1449
        if (*p == 0)
×
1450
                return p;
UNCOV
1451
        if (strchr(NEWLINE, *p))
×
UNCOV
1452
                return p + 1;
×
1453

1454
        return NULL;
1455
}
1456

1457
bool version_is_valid(const char *s) {
37,302✔
1458
        if (isempty(s))
37,302✔
1459
                return false;
1460

1461
        if (!filename_part_is_valid(s))
37,300✔
1462
                return false;
1463

1464
        /* This is a superset of the characters used by semver. We additionally allow "," and "_". */
1465
        if (!in_charset(s, ALPHANUMERICAL ".,_-+"))
37,300✔
UNCOV
1466
                return false;
×
1467

1468
        return true;
1469
}
1470

1471
bool version_is_valid_versionspec(const char *s) {
97✔
1472
        if (!filename_part_is_valid(s))
97✔
1473
                return false;
1474

1475
        if (!in_charset(s, ALPHANUMERICAL "-.~^"))
97✔
UNCOV
1476
                return false;
×
1477

1478
        return true;
1479
}
1480

1481
ssize_t strlevenshtein(const char *x, const char *y) {
122✔
1482
        _cleanup_free_ size_t *t0 = NULL, *t1 = NULL, *t2 = NULL;
244✔
1483
        size_t xl, yl;
122✔
1484

1485
        /* This is inspired from the Linux kernel's Levenshtein implementation */
1486

1487
        if (streq_ptr(x, y))
122✔
1488
                return 0;
1489

1490
        xl = strlen_ptr(x);
118✔
1491
        if (xl > SSIZE_MAX)
117✔
1492
                return -E2BIG;
1493

1494
        yl = strlen_ptr(y);
118✔
1495
        if (yl > SSIZE_MAX)
117✔
1496
                return -E2BIG;
1497

1498
        if (isempty(x))
118✔
1499
                return yl;
3✔
1500
        if (isempty(y))
115✔
1501
                return xl;
1✔
1502

1503
        t0 = new0(size_t, yl + 1);
114✔
1504
        if (!t0)
114✔
1505
                return -ENOMEM;
1506
        t1 = new0(size_t, yl + 1);
114✔
1507
        if (!t1)
114✔
1508
                return -ENOMEM;
1509
        t2 = new0(size_t, yl + 1);
114✔
1510
        if (!t2)
114✔
1511
                return -ENOMEM;
1512

1513
        for (size_t i = 0; i <= yl; i++)
1,249✔
1514
                t1[i] = i;
1,135✔
1515

1516
        for (size_t i = 0; i < xl; i++) {
712✔
1517
                t2[0] = i + 1;
598✔
1518

1519
                for (size_t j = 0; j < yl; j++) {
6,439✔
1520
                        /* Substitution */
1521
                        t2[j+1] = t1[j] + (x[i] != y[j]);
5,841✔
1522

1523
                        /* Swap */
1524
                        if (i > 0 && j > 0 && x[i-1] == y[j] && x[i] == y[j-1] && t2[j+1] > t0[j-1] + 1)
5,841✔
1525
                                t2[j+1] = t0[j-1] + 1;
14✔
1526

1527
                        /* Deletion */
1528
                        if (t2[j+1] > t1[j+1] + 1)
5,841✔
1529
                                t2[j+1] = t1[j+1] + 1;
247✔
1530

1531
                        /* Insertion */
1532
                        if (t2[j+1] > t2[j] + 1)
5,841✔
1533
                                t2[j+1] = t2[j] + 1;
880✔
1534
                }
1535

1536
                size_t *dummy = t0;
1537
                t0 = t1;
1538
                t1 = t2;
1539
                t2 = dummy;
1540
        }
1541

1542
        return t1[yl];
114✔
1543
}
1544

1545
char* strrstr_internal(const char *haystack, const char *needle) {
25,301✔
1546
        /* Like strstr() but returns the last rather than the first occurrence of "needle" in "haystack". */
1547

1548
        if (!haystack || !needle)
25,301✔
1549
                return NULL;
1550

1551
        /* Special case: for the empty string we return the very last possible occurrence, i.e. *after* the
1552
         * last char, not before. */
1553
        if (needle[0] == 0)
25,298✔
1554
                return (char*) strchr(haystack, 0);
2✔
1555

1556
        /* Special case: for single character strings, just use optimized strrchr() */
1557
        if (needle[1] == 0)
25,296✔
1558
                return (char*) strrchr(haystack, needle[0]);
3✔
1559

1560
        for (const char *p = strstr(haystack, needle), *q; p; p = q) {
25,299✔
1561
                q = strstr(p + 1, needle);
18✔
1562
                if (!q)
18✔
1563
                        return (char*) p;
1564
        }
1565
        return NULL;
1566
}
1567

1568
char* strrstr_no_case_internal(const char *haystack, const char *needle) {
41✔
1569
        if (!haystack || !needle)
41✔
1570
                return NULL;
1571

1572
        for (const char *p = strchr(haystack, 0); p > haystack; p--)
438✔
1573
                if (startswith_no_case(p, needle))
431✔
1574
                        return (char*) p;
1575

1576
        return startswith_no_case(haystack, needle) ? (char*) haystack : NULL;
7✔
1577
}
1578

1579
size_t str_common_prefix(const char *a, const char *b) {
866✔
1580
        assert(a);
866✔
1581
        assert(b);
866✔
1582

1583
        /* Returns the length of the common prefix of the two specified strings, or SIZE_MAX in case the
1584
         * strings are fully identical. */
1585

1586
        for (size_t n = 0;; n++) {
731✔
1587
                char c = a[n];
1,597✔
1588
                if (c != b[n])
1,597✔
1589
                        return n;
1590
                if (c == 0)
734✔
1591
                        return SIZE_MAX;
1592
        }
1593
}
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