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

systemd / systemd / 29544664670

16 Jul 2026 04:17PM UTC coverage: 73.034% (+0.05%) from 72.983%
29544664670

push

github

yuwata
boot: fix MEMMAP_DEVICE_PATH EndingAddress field calculation

Let's do what EDK2 does.

Fixes: #43038

346521 of 474466 relevant lines covered (73.03%)

1340443.02 hits per line

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

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

30
        const char *p = startswith(s, word);
4,877,178✔
31
        if (!p)
4,877,178✔
32
                return NULL;
33
        if (*p == '\0')
260,535✔
34
                return (char*) p;
35

36
        const char *nw = skip_leading_chars(p, WHITESPACE);
260,534✔
37
        if (p == nw)
260,534✔
38
                return NULL;
837✔
39

40
        return (char*) nw;
41
}
42

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

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

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

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

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

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

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

67
char* strstrip(char *s) {
10,414,732✔
68
        if (!s)
10,414,732✔
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);
10,412,011✔
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) {
12,160,096✔
100
        char *c = s;
12,160,096✔
101

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

104
        if (!s)
12,160,096✔
105
                return NULL;
106

107
        if (!bad)
12,160,096✔
108
                bad = WHITESPACE;
91,666✔
109

110
        for (char *p = s; *p; p++)
396,610,988✔
111
                if (!strchr(bad, *p))
384,450,892✔
112
                        c = p + 1;
369,249,456✔
113

114
        *c = 0;
12,160,096✔
115

116
        return s;
12,160,096✔
117
}
118

119
char* truncate_nl_full(char *s, size_t *ret_len) {
3,109,120✔
120
        size_t n;
3,109,120✔
121

122
        assert(s);
3,109,120✔
123

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

131
char ascii_tolower(char x) {
57,004,267✔
132

133
        if (x >= 'A' && x <= 'Z')
57,004,267✔
134
                return x - 'A' + 'a';
3,933,438✔
135

136
        return x;
137
}
138

139
char ascii_toupper(char x) {
334,591✔
140

141
        if (x >= 'a' && x <= 'z')
334,591✔
142
                return x - 'a' + 'A';
205,525✔
143

144
        return x;
145
}
146

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

150
        for (char *p = s; *p; p++)
157,270✔
151
                *p = ascii_tolower(*p);
133,056✔
152

153
        return s;
24,214✔
154
}
155

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

159
        for (char *p = s; *p; p++)
358,306✔
160
                *p = ascii_toupper(*p);
334,428✔
161

162
        return s;
23,878✔
163
}
164

165
char* ascii_strlower_n(char *s, size_t n) {
1,907,595✔
166
        assert(n <= 0 || s);
1,907,595✔
167

168
        if (n <= 0)
1,907,595✔
169
                return s;
170

171
        for (size_t i = 0; i < n; i++)
16,038,648✔
172
                s[i] = ascii_tolower(s[i]);
14,131,396✔
173

174
        return s;
175
}
176

177
int ascii_strcasecmp_n(const char *a, const char *b, size_t n) {
2,799,746✔
178

179
        assert(a);
2,799,746✔
180
        assert(b);
2,799,746✔
181

182
        for (; n > 0; a++, b++, n--) {
23,514,991✔
183
                int x, y;
21,364,919✔
184

185
                x = (int) (uint8_t) ascii_tolower(*a);
21,364,919✔
186
                y = (int) (uint8_t) ascii_tolower(*b);
21,364,919✔
187

188
                if (x != y)
21,364,919✔
189
                        return x - y;
649,674✔
190
        }
191

192
        return 0;
193
}
194

195
int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m) {
1,144,658✔
196
        int r;
1,144,658✔
197

198
        r = ascii_strcasecmp_n(a, b, MIN(n, m));
1,144,658✔
199
        if (r != 0)
1,144,658✔
200
                return r;
201

202
        return CMP(n, m);
1,010,840✔
203
}
204

205
bool chars_intersect(const char *a, const char *b) {
13,050✔
206
        /* Returns true if any of the chars in a are in b. */
207
        for (const char *p = a; *p; p++)
188,353✔
208
                if (strchr(b, *p))
175,325✔
209
                        return true;
210

211
        return false;
212
}
213

214
bool string_has_cc(const char *p, const char *ok) {
298,209✔
215
        assert(p);
298,209✔
216

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

223
        for (const char *t = p; *t; t++) {
2,894,387✔
224
                if (ok && strchr(ok, *t))
2,596,194✔
225
                        continue;
8✔
226

227
                if (char_is_cc(*t))
2,596,186✔
228
                        return true;
229
        }
230

231
        return false;
232
}
233

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

241
static size_t ansi_sequence_length(const char *s, size_t len) {
6,342✔
242
        assert(s);
6,342✔
243

244
        if (len < 2)
6,342✔
245
                return 0;
246

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

250
        if (s[1] == 0x5B) { /* [, start of CSI sequence */
909✔
251
                size_t i = 2;
908✔
252

253
                if (i == len)
908✔
254
                        return 0;
255

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

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

269
        return 0;  /* Bad escape? */
270
}
271

272
static bool string_has_ansi_sequence(const char *s, size_t len) {
7,824✔
273
        const char *t = s;
7,824✔
274

275
        while ((t = memchr(t, 0x1B, len - (t - s)))) {
7,825✔
276
                if (ansi_sequence_length(t, len - (t - s)) > 0)
157✔
277
                        return true;
278
                t++;
1✔
279
        }
280
        return false;
281
}
282

283
static size_t previous_ansi_sequence(const char *s, size_t length, const char **ret_where) {
269✔
284

285
        assert(s);
269✔
286
        assert(ret_where);
269✔
287

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

290
        if (length < 2) {
269✔
291
                /* Need at least two bytes for an ANSI sequence */
292
                *ret_where = NULL;
2✔
293
                return 0;
2✔
294
        }
295

296
        for (size_t i = length - 2; i > 0; i--) {  /* -2 because at least two bytes are needed */
3,444✔
297
                size_t slen = ansi_sequence_length(s + (i - 1), length - (i - 1));
3,442✔
298
                if (slen == 0)
3,442✔
299
                        continue;
3,177✔
300

301
                *ret_where = s + (i - 1);
265✔
302
                return slen;
265✔
303
        }
304

305
        *ret_where = NULL;
2✔
306
        return 0;
2✔
307
}
308

309
static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4,411✔
310
        size_t x, need_space, suffix_len;
4,411✔
311
        char *t;
4,411✔
312

313
        assert(s);
4,411✔
314
        assert(percent <= 100);
4,411✔
315
        assert(new_length != SIZE_MAX);
4,411✔
316

317
        if (old_length <= new_length)
4,411✔
318
                return strndup(s, old_length);
1,851✔
319

320
        /* Special case short ellipsations */
321
        switch (new_length) {
2,560✔
322

323
        case 0:
×
324
                return strdup("");
×
325

326
        case 1:
65✔
327
                if (is_locale_utf8())
65✔
328
                        return strdup("…");
65✔
329
                else
330
                        return strdup(".");
×
331

332
        case 2:
35✔
333
                if (!is_locale_utf8())
35✔
334
                        return strdup("..");
×
335
                break;
336
        }
337

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

343
        t = new(char, new_length+3);
2,495✔
344
        if (!t)
2,495✔
345
                return NULL;
346

347
        assert(new_length >= need_space);
2,495✔
348

349
        x = ((new_length - need_space) * percent + 50) / 100;
2,495✔
350
        assert(x <= new_length - need_space);
2,495✔
351

352
        write_ellipsis(mempcpy(t, s, x), /* unicode= */ false);
2,495✔
353
        suffix_len = new_length - x - need_space;
2,495✔
354
        memcpy(t + x + 3, s + old_length - suffix_len, suffix_len);
2,495✔
355
        *(t + x + 3 + suffix_len) = '\0';
2,495✔
356

357
        return t;
2,495✔
358
}
359

