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

systemd / systemd / 27854786886

20 Jun 2026 12:28AM UTC coverage: 73.048% (+0.05%) from 72.995%
27854786886

push

github

bluca
report: disable json normalization

Two PRs got merged at the same time, which cause a test to fail,
as they work individually but fail when combined

TEST-74-AUX-UTILS.sh[1688]: + /usr/lib/systemd/systemd-report generate io.systemd.Manager.UnitsTotal
TEST-74-AUX-UTILS.sh[1805]: {"mediaType":"application/vnd.io.systemd.report","metrics":[{"name":"io.systemd.Manager.UnitsTotal","value":249}],"timestamp":"Fri 2026-06-19 19:50:48 UTC"}
TEST-74-AUX-UTILS.sh[1806]: + /usr/lib/systemd/systemd-report generate io.systemd.Manager.UnitsTotal
TEST-74-AUX-UTILS.sh[1807]: + jq .
TEST-74-AUX-UTILS.sh[1807]: {
TEST-74-AUX-UTILS.sh[1807]:   "mediaType": "application/vnd.io.systemd.report",
TEST-74-AUX-UTILS.sh[1807]:   "metrics": [
TEST-74-AUX-UTILS.sh[1807]: {
TEST-74-AUX-UTILS.sh[1807]:   "name": "io.systemd.Manager.UnitsTotal",
TEST-74-AUX-UTILS.sh[1807]:   "value": 249
TEST-74-AUX-UTILS.sh[1807]: }
TEST-74-AUX-UTILS.sh[1807]:   ],
TEST-74-AUX-UTILS.sh[1807]:   "timestamp": "Fri 2026-06-19 19:50:48 UTC"
TEST-74-AUX-UTILS.sh[1807]: }
TEST-74-AUX-UTILS.sh[1688]: + /usr/lib/systemd/systemd-report upload --url=http://localhost:8089/
TEST-74-AUX-UTILS.sh[1808]: Failed to normalize report JSON: Wrong medium type

https://github.com/systemd/systemd/pull/42594
https://github.com/systemd/systemd/pull/42595

Disable normalization for now, and track the issue at
https://github.com/systemd/systemd/issues/42669

Follow-up for 3c2f7c600

339084 of 464191 relevant lines covered (73.05%)

1311580.8 hits per line

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

91.85
/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,525,949✔
21
        assert(s);
4,525,949✔
22
        assert(word);
4,525,949✔
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,525,949✔
28
                return (char*) s;
29

30
        const char *p = startswith(s, word);
4,525,948✔
31
        if (!p)
4,525,948✔
32
                return NULL;
33
        if (*p == '\0')
232,742✔
34
                return (char*) p;
35

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

40
        return (char*) nw;
41
}
42

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

47
        if (l > 0)
33,641✔
48
                l = strnlen(s, l); /* ignore trailing noise */
33,303✔
49

50
        if (l > 0 || !*x) {
33,641✔
51
                size_t q;
33,479✔
52
                char *m;
33,479✔
53

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

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

61
                *x = m;
33,479✔
62
        }
63

64
        return *x;
33,641✔
65
}
66

67
char* strstrip(char *s) {
9,514,521✔
68
        if (!s)
9,514,521✔
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,511,659✔
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,101,152✔
100
        char *c = s;
11,101,152✔
101

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

104
        if (!s)
11,101,152✔
105
                return NULL;
106

107
        if (!bad)
11,101,152✔
108
                bad = WHITESPACE;
90,388✔
109

110
        for (char *p = s; *p; p++)
366,009,375✔
111
                if (!strchr(bad, *p))
354,908,223✔
112
                        c = p + 1;
340,597,416✔
113

114
        *c = 0;
11,101,152✔
115

116
        return s;
11,101,152✔
117
}
118

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

122
        assert(s);
2,839,461✔
123

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

131
char ascii_tolower(char x) {
51,392,071✔
132

133
        if (x >= 'A' && x <= 'Z')
51,392,071✔
134
                return x - 'A' + 'a';
3,522,952✔
135

136
        return x;
137
}
138

139
char ascii_toupper(char x) {
321,661✔
140

141
        if (x >= 'a' && x <= 'z')
321,661✔
142
                return x - 'a' + 'A';
193,164✔
143

144
        return x;
145
}
146