360
/* Walk backwards from 'end' (exclusive) to the start of the last complete UTF-8 character, without
361
 * descending below 'start', validate it and return a pointer to its first byte, optionally decoding it
362
 * into *ret_c. Returns NULL on a truncated or otherwise malformed sequence. */
363
static const char* find_previous_unichar(const char *start, const char *end, char32_t *ret_c) {
8,944✔
364
        const char *p;
8,944✔
365
        int r;
8,944✔
366

367
        assert(start);
8,944✔
368
        assert(end);
8,944✔
369
        assert(end > start);
8,944✔
370

371
        for (p = end; p > start; ) {
13,327✔
372
                p--;
13,327✔
373
                if (((uint8_t) *p & 0xc0) != 0x80) /* Found a non-continuation byte, i.e. a character start. */
13,327✔
374
                        break;
375
        }
376

377
        r = utf8_encoded_valid_unichar(p, end - p);
8,944✔
378
        if (r < 0 || p + r != end)
8,944✔
379
                return NULL;
380

381
        if (ret_c)
8,943✔
382
                assert_se(utf8_encoded_to_unichar(p, ret_c) == r);
8,943✔
383

384
        return p;
385
}
386

387
char* ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
7,995✔
388
        size_t x, k, len, len2;
7,995✔
389
        const char *i, *j;
7,995✔
390
        int r;
7,995✔
391

392
        /* Note that 'old_length' refers to bytes in the string, while 'new_length' refers to character cells taken up
393
         * on screen. This distinction doesn't matter for ASCII strings, but it does matter for non-ASCII UTF-8
394
         * strings.
395
         *
396
         * Ellipsation is done in a locale-dependent way:
397
         * 1. If the string passed in is fully ASCII and the current locale is not UTF-8, three dots are used ("...")
398
         * 2. Otherwise, a unicode ellipsis is used ("…")
399
         *
400
         * In other words: you'll get a unicode ellipsis as soon as either the string contains non-ASCII characters or
401
         * the current locale is UTF-8.
402
         */
403

404
        assert(s);
7,995✔
405
        assert(percent <= 100);
7,995✔
406

407
        if (new_length == SIZE_MAX)
7,995✔
408
                return strndup(s, old_length);
×
409

410
        if (new_length == 0)
7,995✔
411
                return strdup("");
171✔
412

413
        bool has_ansi_seq = string_has_ansi_sequence(s, old_length);
7,824✔
414

415
        /* If no multibyte characters or ANSI sequences, use ascii_ellipsize_mem for speed */
416
        if (!has_ansi_seq && ascii_is_valid_n(s, old_length))
7,824✔
417
                return ascii_ellipsize_mem(s, old_length, new_length, percent);
4,411✔
418

419
        x = (new_length - 1) * percent / 100;
3,413✔
420
        assert(x <= new_length - 1);
3,413✔
421

422
        k = 0;
423
        for (i = s; i < s + old_length; ) {
45,135✔
424
                size_t slen = has_ansi_seq ? ansi_sequence_length(i, old_length - (i - s)) : 0;
43,942✔
425
                if (slen > 0) {
1,014✔
426
                        i += slen;
225✔
427
                        continue;  /* ANSI sequences don't take up any space in output */
225✔
428
                }
429

430
                r = utf8_encoded_valid_unichar(i, s + old_length - i);
43,717✔
431
                if (r < 0)
43,717✔
432
                        return NULL;
×
433

434
                char32_t c;
43,717✔
435
                assert_se(utf8_encoded_to_unichar(i, &c) == r);
43,717✔
436

437
                int w = unichar_iswide(c) ? 2 : 1;
43,717✔
438
                if (k + w > x)
43,717✔
439
                        break;
440

441
                k += w;
41,497✔
442
                i += r;
41,497✔
443
        }
444

445
        const char *ansi_start = s + old_length;
3,413✔
446
        size_t ansi_len = 0;
3,413✔
447

448
        for (const char *t = j = s + old_length; t > i && k < new_length; ) {
12,384✔
449
                char32_t c;
9,058✔
450
                int w;
9,058✔
451
                const char *tt;
9,058✔
452

453
                if (has_ansi_seq && ansi_start >= t)
9,058✔
454
                        /* Figure out the previous ANSI sequence, if any */
455
                        ansi_len = previous_ansi_sequence(s, t - s, &ansi_start);
269✔
456

457
                /* If the sequence extends all the way to the current position, skip it. */
458
                if (has_ansi_seq && ansi_len > 0 && ansi_start + ansi_len == t) {
9,058✔
459
                        t = ansi_start;
114✔
460
                        continue;
114✔
461
                }
462

463
                /* Find the previous complete UTF-8 character inside the retained suffix. */
464
                tt = find_previous_unichar(i, t, &c);
8,944✔
465
                if (!tt)
8,944✔
466
                        return NULL;
1✔
467

468
                w = unichar_iswide(c) ? 2 : 1;
8,943✔
469
                if (k + w > new_length)
8,943✔
470
                        break;
471

472
                k += w;
8,857✔
473
                j = t = tt;  /* j should always point to the first "real" character */
8,857✔
474
        }
475

476
        /* We don't actually need to ellipsize */
477
        if (i >= j)
3,412✔
478
                return memdup_suffix0(s, old_length);
1,723✔
479

480
        if (k >= new_length) {
1,689✔
481
                /* Make space for ellipsis, if required and possible. We know that the edge character is not
482
                 * part of an ANSI sequence (because then we'd skip it). If the last character we looked at
483
                 * was wide, we don't need to make space.
484
                 * Move the edge by one complete UTF-8 character within the input slice. */
485
                if (j < s + old_length) {
1,603✔
486
                        r = utf8_encoded_valid_unichar(j, s + old_length - j);
1,603✔
487
                        if (r < 0)
1,603✔
488
                                return NULL;
489

490
                        j += r;
1,603✔
491
                } else if (i > s) {
×
492
                        const char *tt = find_previous_unichar(s, i, NULL);
×
493
                        if (!tt)
×
494
                                return NULL;
495

496
                        i = tt;
497
                }
498
        }
499

500
        len = i - s;
1,689✔
501
        len2 = s + old_length - j;
1,689✔
502

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

508
        char *e = new(char, alloc_len);
1,689✔
509
        if (!e)
1,689✔
510
                return NULL;
511

512
        memcpy_safe(e, s, len);
1,689✔
513
        write_ellipsis(e + len, /* unicode= */ true);
1,689✔
514

515
        char *dst = e + len + 3;
1,689✔
516

517
        if (has_ansi_seq)
1,689✔
518
                /* Copy over any ANSI sequences in full */
519
                for (const char *p = s + len; p < j; ) {
1,864✔
520
                        size_t slen = ansi_sequence_length(p, j - p);
1,729✔
521
                        if (slen > 0) {
1,729✔
522
                                dst = mempcpy(dst, p, slen);
262✔
523
                                p += slen;
262✔
524
                        } else
525
                                p = utf8_next_char(p);
1,467✔
526
                }