147
char* ascii_strlower(char *s) {
24,796✔
148
        assert(s);
24,796✔
149

150
        for (char *p = s; *p; p++)
160,777✔
151
                *p = ascii_tolower(*p);
135,981✔
152

153
        return s;
24,796✔
154
}
155

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

159
        for (char *p = s; *p; p++)
343,870✔
160
                *p = ascii_toupper(*p);
321,531✔
161

162
        return s;
22,339✔
163
}
164

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

169
        for (size_t i = 0; i < n; i++)
15,139,359✔
170
                s[i] = ascii_tolower(s[i]);
13,316,113✔
171

172
        return s;
173
}
174

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

177
        assert(a);
2,545,233✔
178
        assert(b);
2,545,233✔
179

180
        for (; n > 0; a++, b++, n--) {
20,918,104✔
181
                int x, y;
18,965,400✔
182

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

186
                if (x != y)
18,965,400✔
187
                        return x - y;
592,529✔
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,102,531✔
194
        int r;
1,102,531✔
195

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

200
        return CMP(n, m);
972,678✔
201
}
202

203
bool chars_intersect(const char *a, const char *b) {
12,733✔
204
        /* Returns true if any of the chars in a are in b. */
205
        for (const char *p = a; *p; p++)
183,449✔
206
                if (strchr(b, *p))
170,736✔
207
                        return true;
208

209
        return false;
210
}
211

212
bool string_has_cc(const char *p, const char *ok) {
287,266✔
213
        assert(p);
287,266✔
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,658,135✔
222
                if (ok && strchr(ok, *t))
2,370,885✔
223
                        continue;
8✔
224

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

229
        return false;
230
}
231

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

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

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

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

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

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

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

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

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

349
        return t;
2,551✔
350
}
351

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

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

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

378
        bool has_ansi_seq = string_has_ansi_sequence(s, old_length);
7,947✔
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,947✔
382
                return ascii_ellipsize_mem(s, old_length, new_length, percent);
4,394✔
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,918✔
389
                size_t slen = has_ansi_seq ? ansi_sequence_length(i, old_length - (i - s)) : 0;
48,726✔
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,502✔
396
                r = utf8_encoded_to_unichar(i, &c);
48,502✔
397
                if (r < 0)
48,502✔
398
                        return NULL;
×
399

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

404
                k += w;
46,141✔
405
                i += r;