527

528
        memcpy_safe(dst, j, len2);
1,689✔
529
        dst[len2] = '\0';
1,689✔
530

531
        return e;
1,689✔
532
}
533

534
char* cellescape(char *buf, size_t len, const char *s) {
59,397✔
535
        /* Escape and ellipsize s into buffer buf of size len. Only non-control ASCII
536
         * characters are copied as they are, everything else is escaped. The result
537
         * is different then if escaping and ellipsization was performed in two
538
         * separate steps, because each sequence is either stored in full or skipped.
539
         *
540
         * This function should be used for logging about strings which expected to
541
         * be plain ASCII in a safe way.
542
         *
543
         * An ellipsis will be used if s is too long. It was always placed at the
544
         * very end.
545
         */
546

547
        size_t i = 0, last_char_width[4] = {}, k = 0;
59,397✔
548

549
        assert(buf);
59,397✔
550
        assert(len > 0); /* at least a terminating NUL */
59,397✔
551
        assert(s);
59,397✔
552

553
        for (;;) {
1,284,895✔
554
                char four[4];
672,146✔
555
                int w;
672,146✔
556

557
                if (*s == 0) /* terminating NUL detected? then we are done! */
672,146✔
558
                        goto done;
59,361✔
559

560
                w = cescape_char(*s, four);
612,785✔
561
                if (i + w + 1 > len) /* This character doesn't fit into the buffer anymore? In that case let's
612,785✔
562
                                      * ellipsize at the previous location */
563
                        break;
564

565
                /* OK, there was space, let's add this escaped character to the buffer */
566
                memcpy(buf + i, four, w);
612,749✔
567
                i += w;
612,749✔
568

569
                /* And remember its width in the ring buffer */
570
                last_char_width[k] = w;
612,749✔
571
                k = (k + 1) % 4;
612,749✔
572

573
                s++;
612,749✔
574
        }
575

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

580
                if (i + 4 <= len) /* nice, we reached our space goal */
81✔
581
                        break;
582

583
                k = k == 0 ? 3 : k - 1;
57✔
584
                if (last_char_width[k] == 0) /* bummer, we reached the beginning of the strings */
57✔
585
                        break;
586

587
                assert(i >= last_char_width[k]);
45✔
588
                i -= last_char_width[k];
45✔
589
        }
590

591
        if (i + 4 <= len) /* yay, enough space */
36✔
592
                i += write_ellipsis(buf + i, /* unicode= */ false);
24✔
593
        else if (i + 3 <= len) { /* only space for ".." */
12✔
594
                buf[i++] = '.';
4✔
595
                buf[i++] = '.';
4✔
596
        } else if (i + 2 <= len) /* only space for a single "." */
8✔
597
                buf[i++] = '.';
4✔
598
        else
599
                assert(i + 1 <= len);
4✔
600

601
done:
4✔
602
        buf[i] = '\0';
59,397✔
603
        return buf;
59,397✔
604
}
605

606
char* strshorten(char *s, size_t l) {
366,584✔
607
        assert(s);
366,584✔
608

609
        if (l >= SIZE_MAX-1) /* Would not change anything */
366,584✔
610
                return s;
611

612
        if (strnlen(s, l+1) > l)
366,582✔
613
                s[l] = 0;
105✔
614

615
        return s;
616
}
617

618
int strgrowpad0(char **s, size_t l) {
24✔
619
        size_t sz;
24✔
620

621
        assert(s);
24✔
622

623
        if (*s) {
24✔
624
                sz = strlen(*s) + 1;
24✔
625
                if (sz >= l) /* never shrink */
24✔
626
                        return 0;
627
        } else
628
                sz = 0;
629

630
        char *q = realloc(*s, l);
24✔
631
        if (!q)
24✔
632
                return -ENOMEM;
633

634
        *s = q;
24✔
635

636
        memzero(*s + sz, l - sz);
24✔
637
        return 0;
638
}
639

640
char* strreplace(const char *text, const char *old_string, const char *new_string) {
7,583✔
641
        size_t l, old_len, new_len;
7,583✔
642
        char *t, *ret = NULL;
7,583✔
643
        const char *f;
7,583✔
644

645
        assert(old_string);
7,583✔
646
        assert(new_string);
7,583✔
647

648
        if (!text)
7,583✔
649
                return NULL;
7,583✔
650

651
        old_len = strlen(old_string);
7,582✔
652
        new_len = strlen(new_string);
7,582✔
653

654
        l = strlen(text);
7,582✔
655
        if (!GREEDY_REALLOC(ret, l+1))
7,582✔
656
                return NULL;
657

658
        f = text;
7,582✔
659
        t = ret;
7,582✔
660
        while (*f) {
245,789✔
661
                size_t d, nl;
238,207✔
662

663
                if (!startswith(f, old_string)) {
238,207✔
664
                        *(t++) = *(f++);
235,788✔
665
                        continue;
235,788✔
666
                }
667

668
                d = t - ret;
2,419✔
669
                nl = l - old_len + new_len;
2,419✔
670

671
                if (!GREEDY_REALLOC(ret, nl + 1))
2,419✔
672
                        return mfree(ret);
×
673

674
                l = nl;
2,419✔
675
                t = ret + d;
2,419✔
676

677
                t = stpcpy(t, new_string);
2,419✔
678
                f += old_len;
2,419✔
679
        }
680

681
        *t = 0;
7,582✔
682
        return ret;
7,582✔
683
}
684

685
static void advance_offsets(
559✔
686
                ssize_t diff,
687
                size_t offsets[2], /* note: we can't use [static 2] here, since this may be NULL */
688
                size_t shift[static 2],
689
                size_t size) {
690

691
        if (!offsets)
559✔
692
                return;
693

694
        assert(shift);
549✔
695

696
        if ((size_t) diff < offsets[0])
549✔
697
                shift[0] += size;
×
698
        if ((size_t) diff < offsets[1])
549✔
699
                shift[1] += size;
×
700
}
701