46,141✔
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) {
57,497✔
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;
57,497✔
501

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

506
        for (;;) {
1,242,295✔
507
                char four[4];
649,896✔
508
                int w;
649,896✔
509

510
                if (*s == 0) /* terminating NUL detected? then we are done! */
649,896✔
511
                        goto done;
57,461✔
512

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

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

526
                s++;
592,399✔
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';
57,497✔
556
        return buf;
57,497✔
557
}
558

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

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

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

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

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

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

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

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

616
                if (!startswith(f, old_string)) {
234,096✔
617
                        *(t++) = *(f++);
231,732✔
618
                        continue;
231,732✔
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,419✔
635
        return ret;
7,419✔
636
}
637

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

647
        assert(shift);
555✔
648

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

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

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

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

696
                bool eot = i >= *ibuf + isz;
30,116,797✔
697

698
                switch (state) {
30,116,797✔
699

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

704
                        if (*i == '\r') {
29,862,798✔
705
                                n_carriage_returns++;
7✔
706
                                break;
7✔
707
                        } else if (*i == '\n')
29,862,791✔
708
                                /* Ignore carriage returns before new line */
709
                                n_carriage_returns = 0;
2✔
710
                        for (; n_carriage_returns > 0; n_carriage_returns--)
29,862,793✔
711
                                fputc('\r', f);
2✔
712

713
                        if (*i == '\x1B')
29,862,791✔
714
                                state = STATE_ESCAPE;
715
                        else if (*i == '\t') {
29,862,757✔
716
                                fputs("        ", f);
560✔
717
                                advance_offsets(i - *ibuf, highlight, shift, 7);
560✔
718
                        } else
719
                                fputc(*i, f);
29,862,197✔
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;
253,748✔
793
        if (memstream_finalize(&m, &obuf, _isz) < 0)
253,748✔
794
                return NULL;
795

796
        free_and_replace(*ibuf, obuf);
253,748✔
797

798
        if (highlight) {
253,748✔
799
                highlight[0] += shift[0];
253,721✔
800
                highlight[1] += shift[1];
253,721✔
801
        }
802

803
        return *ibuf;
253,748✔
804
}
805

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

812
        if (!x)
31,807,999✔
813
                x = &buffer;
29,677,320✔
814

815
        l = f = strlen_ptr(*x);
31,807,999✔
816

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

820
        va_list aq;
31,807,999✔
821
        va_copy(aq, ap);
31,807,999✔
822
        for (const char *t;;) {
119,880,795✔
823
                size_t n;
119,880,795✔
824

825
                t = va_arg(aq, const char *);
119,880,795✔
826
                if (!t)
119,880,795✔
827
                        break;
828
                if (t == POINTER_MAX)
88,072,796✔
829
                        continue;
3✔
830

831
                n = strlen(t);
88,072,793✔
832

833
                if (need_separator)
88,072,793✔
834
                        n += l_separator;
57,473,669✔
835

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

841
                l += n;
88,072,793✔
842
                need_separator = true;
88,072,793✔
843
        }
844
        va_end(aq);
31,807,999✔
845

846
        need_separator = !isempty(*x);
31,807,999✔
847

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

852
        *x = nr;
31,807,999✔
853
        p = nr + f;
31,807,999✔
854

855
        for (;;) {
119,880,795✔
856
                const char *t;
119,880,795✔
857

858
                t = va_arg(ap, const char *);
119,880,795✔
859
                if (!t)
119,880,795✔
860
                        break;
861
                if (t == POINTER_MAX)
88,072,796✔
862
                        continue;
3✔
863

864
                if (need_separator && separator)
88,072,793✔
865
                        p = stpcpy(p, separator);
167,500✔
866

867
                p = stpcpy(p, t);
88,072,793✔
868

869
                need_separator = true;
88,072,793✔
870
        }
871

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

875
        /* If no buffer to extend was passed in return the start of the buffer */
876
        if (buffer)
31,807,999✔
877
                return TAKE_PTR(buffer);
29,677,320✔
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,747,504✔
884
        va_list ap;
31,747,504✔
885
        char *ret;
31,747,504✔
886

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

891
        return ret;
31,747,504✔
892
}
893

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

906
        l_separator = isempty(*x) ? 0 : strlen_ptr(separator);
40,388✔
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) {
23,347✔
910
                m = strlen(*x);
17,041✔
911
                a = MALLOC_SIZEOF_SAFE(*x);
17,041✔
912
                assert(a >= m + 1);
17,041✔
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 */
23,347✔
917
                char *n;
12,980✔
918

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

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

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

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

938
        assert(l >= 0);
23,347✔
939

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

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

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

969
                assert((size_t) l < a - m - l_separator);
533✔
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,704✔
1004
        assert(s);
1,704✔
1005
        assert(!isempty(sep));
1,704✔
1006
        assert(ret_first);
1,704✔
1007
        assert(ret_second);
1,704✔
1008

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

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

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

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

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

1029
        assert(p);
2,387,276✔
1030

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

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

1037
        if (s) {
1,913,794✔
1038
                t = strdup(s);
1,905,481✔
1039
                if (!t)
1,905,481✔
1040
                        return -ENOMEM;
1041
        } else
1042
                t = NULL;
1043

1044
        free_and_replace(*p, t);
1,913,794✔
1045

1046
        return 1;
1,913,794✔
1047
}
1048

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

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

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

1061
        assert(p);
78,836✔
1062
        assert(s || l == 0);
78,836✔
1063

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

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

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

1073
        if (s) {
36,972✔
1074
                t = strndup(s, l);
37,043✔
1075
                if (!t)
37,043✔
1076
                        return -ENOMEM;
1077
        } else
1078
                t = NULL;
1079

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

1084
int strdup_to_full(char **ret, const char *src) {
862,023✔
1085
        if (!src) {
862,023✔
1086
                if (ret)
312,790✔
1087
                        *ret = NULL;
312,789✔
1088

1089
                return 0;
1090
        } else {
1091
                if (ret) {
549,233✔
1092
                        char *t = strdup(src);
537,800✔
1093
                        if (!t)
537,800✔
1094
                                return -ENOMEM;
1095
                        *ret = t;
537,800✔
1096
                }
1097

1098
                return 1;
1099
        }
1100
};
1101