702
char* strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]) {
260,690✔
703
        const char *begin = NULL;
260,690✔
704
        enum {
260,690✔
705
                STATE_OTHER,
706
                STATE_ESCAPE,
707
                STATE_CSI,
708
                STATE_OSC,
709
                STATE_OSC_CLOSING,
710
        } state = STATE_OTHER;
260,690✔
711
        _cleanup_(memstream_done) MemStream m = {};
260,690✔
712
        size_t isz, shift[2] = {}, n_carriage_returns = 0;
260,690✔
713
        FILE *f;
260,690✔
714

715
        assert(ibuf);
260,690✔
716
        assert(*ibuf);
260,690✔
717
        POINTER_MAY_BE_NULL(_isz);
260,690✔
718

719
        /* This does three things:
720
         *
721
         * 1. Replaces TABs by 8 spaces
722
         * 2. Strips ANSI color sequences (a subset of CSI), i.e. ESC '[' … 'm' sequences
723
         * 3. Strips ANSI operating system sequences (OSC), i.e. ESC ']' … ST sequences
724
         * 4. Strip trailing \r characters (since they would "move the cursor", but have no
725
         *    other effect).
726
         *
727
         * Everything else will be left as it is. In particular other ANSI sequences are left as they are, as
728
         * are any other special characters. Truncated ANSI sequences are left-as is too. This call is
729
         * supposed to suppress the most basic formatting noise, but nothing else.
730
         *
731
         * Why care for OSC sequences? Well, to undo what terminal_urlify() and friends generate. */
732

733
        isz = _isz ? *_isz : strlen(*ibuf);
260,690✔
734

735
        /* Note we turn off internal locking on f for performance reasons. It's safe to do so since we
736
         * created f here and it doesn't leave our scope. */
737
        f = memstream_init(&m);
260,690✔
738
        if (!f)
260,690✔
739
                return NULL;
740

741
        for (const char *i = *ibuf; i < *ibuf + isz + 1; i++) {
31,789,440✔
742

743
                bool eot = i >= *ibuf + isz;
31,528,750✔
744

745
                switch (state) {
31,528,750✔
746

747
                case STATE_OTHER:
31,528,499✔
748
                        if (eot)
31,528,499✔
749
                                break;
750

751
                        if (*i == '\r') {
31,267,809✔
752
                                n_carriage_returns++;
7✔
753
                                break;
7✔
754
                        } else if (*i == '\n')
31,267,802✔
755
                                /* Ignore carriage returns before new line */
756
                                n_carriage_returns = 0;
34✔
757
                        for (; n_carriage_returns > 0; n_carriage_returns--)
31,267,804✔
758
                                fputc('\r', f);
2✔
759

760
                        if (*i == '\x1B')
31,267,802✔
761
                                state = STATE_ESCAPE;
762
                        else if (*i == '\t') {
31,267,768✔
763
                                fputs("        ", f);
554✔
764
                                advance_offsets(i - *ibuf, highlight, shift, 7);
554✔
765
                        } else
766
                                fputc(*i, f);
31,267,214✔
767

768
                        break;
769

770
                case STATE_ESCAPE:
34✔
771
                        assert(n_carriage_returns == 0);
34✔
772

773
                        if (eot) {
34✔
774
                                fputc('\x1B', f);
×
775
                                advance_offsets(i - *ibuf, highlight, shift, 1);
×
776
                                break;
777
                        } else if (*i == '[') { /* ANSI CSI */
34✔
778
                                state = STATE_CSI;
31✔
779
                                begin = i + 1;
31✔
780
                        } else if (*i == ']') { /* ANSI OSC */
3✔
781
                                state = STATE_OSC;
3✔
782
                                begin = i + 1;
3✔
783
                        } else {
784
                                fputc('\x1B', f);
×
785
                                fputc(*i, f);
×
786
                                advance_offsets(i - *ibuf, highlight, shift, 1);
×
787
                                state = STATE_OTHER;
×
788
                        }
789

790
                        break;
791

792
                case STATE_CSI:
191✔
793
                        assert(n_carriage_returns == 0);
191✔
794

795
                        if (eot || !strchr(DIGITS ";:m", *i)) { /* EOT or invalid chars in sequence */
191✔
796
                                fputc('\x1B', f);
5✔
797
                                fputc('[', f);
5✔
798
                                advance_offsets(i - *ibuf, highlight, shift, 2);
5✔
799
                                state = STATE_OTHER;
5✔
800
                                i = begin-1;
5✔
801
                        } else if (*i == 'm')
186✔
802
                                state = STATE_OTHER;
26✔
803

804
                        break;
805

806
                case STATE_OSC:
24✔
807
                        assert(n_carriage_returns == 0);
24✔
808

809
                        /* There are three kinds of OSC terminators: \x07, \x1b\x5c or \x9c. We only support
810
                         * the first two, because the last one is a valid UTF-8 codepoint and hence creates
811
                         * an ambiguity (many Terminal emulators refuse to support it as well). */
812
                        if (eot || (!IN_SET(*i, '\x07', '\x1b') && !osc_char_is_valid(*i))) { /* EOT or invalid chars in sequence */
24✔
813
                                fputc('\x1B', f);
×
814
                                fputc(']', f);
×
815
                                advance_offsets(i - *ibuf, highlight, shift, 2);
×
816
                                state = STATE_OTHER;
×
817
                                i = begin-1;
×
818
                        } else if (*i == '\x07') /* Single character ST */
24✔
819
                                state = STATE_OTHER;
820
                        else if (*i == '\x1B')
23✔
821
                                state = STATE_OSC_CLOSING;
2✔
822

823
                        break;
824

825
                case STATE_OSC_CLOSING:
2✔
826
                        if (eot || *i != '\x5c') { /* EOT or incomplete two-byte ST in sequence */
2✔
827
                                fputc('\x1B', f);
×
828
                                fputc(']', f);
×
829
                                advance_offsets(i - *ibuf, highlight, shift, 2);
×
830
                                state = STATE_OTHER;
×
831
                                i = begin-1;
×
832
                        } else if (*i == '\x5c')
833
                                state = STATE_OTHER;
834

835
                        break;
836
                }
837
        }
838

839
        char *obuf;
260,690✔
840
        if (memstream_finalize(&m, &obuf, _isz) < 0)
260,690✔
841
                return NULL;
842

843
        free_and_replace(*ibuf, obuf);
260,690✔
844

845
        if (highlight) {
260,690✔
846
                highlight[0] += shift[0];
260,663✔
847
                highlight[1] += shift[1];
260,663✔
848
        }
849

850
        return *ibuf;
260,690✔
851
}
852

853
char* strextendv_with_separator(char **x, const char *separator, va_list ap) {
33,629,663✔
854
        _cleanup_free_ char *buffer = NULL;
33,629,663✔
855
        size_t f, l, l_separator;
33,629,663✔
856
        bool need_separator;
33,629,663✔
857
        char *nr, *p;
33,629,663✔
858

859
        if (!x)
33,629,663✔
860
                x = &buffer;
31,399,477✔
861

862
        l = f = strlen_ptr(*x);
33,629,663✔
863

864
        need_separator = !isempty(*x);
33,629,663✔
865
        l_separator = strlen_ptr(separator);
33,629,663✔
866

867
        va_list aq;
33,629,663✔
868
        va_copy(aq, ap);
33,629,663✔
869
        for (const char *t;;) {
126,887,878✔
870
                size_t n;
126,887,878✔
871

872
                t = va_arg(aq, const char *);
126,887,878✔
873
                if (!t)
126,887,878✔
874
                        break;
875
                if (t == POINTER_MAX)
93,258,215✔
876
                        continue;
3✔
877

878
                n = strlen(t);
93,258,212✔
879

880
                if (need_separator)
93,258,212✔
881
                        n += l_separator;
60,893,105✔
882

883
                if (n >= SIZE_MAX - l) {
93,258,212✔
884
                        va_end(aq);
×
885
                        return NULL;
×
886
                }
887

888
                l += n;
93,258,212✔
889
                need_separator = true;
93,258,212✔
890
        }
891
        va_end(aq);
33,629,663✔
892

893
        need_separator = !isempty(*x);
33,629,663✔
894

895
        nr = realloc(*x, GREEDY_ALLOC_ROUND_UP(l+1));
33,629,663✔
896
        if (!nr)
33,629,663✔
897
                return NULL;
898

899
        *x = nr;
33,629,663✔
900
        p = nr + f;
33,629,663✔
901

902
        for (;;) {
126,887,878✔
903
                const char *t;
126,887,878✔
904

905
                t = va_arg(ap, const char *);
126,887,878✔
906
                if (!t)
126,887,878✔
907
                        break;
908
                if (t == POINTER_MAX)
93,258,215✔
909
                        continue;
3✔
910

911
                if (need_separator && separator)
93,258,212✔
912
                        p = stpcpy(p, separator);
173,637✔
913

914
                p = stpcpy(p, t);
93,258,212✔
915

916
                need_separator = true;
93,258,212✔
917
        }
918

919
        assert(p == nr + l);
33,629,663✔
920
        *p = 0;
33,629,663✔
921

922
        /* If no buffer to extend was passed in return the start of the buffer */
923
        if (buffer)
33,629,663✔
924
                return TAKE_PTR(buffer);
31,399,477✔
925

926
        /* Otherwise we extended the buffer: return the end */
927
        return p;
928
}
929