1102
bool string_is_safe(const char *p, StringSafeFlags flags) {
13,978,689✔
1103

1104
        /* Baseline checks are:
1105
         *   • No control characters (i.e. 0…31 + 127)
1106
         *   • UTF-8 valid (well, technically we skip this test if STRING_ASCII is set, since that is a tighter test)
1107
         */
1108

1109
        if (FLAGS_SET(flags, STRING_ALLOW_EMPTY) ? !p : isempty(p))
13,978,689✔
1110
                return false;
1111

1112
        if (!FLAGS_SET(flags, STRING_ASCII) && !utf8_is_valid(p))
27,956,304✔
1113
                return false;
1114

1115
        for (const char *t = p; *t; t++) {
261,701,803✔
1116
                /* never allow control characters, except for new line */
1117
                if ((*t > 0 && *t < ' ' && *t != '\n') || *t == 0x7f)
247,723,200✔
1118
                        return false;
1119

1120
                if (!FLAGS_SET(flags, STRING_ALLOW_NEWLINES) && *t == '\n')
247,723,177✔
1121
                        return false;
1122

1123
                if (!FLAGS_SET(flags, STRING_ALLOW_BACKSLASHES) && *t == '\\')
247,723,169✔
1124
                        return false;
1125

1126
                if (!FLAGS_SET(flags, STRING_ALLOW_QUOTES) && strchr(QUOTES, *t))
247,723,160✔
1127
                        return false;
1128

1129
                if (!FLAGS_SET(flags, STRING_ALLOW_GLOBS) && strchr(GLOB_CHARS, *t))
247,723,149✔
1130
                        return false;
1131

1132
                if (FLAGS_SET(flags, STRING_DISALLOW_WHITESPACE) && strchr(WHITESPACE, *t))
247,723,141✔
1133
                        return false;
1134

1135
                if (FLAGS_SET(flags, STRING_ASCII) && (uint8_t) *t >= 0x80)
247,723,136✔
1136
                        return false;
1137
        }
1138

1139
        if (FLAGS_SET(flags, STRING_FILENAME) && !filename_is_valid(p))
13,978,603✔
1140
                return false;
12✔
1141

1142
        return true;
1143
}
1144

1145
char* str_realloc(char *p) {
57,559✔
1146
        /* Reallocate *p to actual size. Ignore failure, and return the original string on error. */
1147

1148
        if (!p)
57,559✔
1149
                return NULL;
1150

1151
        return realloc(p, strlen(p) + 1) ?: p;
57,559✔
1152
}
1153

1154
char* string_erase(char *x) {
124✔
1155
        if (!x)
124✔
1156
                return NULL;
1157

1158
        /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1159
         * used them. */
1160
        explicit_bzero_safe(x, strlen(x));
124✔
1161
        return x;
124✔
1162
}
1163

1164
int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
300✔
1165
        const char *p = s, *e = s;
300✔
1166
        bool truncation_applied = false;
300✔
1167
        char *copy;
300✔
1168
        size_t n = 0;
300✔
1169

1170
        assert(s);
300✔
1171
        assert(ret);
300✔
1172

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

1177
        for (;;) {
530✔
1178
                size_t k;
415✔
1179

1180
                k = strcspn(p, "\n");
415✔
1181

1182
                if (p[k] == 0) {
415✔
1183
                        if (k == 0) /* final empty line */
268✔
1184
                                break;
1185

1186
                        if (n >= n_lines) /* above threshold */
243✔
1187
                                break;
1188

1189
                        e = p + k; /* last line to include */
226✔
1190
                        break;
226✔
1191
                }
1192

1193
                assert(p[k] == '\n');
147✔
1194

1195
                if (n >= n_lines)
147✔
1196
                        break;
1197

1198
                if (k > 0)
115✔
1199
                        e = p + k;
92✔
1200

1201
                p += k + 1;
115✔
1202
                n++;
115✔
1203
        }
1204

1205
        /* e points after the last character we want to keep */
1206
        if (isempty(e))
300✔
1207
                copy = strdup(s);
230✔
1208
        else {
1209
                if (!in_charset(e, "\n")) /* We only consider things truncated if we remove something that
70✔
1210
                                           * isn't a new-line or a series of them */
1211
                        truncation_applied = true;
42✔
1212

1213
                copy = strndup(s, e - s);
70✔
1214
        }