930
char* strextend_with_separator_internal(char **x, const char *separator, ...) {
33,566,819✔
931
        va_list ap;
33,566,819✔
932
        char *ret;
33,566,819✔
933

934
        va_start(ap, separator);
33,566,819✔
935
        ret = strextendv_with_separator(x, separator, ap);
33,566,819✔
936
        va_end(ap);
33,566,819✔
937

938
        return ret;
33,566,819✔
939
}
940

941
int strextendf_with_separator(char **x, const char *separator, const char *format, ...) {
25,648✔
942
        size_t m, a, l_separator;
25,648✔
943
        va_list ap;
25,648✔
944
        int l;
25,648✔
945

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

950
        assert(x);
25,648✔
951
        assert(format);
25,648✔
952

953
        l_separator = isempty(*x) ? 0 : strlen_ptr(separator);
43,992✔
954

955
        /* Let's try to use the allocated buffer, if there's room at the end still. Otherwise let's extend by 64 chars. */
956
        if (*x) {
25,648✔
957
                m = strlen(*x);
18,344✔
958
                a = MALLOC_SIZEOF_SAFE(*x);
18,344✔
959
                assert(a >= m + 1);
18,344✔
960
        } else
961
                m = a = 0;
962

963
        if (a - m < 17 + l_separator) { /* if there's less than 16 chars space, then enlarge the buffer first */
25,648✔
964
                char *n;
14,271✔
965

966
                if (_unlikely_(l_separator > SIZE_MAX - 64)) /* overflow check #1 */
14,271✔
967
                        return -ENOMEM;
25,648✔
968
                if (_unlikely_(m > SIZE_MAX - 64 - l_separator)) /* overflow check #2 */
14,271✔
969
                        return -ENOMEM;
970

971
                n = realloc(*x, m + 64 + l_separator);
14,271✔
972
                if (!n)
14,271✔
973
                        return -ENOMEM;
974

975
                *x = n;
14,271✔
976
                a = MALLOC_SIZEOF_SAFE(*x);
14,271✔
977
        }
978

979
        /* Now, let's try to format the string into it */
980
        memcpy_safe(*x + m, separator, l_separator);
25,648✔
981
        va_start(ap, format);
25,648✔
982
        l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
25,648✔
983
        va_end(ap);
25,648✔
984

985
        assert(l >= 0);
25,648✔
986

987
        if ((size_t) l < a - m - l_separator) {
25,648✔
988
                char *n;
25,128✔
989

990
                /* Nice! This worked. We are done. But first, let's return the extra space we don't
991
                 * need. This should be a cheap operation, since we only lower the allocation size here,
992
                 * never increase. */
993
                n = realloc(*x, m + (size_t) l + l_separator + 1);
25,128✔
994
                if (n)
25,128✔
995
                        *x = n;
25,128✔
996
        } else {
997
                char *n;
520✔
998

999
                /* Wasn't enough. Then let's allocate exactly what we need. */
1000

1001
                if (_unlikely_((size_t) l > SIZE_MAX - (l_separator + 1))) /* overflow check #1 */
520✔
1002
                        goto oom;
×
1003
                if (_unlikely_(m > SIZE_MAX - ((size_t) l + l_separator + 1))) /* overflow check #2 */
520✔
1004
                        goto oom;
×
1005

1006
                a = m + (size_t) l + l_separator + 1;
520✔
1007
                n = realloc(*x, a);
520✔
1008
                if (!n)
520✔
1009
                        goto oom;
×
1010
                *x = n;
520✔
1011

1012
                va_start(ap, format);
520✔
1013
                l = vsnprintf(*x + m + l_separator, a - m - l_separator, format, ap);
520✔
1014
                va_end(ap);
520✔
1015

1016
                assert((size_t) l < a - m - l_separator);
520✔
1017
        }
1018

1019
        return 0;
1020

1021
oom:
×
1022
        /* truncate the bytes added after memcpy_safe() again */
1023
        (*x)[m] = 0;
×
1024
        return -ENOMEM;
×
1025
}
1026

1027
char* strrep(const char *s, size_t n) {
16✔
1028
        char *ret, *p;
16✔
1029
        size_t l;
16✔
1030

1031
        assert(s);
16✔
1032

1033
        l = strlen(s);
16✔
1034
        if (!MUL_ASSIGN_SAFE(&l, n))
16✔
1035
                return NULL;
16✔
1036
        if (!INC_SAFE(&l, 1))
15✔
1037
                return NULL;
1038

1039
        p = ret = malloc(l);
15✔
1040
        if (!ret)
15✔
1041
                return NULL;
1042

1043
        for (size_t i = 0; i < n; i++)
41,363✔
1044
                p = stpcpy(p, s);
41,348✔
1045

1046
        *p = 0;
15✔
1047
        return ret;
15✔
1048
}
1049

1050
int split_pair(const char *s, const char *sep, char **ret_first, char **ret_second) {
29,914✔
1051
        assert(s);
29,914✔
1052
        assert(!isempty(sep));
29,914✔
1053

1054
        const char *x = strstr(s, sep);
29,914✔
1055
        if (!x)
29,914✔
1056
                return -EINVAL;
29,914✔
1057

1058
        _cleanup_free_ char *a = NULL;
28,451✔
1059
        if (ret_first) {
28,451✔
1060
                a = strndup(s, x - s);
28,449✔
1061
                if (!a)
28,449✔
1062
                        return -ENOMEM;
1063
        }
1064

1065
        _cleanup_free_ char *b = NULL;
28,451✔
1066
        if (ret_second) {
28,451✔
1067
                b = strdup(x + strlen(sep));
28,449✔
1068
                if (!b)
28,449✔
1069
                        return -ENOMEM;
1070
        }
1071

1072
        if (ret_first)
28,451✔
1073
                *ret_first = TAKE_PTR(a);
28,449✔
1074
        if (ret_second)
28,451✔
1075
                *ret_second = TAKE_PTR(b);
28,449✔
1076
        return 0;
1077
}
1078

1079
int free_and_strdup(char **p, const char *s) {
2,152,148✔
1080
        char *t;
2,152,148✔
1081

1082
        assert(p);
2,152,148✔
1083

1084
        /* Replaces a string pointer with a strdup()ed new string,
1085
         * possibly freeing the old one. */
1086

1087
        if (streq_ptr(*p, s))
2,152,148✔
1088
                return 0;
2,152,148✔
1089

1090
        if (s) {
1,662,374✔
1091
                t = strdup(s);
1,653,740✔
1092
                if (!t)
1,653,740✔
1093
                        return -ENOMEM;
1094
        } else
1095
                t = NULL;
1096

1097
        free_and_replace(*p, t);
1,662,374✔
1098

1099
        return 1;
1,662,374✔
1100
}
1101

1102
int free_and_strdup_warn(char **p, const char *s) {
105,804✔
1103
        int r;
105,804✔
1104

1105
        r = free_and_strdup(p, s);
105,804✔
1106
        if (r < 0)
105,804✔
1107
                return log_oom();
×
1108
        return r;
1109
}
1110

1111
int free_and_strndup(char **p, const char *s, size_t l) {
80,885✔
1112
        char *t;
80,885✔
1113

1114
        assert(p);
80,885✔
1115
        assert(s || l == 0);
80,885✔
1116

1117
        /* Replaces a string pointer with a strndup()ed new string,
1118
         * freeing the old one. */
1119

1120
        if (!*p && !s)
80,885✔
1121
                return 0;
80,885✔
1122

1123
        if (*p && s && strneq(*p, s, l) && (l > strlen(*p) || (*p)[l] == '\0'))
80,885✔
1124
                return 0;
1125

1126
        if (s) {
37,970✔
1127
                t = strndup(s, l);
38,041✔
1128
                if (!t)
38,041✔
1129
                        return -ENOMEM;
1130
        } else
1131
                t = NULL;
1132

1133
        free_and_replace(*p, t);
38,042✔
1134
        return 1;
38,042✔
1135
}
1136

1137
int strdup_to_full(char **ret, const char *src) {
936,169✔
1138
        if (!src) {
936,169✔
1139
                if (ret)
327,299✔
1140
                        *ret = NULL;
327,298✔
1141

1142
                return 0;
1143
        } else {
1144
                if (ret) {
608,870✔
1145
                        char *t = strdup(src);
596,929✔
1146
                        if (!t)
596,929✔
1147
                                return -ENOMEM;
1148
                        *ret = t;
596,929✔
1149
                }
1150

1151
                return 1;
1152
        }
1153
};
1154

1155
bool string_is_safe(const char *p, StringSafeFlags flags) {
15,896,275✔
1156

1157
        /* Baseline checks are:
1158
         *   • No control characters (i.e. 0…31 + 127)
1159
         *   • UTF-8 valid (well, technically we skip this test if STRING_ASCII is set, since that is a tighter test)
1160
         */
1161

1162
        if (FLAGS_SET(flags, STRING_ALLOW_EMPTY) ? !p : isempty(p))
15,896,275✔
1163
                return false;
1164

1165
        if (!FLAGS_SET(flags, STRING_ASCII) && !utf8_is_valid(p))
31,791,458✔
1166
                return false;
1167

1168
        for (const char *t = p; *t; t++) {
306,223,205✔
1169
                /* never allow control characters, except for new line */
1170
                if ((*t > 0 && *t < ' ' && *t != '\n') || *t == 0x7f)
290,327,025✔
1171
                        return false;
1172

1173
                if (!FLAGS_SET(flags, STRING_ALLOW_NEWLINES) && *t == '\n')
290,327,000✔
1174
                        return false;
1175

1176
                if (!FLAGS_SET(flags, STRING_ALLOW_BACKSLASHES) && *t == '\\')
290,326,991✔
1177
                        return false;
1178

1179
                if (!FLAGS_SET(flags, STRING_ALLOW_QUOTES) && strchr(QUOTES, *t))
290,326,980✔
1180
                        return false;
1181

1182
                if (!FLAGS_SET(flags, STRING_ALLOW_GLOBS) && strchr(GLOB_CHARS, *t))
290,326,968✔
1183
                        return false;
1184

1185
                if (FLAGS_SET(flags, STRING_DISALLOW_WHITESPACE) && strchr(WHITESPACE, *t))
290,326,960✔
1186
                        return false;
1187

1188
                if (FLAGS_SET(flags, STRING_ASCII) && (uint8_t) *t >= 0x80)
290,326,955✔
1189
                        return false;
1190
        }
1191

1192
        if (FLAGS_SET(flags, STRING_FILENAME) && !filename_is_valid(p))
15,896,180✔
1193
                return false;
1194

1195
        if (FLAGS_SET(flags, STRING_FILENAME_PART) && !filename_part_is_valid(p))
15,896,168✔
1196
                return false;
25✔
1197

1198
        return true;
1199
}
1200

1201
char* str_realloc(char *p) {
61,091✔
1202
        /* Reallocate *p to actual size. Ignore failure, and return the original string on error. */
1203

1204
        if (!p)
61,091✔
1205
                return NULL;
1206

1207
        return realloc(p, strlen(p) + 1) ?: p;
61,091✔
1208
}
1209

1210
char* string_erase(char *x) {
132✔
1211
        if (!x)
132✔
1212
                return NULL;
1213

1214
        /* A delicious drop of snake-oil! To be called on memory where we stored passphrases or so, after we
1215
         * used them. */
1216
        explicit_bzero_safe(x, strlen(x));
132✔
1217
        return x;
132✔
1218
}
1219

1220
int string_truncate_lines(const char *s, size_t n_lines, char **ret) {
300✔
1221
        const char *p = s, *e = s;
300✔
1222
        bool truncation_applied = false;
300✔
1223
        char *copy;
300✔
1224
        size_t n = 0;
300✔
1225

1226
        assert(s);
300✔
1227
        assert(ret);
300✔
1228

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

1233
        for (;;) {
530✔
1234
                size_t k;
415✔
1235

1236
                k = strcspn(p, "\n");
415✔
1237

1238
                if (p[k] == 0) {
415✔
1239
                        if (k == 0) /* final empty line */
268✔
1240
                                break;
1241

1242
                        if (n >= n_lines) /* above threshold */
243✔
1243
                                break;
1244

1245
                        e = p + k; /* last line to include */
226✔
1246
                        break;
226✔
1247
                }
1248

1249
                assert(p[k] == '\n');
147✔
1250

1251
                if (n >= n_lines)
147✔
1252
                        break;
1253

1254
                if (k > 0)
115✔
1255
                        e = p + k;
92✔
1256

1257
                p += k + 1;
115✔
1258
                n++;
115✔
1259
        }
1260

1261
        /* e points after the last character we want to keep */
1262
        if (isempty(e))
300✔
1263
                copy = strdup(s);
230✔
1264
        else {
1265
                if (!in_charset(e, "\n")) /* We only consider things truncated if we remove something that
70✔
1266
                                           * isn't a new-line or a series of them */
1267
                        truncation_applied = true;
42✔
1268

1269
                copy = strndup(s, e - s);
70✔
1270
        }
1271
        if (!copy)
300✔
1272
                return -ENOMEM;
1273

1274
        *ret = copy;
300✔
1275
        return truncation_applied;
300✔
1276
}
1277

1278
int string_extract_line(const char *s, size_t i, char **ret) {
235,994✔
1279
        const char *p = s;
235,994✔
1280
        size_t c = 0;
235,994✔
1281

1282
        assert(ret);
235,994✔
1283

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

1290
        for (;;) {
423,792✔
1291
                const char *q;
329,893✔
1292

1293
                q = strchr(p, '\n');
329,893✔
1294
                if (i == c) {
329,893✔
1295
                        /* The line we are looking for! */
1296

1297
                        if (q) {
232,203✔
1298
                                char *m;
3,922✔
1299

1300
                                m = strndup(p, q - p);
3,922✔
1301
                                if (!m)
3,922✔
1302
                                        return -ENOMEM;
1303

1304
                                *ret = m;
3,922✔
1305
                                return !isempty(q + 1); /* More coming? */
7,844✔
1306
                        } else
1307
                                /* Tell the caller to use the input string if equal */
1308
                                return strdup_to(ret, p != s ? p : NULL);
454,728✔
1309
                }
1310

1311
                if (!q)
97,690✔
1312
                        /* No more lines, return empty line */
1313
                        return strdup_to(ret, "");
3,791✔
1314

1315
                p = q + 1;
93,899✔
1316
                c++;
93,899✔
1317
        }
1318
}
1319