1215
        if (!copy)
300✔
1216
                return -ENOMEM;
1217

1218
        *ret = copy;
300✔
1219
        return truncation_applied;
300✔
1220
}
1221

1222
int string_extract_line(const char *s, size_t i, char **ret) {
232,395✔
1223
        const char *p = s;
232,395✔
1224
        size_t c = 0;
232,395✔
1225

1226
        assert(ret);
232,395✔
1227

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

1234
        for (;;) {
420,335✔
1235
                const char *q;
326,365✔
1236

1237
                q = strchr(p, '\n');
326,365✔
1238
                if (i == c) {
326,365✔
1239
                        /* The line we are looking for! */
1240

1241
                        if (q) {
228,556✔
1242
                                char *m;
3,970✔
1243

1244
                                m = strndup(p, q - p);
3,970✔
1245
                                if (!m)
3,970✔
1246
                                        return -ENOMEM;
1247

1248
                                *ret = m;
3,970✔
1249
                                return !isempty(q + 1); /* More coming? */
7,940✔
1250
                        } else
1251
                                /* Tell the caller to use the input string if equal */
1252
                                return strdup_to(ret, p != s ? p : NULL);
447,310✔
1253
                }
1254

1255
                if (!q)
97,809✔
1256
                        /* No more lines, return empty line */
1257
                        return strdup_to(ret, "");
3,839✔
1258

1259
                p = q + 1;
93,970✔
1260
                c++;
93,970✔
1261
        }
1262
}
1263

1264
int string_contains_word_strv(const char *string, const char *separators, char * const *words, const char **ret_word) {
75✔
1265
        /* In the default mode with no separators specified, we split on whitespace and coalesce separators. */
1266
        const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
75✔
1267
        const char *found = NULL;
75✔
1268
        int r;
202✔
1269

1270
        for (;;) {
329✔
1271
                _cleanup_free_ char *w = NULL;
127✔
1272

1273
                r = extract_first_word(&string, &w, separators, flags);
202✔
1274
                if (r < 0)
202✔
1275
                        return r;
×
1276
                if (r == 0)
202✔
1277
                        break;
1278

1279
                found = strv_find(words, w);
148✔
1280
                if (found)
148✔
1281
                        break;
1282
        }
1283

1284
        if (ret_word)
75✔
1285
                *ret_word = found;
7✔
1286
        return !!found;
75✔
1287
}
1288

1289
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
9,343✔
1290
        if (!s1 && !s2)
9,343✔
1291
                return true;
1292
        if (!s1 || !s2)
9,342✔
1293
                return false;
1294

1295
        if (!ok)
9,340✔
1296
                ok = WHITESPACE;
13✔
1297

1298
        for (; *s1 && *s2; s1++, s2++)
17,843✔
1299
                if (*s1 != *s2)
10,811✔
1300
                        break;
1301

1302
        return in_charset(s1, ok) && in_charset(s2, ok);
11,654✔
1303
}
1304

1305
char* string_replace_char(char *str, char old_char, char new_char) {
631,934✔
1306
        assert(str);
631,934✔
1307
        assert(old_char != '\0');
631,934✔
1308
        assert(new_char != '\0');
631,934✔
1309
        assert(old_char != new_char);
631,934✔
1310

1311
        for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
637,438✔
1312
                *p = new_char;
5,504✔
1313

1314
        return str;
631,934✔
1315
}
1316