1320
int string_contains_word_strv(const char *string, const char *separators, char * const *words, const char **ret_word) {
75✔
1321
        /* In the default mode with no separators specified, we split on whitespace and coalesce separators. */
1322
        const ExtractFlags flags = separators ? EXTRACT_DONT_COALESCE_SEPARATORS : 0;
75✔
1323
        const char *found = NULL;
75✔
1324
        int r;
202✔
1325

1326
        for (;;) {
329✔
1327
                _cleanup_free_ char *w = NULL;
127✔
1328

1329
                r = extract_first_word(&string, &w, separators, flags);
202✔
1330
                if (r < 0)
202✔
1331
                        return r;
×
1332
                if (r == 0)
202✔
1333
                        break;
1334

1335
                found = strv_find(words, w);
148✔
1336
                if (found)
148✔
1337
                        break;
1338
        }
1339

1340
        if (ret_word)
75✔
1341
                *ret_word = found;
7✔
1342
        return !!found;
75✔
1343
}
1344

1345
bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok) {
9,046✔
1346
        if (!s1 && !s2)
9,046✔
1347
                return true;
1348
        if (!s1 || !s2)
9,045✔
1349
                return false;
1350

1351
        if (!ok)
9,043✔
1352
                ok = WHITESPACE;
13✔
1353

1354
        for (; *s1 && *s2; s1++, s2++)
17,542✔
1355
                if (*s1 != *s2)
10,776✔
1356
                        break;
1357

1358
        return in_charset(s1, ok) && in_charset(s2, ok);
11,326✔
1359
}
1360

1361
char* string_replace_char(char *str, char old_char, char new_char) {
699,733✔
1362
        assert(str);
699,733✔
1363
        assert(old_char != '\0');
699,733✔
1364
        assert(new_char != '\0');
699,733✔
1365
        assert(old_char != new_char);
699,733✔
1366

1367
        for (char *p = strchr(str, old_char); p; p = strchr(p + 1, old_char))
705,912✔
1368
                *p = new_char;
6,179✔
1369

1370
        return str;
699,733✔
1371
}
1372

1373
int make_cstring(const void *s, size_t n, MakeCStringMode mode, char **ret) {
10,286✔
1374
        char *b;
10,286✔
1375

1376
        assert(s || n == 0);
10,286✔
1377
        assert(mode >= 0);
10,286✔
1378
        assert(mode < _MAKE_CSTRING_MODE_MAX);
10,286✔
1379

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

1383
        if (n == 0) {
10,286✔
1384
                if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
20✔
1385
                        return -EINVAL;
1386

1387
                if (!ret)
19✔
1388
                        return 0;
1389

1390
                b = new0(char, 1);
19✔
1391
        } else {
1392
                const uint8_t *nul;
10,266✔
1393

1394
                nul = memchr(s, 0, n);
10,266✔
1395
                if (nul) {
10,266✔
1396
                        if (nul < (const uint8_t*) s + n - 1 || /* embedded NUL? */
29✔
1397
                            mode == MAKE_CSTRING_REFUSE_TRAILING_NUL)
1398
                                return -EINVAL;
1399

1400
                        n--;
1401
                } else if (mode == MAKE_CSTRING_REQUIRE_TRAILING_NUL)
10,237✔
1402
                        return -EINVAL;
1403

1404
                if (!ret)
10,255✔
1405
                        return 0;
1406

1407
                b = memdup_suffix0(s, n);
10,255✔
1408
        }
1409
        if (!b)
10,274✔
1410
                return -ENOMEM;
1411

1412
        *ret = b;
10,274✔
1413
        return 0;
10,274✔
1414
}
1415

1416
size_t strspn_from_end(const char *str, const char *accept) {
662,988✔
1417
        size_t n = 0;
662,988✔
1418

1419
        if (isempty(str))
662,988✔
1420
                return 0;
1421

1422
        if (isempty(accept))
662,985✔
1423
                return 0;
1424

1425
        for (const char *p = str + strlen(str); p > str && strchr(accept, p[-1]); p--)
1,288,821✔
1426
                n++;
625,837✔
1427

1428
        return n;
1429
}
1430

1431
size_t strnspn(const char *str, const char *accept, size_t n) {
339,150✔
1432
        size_t i;
339,150✔
1433

1434
        /* Like strspn(), but reads at most 'n' bytes from 'str'. Returns the length of the initial
1435
         * run of 'str' (capped at 'n') that consists solely of bytes found in 'accept'. Stops at a
1436
         * NUL byte too. Unlike strspn() this is safe on a buffer that is not NUL terminated within
1437
         * 'n' bytes. */
1438

1439
        assert(str || n == 0);
339,150✔
1440
        assert(accept);
339,150✔
1441

1442
        for (i = 0; i < n && str[i] != '\0' && strchr(accept, str[i]); i++)
343,398✔
1443
                ;
1444

1445
        return i;
339,150✔
1446
}
1447

1448
char* strdupspn(const char *a, const char *accept) {
×
1449
        if (isempty(a) || isempty(accept))
×
1450
                return strdup("");
×
1451

1452
        return strndup(a, strspn(a, accept));
×
1453
}
1454

1455
char* strdupcspn(const char *a, const char *reject) {
43,848✔
1456
        if (isempty(a))
43,848✔
1457
                return strdup("");
×
1458
        if (isempty(reject))
43,848✔
1459
                return strdup(a);
×
1460

1461
        return strndup(a, strcspn(a, reject));
43,848✔
1462
}
1463

1464
char* find_line_startswith_internal(const char *haystack, const char *needle) {
6,788✔
1465
        assert(haystack);
6,788✔
1466
        assert(needle);
6,788✔
1467

1468
        /* Finds the first line in 'haystack' that starts with the specified string. Returns a pointer to the
1469
         * first character after it */
1470

1471
        char *p = (char*) strstr(haystack, needle);
6,788✔
1472
        if (!p)
6,788✔
1473
                return NULL;
1474

1475
        if (p > haystack)
1,468✔
1476
                while (p[-1] != '\n') {
116✔
1477
                        p = strstr(p + 1, needle);
9✔
1478
                        if (!p)
9✔
1479
                                return NULL;
1480
                }
1481

1482
        return p + strlen(needle);
1,467✔
1483
}
1484

1485
char* find_line_internal(const char *haystack, const char *needle) {
×
1486
        assert(haystack);
×
1487
        assert(needle);
×
1488

1489
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1490
         * beginning of the line */
1491

1492
        char *p = (char*) find_line_startswith(haystack, needle);
×
1493
        if (!p)
×
1494
                return NULL;
1495

1496
        if (*p == 0 || strchr(NEWLINE, *p))
×
1497
                return p - strlen(needle);
×
1498

1499
        return NULL;
1500
}
1501

1502
char* find_line_after_internal(const char *haystack, const char *needle) {
×
1503
        assert(haystack);
×
1504
        assert(needle);
×
1505

1506
        /* Finds the first line in 'haystack' that match the specified string. Returns a pointer to the
1507
         * next line after it */
1508

1509
        char *p = (char*) find_line_startswith(haystack, needle);
×
1510
        if (!p)
×
1511
                return NULL;
1512

1513
        if (*p == 0)
×
1514
                return p;
1515
        if (strchr(NEWLINE, *p))
×
1516
                return p + 1;
×
1517

1518
        return NULL;
1519
}
1520