1317
int make_cstring(const void *s, size_t n, MakeCStringMode mode, char **ret) {
10,341✔
1318
        char *b;
10,341✔
1319

1320
        assert(s || n == 0);
10,341✔
1321
        assert(mode >= 0);
10,341✔
1322
        assert(mode < _MAKE_CSTRING_MODE_MAX);
10,341✔
1323

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

1327
        if (n == 0) {
10,341✔
1328
                if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
20✔
1329
                        return -EINVAL;
1330

1331
                if (!ret)
19✔
1332
                        return 0;
1333

1334
                b = new0(char, 1);
19✔
1335
        } else {
1336
                const uint8_t *nul;
10,321✔
1337

1338
                nul = memchr(s, 0, n);
10,321✔
1339
                if (nul) {
10,321✔
1340
                        if (nul < (const uint8_t*) s + n - 1 || /* embedded NUL? */
29✔
1341
                            mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
1342
                                return -EINVAL;
1343

1344
                        n--;
1345
                } else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
10,292✔
1346
                        return -EINVAL;
1347

1348
                if (!ret)
10,310✔
1349
                        return 0;
1350

1351
                b = memdup_suffix0(s, n);
10,310✔
1352
        }
1353
        if (!b)
10,329✔
1354
                return -ENOMEM;
1355

1356
        *ret = b;
10,329✔
1357
        return 0;
10,329✔
1358
}
1359

1360
size_t strspn_from_end(const char *str, const char *accept) {
597,270✔
1361
        size_t n = 0;
597,270✔
1362

1363
        if (isempty(str))
597,270✔
1364
                return 0;
1365

1366
        if (isempty(accept))
597,267✔
1367
                return 0;
1368

1369
        for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
1,152,934✔
1370
                n++;
555,668✔
1371

1372
        return n;
1373
}
1374

1375
char* strdupspn(const char *a, const char *accept) {
×
1376
        if (isempty(a) || isempty(accept))
×
1377
                return strdup("");
×
1378

1379
        return strndup(a, strspn(a, accept));
×
1380
}
1381

1382
char* strdupcspn(const char *a, const char *reject) {
41,452✔
1383
        if (isempty(a))
41,452✔
1384
                return strdup("");
×
1385
        if (isempty(reject))
41,452✔
1386
                return strdup(a);
×
1387

1388
        return strndup(a, strcspn(a, reject));
41,452✔
1389
}
1390

1391
char* find_line_startswith_internal(const char *haystack, const char *needle) {
3,384✔
1392
        assert(haystack);
3,384✔
1393
        assert(needle);
3,384✔
1394

1395
        /* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
1396
         * first character after it */
1397

1398
        char *p = (char*) strstr(haystack, needle);
3,384✔
1399
        if (!p)
3,384✔
1400
                return NULL;
1401

1402
        if (p > haystack)
770✔
1403
                while (p[-1] != '\n') {
66✔
1404
                        p = strstr(p + 1, needle);
9✔
1405
                        if (!p)
9✔
1406
                                return NULL;
1407
                }
1408

1409
        return p + strlen(needle);
769✔
1410
}
1411

1412
char* find_line_internal(const char *haystack, const char *needle) {
×
1413
        assert(haystack);
×
1414
        assert(needle);
×
1415

1416
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1417
         * beginning of the line */
1418

1419
        char *p = (char*) find_line_startswith(haystack, needle);
×
1420
        if (!p)
×
1421
                return NULL;
1422

1423
        if (*p == 0 || strchr(NEWLINE, *p))
×
1424
                return p - strlen(needle);
×
1425

1426
        return NULL;
1427
}
1428

1429
char* find_line_after_internal(const char *haystack, const char *needle) {
×
1430
        assert(haystack);
×
1431
        assert(needle);
×
1432

1433
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1434
         * next line after it */
1435

1436
        char *p = (char*) find_line_startswith(haystack, needle);
×
1437
        if (!p)
×
1438
                return NULL;
1439

1440
        if (*p == 0)
×
1441
                return p;
1442
        if (strchr(NEWLINE, *p))
×
1443
                return p + 1;
×
1444

1445
        return NULL;
1446
}
1447

1448
bool version_is_valid(const char *s) {
37,262✔
1449
        if (isempty(s))
37,262✔
1450
                return false;
1451

1452
        if (!filename_part_is_valid(s))
37,260✔
1453
                return false;
1454

1455
        /* This is a superset of the characters used by semver. We additionally allow "," and "_". */
1456
        if (!in_charset(s, ALPHANUMERICAL ".,_-+"))
37,260✔
1457
                return false;
×
1458

1459
        return true;
1460
}
1461

1462
bool version_is_valid_versionspec(const char *s) {
97✔
1463
        if (!filename_part_is_valid(s))
97✔
1464
                return false;
1465

1466
        if (!in_charset(s, ALPHANUMERICAL "-.~^"))
97✔
1467
                return false;
×
1468

1469
        return true;
1470
}
1471

1472
ssize_t strlevenshtein(const char *x, const char *y) {
122✔
1473
        _cleanup_free_ size_t *t0 = NULL, *t1 = NULL, *t2 = NULL;
244✔
1474
        size_t xl, yl;
122✔
1475

1476
        /* This is inspired from the Linux kernel's Levenshtein implementation */
1477

1478
        if (streq_ptr(x, y))
122✔
1479
                return 0;
1480

1481
        xl = strlen_ptr(x);
118✔
1482
        if (xl > SSIZE_MAX)
117✔
1483
                return -E2BIG;
1484

1485
        yl = strlen_ptr(y);
118✔
1486
        if (yl > SSIZE_MAX)
117✔
1487
                return -E2BIG;
1488

1489
        if (isempty(x))
118✔
1490
                return yl;
3✔
1491
        if (isempty(y))
115✔
1492
                return xl;
1✔
1493

1494
        t0 = new0(size_t, yl + 1);
114✔
1495
        if (!t0)
114✔
1496
                return -ENOMEM;
1497
        t1 = new0(size_t, yl + 1);
114✔
1498
        if (!t1)
114✔
1499
                return -ENOMEM;
1500
        t2 = new0(size_t, yl + 1);
114✔
1501
        if (!t2)
114✔
1502
                return -ENOMEM;
1503

1504
        for (size_t i = 0; i <= yl; i++)
1,249✔
1505
                t1[i] = i;
1,135✔
1506

1507
        for (size_t i = 0; i < xl; i++) {
712✔
1508
                t2[0] = i + 1;
598✔
1509

1510
                for (size_t j = 0; j < yl; j++) {
6,439✔
1511
                        /* Substitution */
1512
                        t2[j+1] = t1[j] + (x[i] != y[j]);
5,841✔
1513

1514
                        /* Swap */
1515
                        if (i > 0 && j > 0 && x[i-1] == y[j] && x[i] == y[j-1] && t2[j+1] > t0[j-1] + 1)
5,841✔
1516
                                t2[j+1] = t0[j-1] + 1;
14✔
1517

1518
                        /* Deletion */
1519
                        if (t2[j+1] > t1[j+1] + 1)
5,841✔
1520
                                t2[j+1] = t1[j+1] + 1;
247✔
1521

1522
                        /* Insertion */
1523
                        if (t2[j+1] > t2[j] + 1)
5,841✔
1524
                                t2[j+1] = t2[j] + 1;
880✔
1525
                }
1526

1527
                size_t *dummy = t0;
1528
                t0 = t1;
1529
                t1 = t2;
1530
                t2 = dummy;
1531
        }
1532

1533
        return t1[yl];
114✔
1534
}
1535

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

1539
        if (!haystack || !needle)
25,301✔
1540
                return NULL;
1541

1542
        /* Special case: for the empty string we return the very last possible occurrence, i.e. *after* the
1543
         * last char, not before. */
1544
        if (needle[0] == 0)
25,298✔
1545
                return (char*) strchr(haystack, 0);
2✔
1546

1547
        /* Special case: for single character strings, just use optimized strrchr() */
1548
        if (needle[1] == 0)
25,296✔
1549
                return (char*) strrchr(haystack, needle[0]);
3✔
1550

1551
        for (const char *p = strstr(haystack, needle), *q; p; p = q) {
25,299✔
1552
                q = strstr(p + 1, needle);
18✔
1553
                if (!q)
18✔
1554
                        return (char*) p;
1555
        }
1556
        return NULL;
1557
}
1558

1559
char* strrstr_no_case_internal(const char *haystack, const char *needle) {
41✔
1560
        if (!haystack || !needle)
41✔
1561
                return NULL;
1562

1563
        for (const char *p = strchr(haystack, 0); p > haystack; p--)
438✔
1564
                if (startswith_no_case(p, needle))
431✔
1565
                        return (char*) p;
1566

1567
        return startswith_no_case(haystack, needle) ? (char*) haystack : NULL;
7✔
1568
}
1569

1570
size_t str_common_prefix(const char *a, const char *b) {
866✔
1571
        assert(a);
866✔
1572
        assert(b);
866✔
1573

1574
        /* Returns the length of the common prefix of the two specified strings, or SIZE_MAX in case the
1575
         * strings are fully identical. */
1576

1577
        for (size_t n = 0;; n++) {
731✔
1578
                char c = a[n];
1,597✔
1579
                if (c != b[n])
1,597✔
1580
                        return n;
1581
                if (c == 0)
734✔
1582
                        return SIZE_MAX;
1583
        }
1584
}
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