1521
bool version_is_valid(const char *s, VersionFlags flags) {
78,580✔
1522

1523
        /* Validates a version string superficially. This does not proces the version string in any
1524
         * semantical way, it mostly just validates that its charset is reasonable. */
1525

1526
        if (FLAGS_SET(flags, VERSION_ALLOW_EMPTY) ? !s : isempty(s))
78,580✔
1527
                return false;
78,580✔
1528

1529
        if (!filename_part_is_valid(s))
78,575✔
1530
                return false;
1531

1532
        /* We always allow all characters specified by the UAPI.10 Version Specification, i.e. 0-9, a-z, A-Z,
1533
         * ".", "-", "~", "^".
1534
         *
1535
         * If the relevant flags are set we'll also allow "+" and "_" separators.
1536
         *
1537
         * Note that with SemVer allows 0-9, a-z, A-Z, "+", "-", ".", hence with VERSION_ALLOW_PLUS we
1538
         * implement a superset of it.
1539
         *
1540
         * If you wonder when to use which flags: when validating foreign versions (e.g. distribution
1541
         * versions in /etc/os-release or so) validate liberally, i.e. add
1542
         * VERSION_ALLOW_UNDERSCORE|VERSION_ALLOW_PLUS. When validating our own versioned objects (e.g. vpick
1543
         * or so) validate more strictly, and in particular refuse characters such as "_" and "+" that may be
1544
         * used for separating component names or boot attempt counters. Also: first – if appropriate – split
1545
         * the string into individual components. For example, if the string consists of a name and a
1546
         * version, separated by some character, only pass the version part to this function. The name part
1547
         * may pass verification, but it's cleaner to not rely on that.
1548
         *
1549
         * For details about UAPI.10 see:
1550
         *
1551
         * → https://uapi-group.org/specifications/specs/version_format_specification/ */
1552

1553
        char charset[] = ALPHANUMERICAL ".-~^" /* plus room for the two chars below: */ "\0\0";
78,568✔
1554
        size_t l = strlen(charset);
78,568✔
1555

1556
        if (FLAGS_SET(flags, VERSION_ALLOW_UNDERSCORE))
78,568✔
1557
                charset[l++] = '_';
77,900✔
1558
        if (FLAGS_SET(flags, VERSION_ALLOW_PLUS))
78,568✔
1559
                charset[l++] = '+';
77,900✔
1560

1561
        return in_charset(s, charset);
78,568✔
1562
}
1563

1564
ssize_t strlevenshtein(const char *x, const char *y) {
122✔
1565
        _cleanup_free_ size_t *t0 = NULL, *t1 = NULL, *t2 = NULL;
244✔
1566
        size_t xl, yl;
122✔
1567

1568
        /* This is inspired from the Linux kernel's Levenshtein implementation */
1569

1570
        if (streq_ptr(x, y))
122✔
1571
                return 0;
1572

1573
        xl = strlen_ptr(x);
118✔
1574
        if (xl > SSIZE_MAX)
117✔
1575
                return -E2BIG;
1576

1577
        yl = strlen_ptr(y);
118✔
1578
        if (yl > SSIZE_MAX)
117✔
1579
                return -E2BIG;
1580

1581
        if (isempty(x))
118✔
1582
                return yl;
3✔
1583
        if (isempty(y))
115✔
1584
                return xl;
1✔
1585

1586
        t0 = new0(size_t, yl + 1);
114✔
1587
        if (!t0)
114✔
1588
                return -ENOMEM;
1589
        t1 = new0(size_t, yl + 1);
114✔
1590
        if (!t1)
114✔
1591
                return -ENOMEM;
1592
        t2 = new0(size_t, yl + 1);
114✔
1593
        if (!t2)
114✔
1594
                return -ENOMEM;
1595

1596
        for (size_t i = 0; i <= yl; i++)
1,249✔
1597
                t1[i] = i;
1,135✔
1598

1599
        for (size_t i = 0; i < xl; i++) {
712✔
1600
                t2[0] = i + 1;
598✔
1601

1602
                for (size_t j = 0; j < yl; j++) {
6,439✔
1603
                        /* Substitution */
1604
                        t2[j+1] = t1[j] + (x[i] != y[j]);
5,841✔
1605

1606
                        /* Swap */
1607
                        if (i > 0 && j > 0 && x[i-1] == y[j] && x[i] == y[j-1] && t2[j+1] > t0[j-1] + 1)
5,841✔
1608
                                t2[j+1] = t0[j-1] + 1;
14✔
1609

1610
                        /* Deletion */
1611
                        if (t2[j+1] > t1[j+1] + 1)
5,841✔
1612
                                t2[j+1] = t1[j+1] + 1;
247✔
1613

1614
                        /* Insertion */
1615
                        if (t2[j+1] > t2[j] + 1)
5,841✔
1616
                                t2[j+1] = t2[j] + 1;
880✔
1617
                }
1618

1619
                size_t *dummy = t0;
1620
                t0 = t1;
1621
                t1 = t2;
1622
                t2 = dummy;
1623
        }
1624

1625
        return t1[yl];
114✔
1626
}
1627

1628
char* strrstr_internal(const char *haystack, const char *needle) {
26,463✔
1629
        /* Like strstr() but returns the last rather than the first occurrence of "needle" in "haystack". */
1630

1631
        if (!haystack || !needle)
26,463✔
1632
                return NULL;
1633

1634
        /* Special case: for the empty string we return the very last possible occurrence, i.e. *after* the
1635
         * last char, not before. */
1636
        if (needle[0] == 0)
26,460✔
1637
                return (char*) strchr(haystack, 0);
2✔
1638

1639
        /* Special case: for single character strings, just use optimized strrchr() */
1640
        if (needle[1] == 0)
26,458✔
1641
                return (char*) strrchr(haystack, needle[0]);
3✔
1642

1643
        for (const char *p = strstr(haystack, needle), *q; p; p = q) {
26,461✔
1644
                q = strstr(p + 1, needle);
18✔
1645
                if (!q)
18✔
1646
                        return (char*) p;
1647
        }
1648
        return NULL;
1649
}
1650

1651
char* strrstr_no_case_internal(const char *haystack, const char *needle) {
41✔
1652
        if (!haystack || !needle)
41✔
1653
                return NULL;
1654

1655
        for (const char *p = strchr(haystack, 0); p > haystack; p--)
438✔
1656
                if (startswith_no_case(p, needle))
431✔
1657
                        return (char*) p;
1658

1659
        return startswith_no_case(haystack, needle) ? (char*) haystack : NULL;
7✔
1660
}
1661

1662
size_t str_common_prefix(const char *a, const char *b) {
866✔
1663
        assert(a);
866✔
1664
        assert(b);
866✔
1665

1666
        /* Returns the length of the common prefix of the two specified strings, or SIZE_MAX in case the
1667
         * strings are fully identical. */
1668

1669
        for (size_t n = 0;; n++) {
731✔
1670
                char c = a[n];
1,597✔
1671
                if (c != b[n])
1,597✔
1672
                        return n;
1673
                if (c == 0)
734✔
1674
                        return SIZE_MAX;
1675
        }
1676
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc