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

systemd / systemd / 23624534405

26 Mar 2026 07:08PM UTC coverage: 72.113% (-0.2%) from 72.361%
23624534405

push

github

web-flow
Make imds networking unlocked by default (#41359)

316838 of 439364 relevant lines covered (72.11%)

1174324.03 hits per line

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

94.47
/src/boot/efi-string.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include "efi-string.h"
4
#include "string-util-fundamental.h"
5

6
#if SD_BOOT
7
#  include "proto/simple-text-io.h"
8
#  include "util.h"
9
#else
10
#  include <stdlib.h>
11

12
#  include "alloc-util.h"
13
#  define xnew(t, n) ASSERT_SE_PTR(new(t, n))
14
#  define xmalloc(n) ASSERT_SE_PTR(malloc(n))
15
#endif
16

17
/* String functions for both char and char16_t that should behave the same way as their respective
18
 * counterpart in userspace. Where it makes sense, these accept NULL and do something sensible whereas
19
 * userspace does not allow for this (strlen8(NULL) returns 0 like strlen_ptr(NULL) for example). To make it
20
 * easier to tell in code which kind of string they work on, we use 8/16 suffixes. This also makes is easier
21
 * to unit test them. */
22

23
#define DEFINE_STRNLEN(type, name)             \
24
        size_t name(const type *s, size_t n) { \
25
                if (!s)                        \
26
                        return 0;              \
27
                                               \
28
                size_t len = 0;                \
29
                while (len < n && *s) {        \
30
                        s++;                   \
31
                        len++;                 \
32
                }                              \
33
                                               \
34
                return len;                    \
35
        }
36

37
DEFINE_STRNLEN(char, strnlen8);
1,726✔
38
DEFINE_STRNLEN(char16_t, strnlen16);
140✔
39

40
#define TOLOWER(c)                                                \
41
        ({                                                        \
42
                typeof(c) _c = (c);                               \
43
                (_c >= 'A' && _c <= 'Z') ? _c + ('a' - 'A') : _c; \
44
        })
45

46
#define DEFINE_STRTOLOWER(type, name)                \
47
        type* name(type *s) {                        \
48
                if (!s)                              \
49
                        return NULL;                 \
50
                for (type *p = s; *p; p++)           \
51
                        *p = TOLOWER(*p);            \
52
                return s;                            \
53
        }
54

55
DEFINE_STRTOLOWER(char, strtolower8);
15✔
56
DEFINE_STRTOLOWER(char16_t, strtolower16);
15✔
57

58
#define DEFINE_STRNCASECMP(type, name, tolower)              \
59
        int name(const type *s1, const type *s2, size_t n) { \
60
                if (!s1 || !s2)                              \
61
                        return CMP(s1, s2);                  \
62
                                                             \
63
                while (n > 0) {                              \
64
                        type c1 = *s1, c2 = *s2;             \
65
                        if (tolower) {                       \
66
                                c1 = TOLOWER(c1);            \
67
                                c2 = TOLOWER(c2);            \
68
                        }                                    \
69
                        if (!c1 || c1 != c2)                 \
70
                                return CMP(c1, c2);          \
71
                                                             \
72
                        s1++;                                \
73
                        s2++;                                \
74
                        n--;                                 \
75
                }                                            \
76
                                                             \
77
                return 0;                                    \
78
        }
79

80
DEFINE_STRNCASECMP(char, strncmp8, false);
425✔
81
DEFINE_STRNCASECMP(char16_t, strncmp16, false);
204✔
82
DEFINE_STRNCASECMP(char, strncasecmp8, true);
1,703✔
83
DEFINE_STRNCASECMP(char16_t, strncasecmp16, true);
45✔
84

85
#define DEFINE_STRCPY(type, name)                                     \
86
        type *name(type * restrict dest, const type * restrict src) { \
87
                type *ret = ASSERT_PTR(dest);                         \
88
                                                                      \
89
                if (!src) {                                           \
90
                        *dest = '\0';                                 \
91
                        return ret;                                   \
92
                }                                                     \
93
                                                                      \
94
                while (*src) {                                        \
95
                        *dest = *src;                                 \
96
                        dest++;                                       \
97
                        src++;                                        \
98
                }                                                     \
99
                                                                      \
100
                *dest = '\0';                                         \
101
                return ret;                                           \
102
        }
103

104
DEFINE_STRCPY(char, strcpy8);
8✔
105
DEFINE_STRCPY(char16_t, strcpy16);
8✔
106

107
#define DEFINE_STRCHR(type, name)                  \
108
        type *name(const type *s, type c) {        \
109
                if (!s)                            \
110
                        return NULL;               \
111
                                                   \
112
                while (*s) {                       \
113
                        if (*s == c)               \
114
                                return (type *) s; \
115
                        s++;                       \
116
                }                                  \
117
                                                   \
118
                return c ? NULL : (type *) s;      \
119
        }
120

121
DEFINE_STRCHR(char, strchr8);
2,176✔
122
DEFINE_STRCHR(char16_t, strchr16);
167✔
123

124
#define DEFINE_STRNDUP(type, name, len_func)              \
125
        type *name(const type *s, size_t n) {             \
126
                if (!s)                                   \
127
                        return NULL;                      \
128
                                                          \
129
                size_t len = len_func(s, n);              \
130
                size_t size = len * sizeof(type);         \
131
                                                          \
132
                type *dup = xmalloc(size + sizeof(type)); \
133
                if (size > 0)                             \
134
                        memcpy(dup, s, size);             \
135
                dup[len] = '\0';                          \
136
                                                          \
137
                return dup;                               \
138
        }
139

140
DEFINE_STRNDUP(char, xstrndup8, strnlen8);
10✔
141
DEFINE_STRNDUP(char16_t, xstrndup16, strnlen16);
11✔
142

143
static unsigned utf8_to_unichar(const char *utf8, size_t n, char32_t *c) {
227✔
144
        char32_t unichar;
227✔
145
        unsigned len;
227✔
146

147
        assert(utf8);
227✔
148
        assert(c);
227✔
149

150
        if (!(utf8[0] & 0x80)) {
227✔
151
                *c = utf8[0];
220✔
152
                return 1;
220✔
153
        } else if ((utf8[0] & 0xe0) == 0xc0) {
7✔
154
                len = 2;
4✔
155
                unichar = utf8[0] & 0x1f;
4✔
156
        } else if ((utf8[0] & 0xf0) == 0xe0) {
3✔
157
                len = 3;
1✔
158
                unichar = utf8[0] & 0x0f;
1✔
159
        } else if ((utf8[0] & 0xf8) == 0xf0) {
2✔
160
                len = 4;
2✔
161
                unichar = utf8[0] & 0x07;
2✔
162
        } else if ((utf8[0] & 0xfc) == 0xf8) {
×
163
                len = 5;
×
164
                unichar = utf8[0] & 0x03;
×
165
        } else if ((utf8[0] & 0xfe) == 0xfc) {
×
166
                len = 6;
×
167
                unichar = utf8[0] & 0x01;
×
168
        } else {
169
                *c = UINT32_MAX;
×
170
                return 1;
×
171
        }
172

173
        if (len > n) {
7✔
174
                *c = UINT32_MAX;
1✔
175
                return len;
1✔
176
        }
177

178
        for (unsigned i = 1; i < len; i++) {
17✔
179
                if ((utf8[i] & 0xc0) != 0x80) {
11✔
180
                        *c = UINT32_MAX;
×
181
                        return len;
×
182
                }
183
                unichar <<= 6;
11✔
184
                unichar |= utf8[i] & 0x3f;
11✔
185
        }
186

187
        *c = unichar;
6✔
188
        return len;
6✔
189
}
190

191
/* Convert UTF-8 to UCS-2, skipping any invalid or short byte sequences. */
192
char16_t *xstrn8_to_16(const char *str8, size_t n) {
32✔
193
        assert(str8 || n == 0);
32✔
194

195
        if (n == SIZE_MAX)
32✔
196
                n = strlen8(str8);
2✔
197

198
        size_t i = 0;
32✔
199
        char16_t *str16 = xnew(char16_t, n + 1);
32✔
200

201
        while (n > 0 && *str8 != '\0') {
259✔
202
                char32_t unichar;
227✔
203

204
                size_t utf8len = utf8_to_unichar(str8, n, &unichar);
227✔
205
                str8 += utf8len;
227✔
206
                n = LESS_BY(n, utf8len);
227✔
207

208
                switch (unichar) {
227✔
209
                case 0 ... 0xd7ffU:
224✔
210
                case 0xe000U ... 0xffffU:
211
                        str16[i++] = unichar;
224✔
212
                        break;
224✔
213
                }
214
        }
215

216
        str16[i] = u'\0';
32✔
217
        return str16;
32✔
218
}
219

220
char *xstrn16_to_ascii(const char16_t *str16, size_t n) {
8✔
221
        assert(str16 || n == 0);
8✔
222

223
        if (n == SIZE_MAX)
8✔
224
                n = strlen16(str16);
3✔
225

226
        _cleanup_free_ char *str8 = xnew(char, n + 1);
8✔
227

228
        size_t i = 0;
229
        while (n > 0 && *str16 != u'\0') {
42✔
230

231
                if ((uint16_t) *str16 > 127U) /* Not ASCII? Fail! */
36✔
232
                        return NULL;
233

234
                str8[i++] = (char) (uint16_t) *str16;
34✔
235

236
                str16++;
34✔
237
                n--;
34✔
238
        }
239

240
        str8[i] = '\0';
6✔
241
        return TAKE_PTR(str8);
6✔
242
}
243

244
char* startswith8(const char *s, const char *prefix) {
9✔
245
        size_t l;
9✔
246

247
        assert(prefix);
9✔
248

249
        if (!s)
9✔
250
                return NULL;
251

252
        l = strlen8(prefix);
8✔
253
        if (!strneq8(s, prefix, l))
8✔
254
                return NULL;
255

256
        return (char*) s + l;
5✔
257
}
258

259
static bool efi_fnmatch_prefix(const char16_t *p, const char16_t *h, const char16_t **ret_p, const char16_t **ret_h) {
374✔
260
        assert(p);
374✔
261
        assert(h);
374✔
262
        assert(ret_p);
374✔
263
        assert(ret_h);
374✔
264

265
        for (;; p++, h++)
213✔
266
                switch (*p) {
587✔
267
                case '\0':
69✔
268
                        /* End of pattern. Check that haystack is now empty. */
269
                        return *h == '\0';
69✔
270

271
                case '\\':
3✔
272
                        p++;
3✔
273
                        if (*p == '\0' || *p != *h)
3✔
274
                                /* Trailing escape or no match. */
275
                                return false;
276
                        break;
277

278
                case '?':
6✔
279
                        if (*h == '\0')
6✔
280
                                /* Early end of haystack. */
281
                                return false;
282
                        break;
283

284
                case '*':
285
                        /* Point ret_p at the remainder of the pattern. */
286
                        while (*p == '*')
147✔
287
                                p++;
75✔
288
                        *ret_p = p;
72✔
289
                        *ret_h = h;
72✔
290
                        return true;
72✔
291

292
                case '[':
37✔
293
                        if (*h == '\0')
37✔
294
                                /* Early end of haystack. */
295
                                return false;
296

297
                        bool first = true, can_range = true, match = false;
298
                        for (;; first = false) {
135✔
299
                                p++;
135✔
300
                                if (*p == '\0')
135✔
301
                                        return false;
302

303
                                if (*p == '\\') {
134✔
304
                                        p++;
3✔
305
                                        if (*p == '\0')
3✔
306
                                                return false;
307
                                        if (*p == *h)
3✔
308
                                                match = true;
1✔
309
                                        can_range = true;
3✔
310
                                        continue;
3✔
311
                                }
312

313
                                /* End of set unless it's the first char. */
314
                                if (*p == ']' && !first)
131✔
315
                                        break;
316

317
                                /* Range pattern if '-' is not first or last in set. */
318
                                if (*p == '-' && can_range && !first && *(p + 1) != ']') {
95✔
319
                                        char16_t low = *(p - 1);
25✔
320
                                        p++;
25✔
321
                                        if (*p == '\\')
25✔
322
                                                p++;
1✔
323
                                        if (*p == '\0')
25✔
324
                                                return false;
325

326
                                        if (low <= *h && *h <= *p)
25✔
327
                                                match = true;
19✔
328

329
                                        /* Ranges cannot be chained: [a-c-f] == [-abcf] */
330
                                        can_range = false;
25✔
331
                                        continue;
25✔
332
                                }
333

334
                                if (*p == *h)
70✔
335
                                        match = true;
17✔
336
                                can_range = true;
337
                        }
338

339
                        if (!match)
36✔
340
                                return false;
341
                        break;
342

343
                default:
400✔
344
                        if (*p != *h)
400✔
345
                                /* Single char mismatch. */
346
                                return false;
347
                }
348
}
349

350
/* Patterns are fnmatch-compatible (with reduced feature support). */
351
bool efi_fnmatch(const char16_t *pattern, const char16_t *haystack) {
46✔
352
        assert(haystack);
46✔
353

354
        /* Patterns can be considered as simple patterns (without '*') concatenated by '*'. By doing so we
355
         * simply have to make sure the very first simple pattern matches the start of haystack. Then we just
356
         * look for the remaining simple patterns *somewhere* within the haystack (in order) as any extra
357
         * characters in between would be matches by the '*'. We then only have to ensure that the very last
358
         * simple pattern matches at the actual end of the haystack.
359
         *
360
         * This means we do not need to use backtracking which could have catastrophic runtimes with the
361
         * right input data. */
362

363
        for (bool first = true;;) {
328✔
364
                const char16_t *pattern_tail = NULL, *haystack_tail = NULL;
374✔
365
                bool match = efi_fnmatch_prefix(pattern, haystack, &pattern_tail, &haystack_tail);
374✔
366
                if (first) {
374✔
367
                        if (!match)
46✔
368
                                /* Initial simple pattern must match. */
369
                                return false;
46✔
370
                        if (!pattern_tail)
35✔
371
                                /* No '*' was in pattern, we can return early. */
372
                                return true;
373
                        first = false;
374
                }
375

376
                if (pattern_tail) {
346✔
377
                        assert(match);
72✔
378
                        pattern = pattern_tail;
72✔
379
                        haystack = haystack_tail;
72✔
380
                } else {
381
                        /* If we have a match this must be at the end of the haystack. Note that
382
                         * efi_fnmatch_prefix compares the NUL-bytes at the end, so we cannot match the end
383
                         * of pattern in the middle of haystack). */
384
                        if (match || *haystack == '\0')
274✔
385
                                return match;
386

387
                        /* Match one character using '*'. */
388
                        haystack++;
256✔
389
                }
390
        }
391
}
392

393
#define DEFINE_PARSE_NUMBER(type, name)                                    \
394
        bool name(const type *s, uint64_t *ret_u, const type **ret_tail) { \
395
                assert(ret_u);                                             \
396
                                                                           \
397
                if (!s)                                                    \
398
                        return false;                                      \
399
                                                                           \
400
                /* Need at least one digit. */                             \
401
                if (*s < '0' || *s > '9')                                  \
402
                        return false;                                      \
403
                                                                           \
404
                uint64_t u = 0;                                            \
405
                while (*s >= '0' && *s <= '9') {                           \
406
                        if (!MUL_ASSIGN_SAFE(&u, 10))                      \
407
                                return false;                              \
408
                        if (!INC_SAFE(&u, *s - '0'))                       \
409
                                return false;                              \
410
                        s++;                                               \
411
                }                                                          \
412
                                                                           \
413
                if (!ret_tail && *s != '\0')                               \
414
                        return false;                                      \
415
                                                                           \
416
                *ret_u = u;                                                \
417
                if (ret_tail)                                              \
418
                        *ret_tail = s;                                     \
419
                return true;                                               \
420
        }
421

422
DEFINE_PARSE_NUMBER(char, parse_number8);
355✔
423
DEFINE_PARSE_NUMBER(char16_t, parse_number16);
64✔
424

425
bool parse_boolean(const char *v, bool *ret) {
15✔
426
        assert(ret);
15✔
427

428
        if (!v)
15✔
429
                return false;
430

431
        if (streq8(v, "1") || streq8(v, "yes") || streq8(v, "y") || streq8(v, "true") || streq8(v, "t") ||
14✔
432
            streq8(v, "on")) {
9✔
433
                *ret = true;
6✔
434
                return true;
6✔
435
        }
436

437
        if (streq8(v, "0") || streq8(v, "no") || streq8(v, "n") || streq8(v, "false") || streq8(v, "f") ||
8✔
438
            streq8(v, "off")) {
3✔
439
                *ret = false;
6✔
440
                return true;
6✔
441
        }
442

443
        return false;
444
}
445

446
char* line_get_key_value(char *s, const char *sep, size_t *pos, char **ret_key, char **ret_value) {
24✔
447
        char *line, *value;
24✔
448
        size_t linelen;
24✔
449

450
        assert(s);
24✔
451
        assert(sep);
24✔
452
        assert(pos);
24✔
453
        assert(ret_key);
24✔
454
        assert(ret_value);
24✔
455

456
        for (;;) {
29✔
457
                line = s + *pos;
29✔
458
                if (*line == '\0')
29✔
459
                        return NULL;
460

461
                linelen = 0;
462
                while (line[linelen] && !strchr8("\n\r", line[linelen]))
551✔
463
                        linelen++;
527✔
464

465
                /* move pos to next line */
466
                *pos += linelen;
24✔
467
                if (s[*pos])
24✔
468
                        (*pos)++;
21✔
469

470
                /* empty line */
471
                if (linelen == 0)
24✔
472
                        continue;
2✔
473

474
                /* terminate line */
475
                line[linelen] = '\0';
22✔
476

477
                /* remove leading whitespace */
478
                while (linelen > 0 && strchr8(" \t", *line)) {
34✔
479
                        line++;
12✔
480
                        linelen--;
12✔
481
                }
482

483
                /* remove trailing whitespace */
484
                while (linelen > 0 && strchr8(" \t", line[linelen - 1]))
29✔
485
                        linelen--;
486
                line[linelen] = '\0';
22✔
487

488
                if (*line == '#')
22✔
489
                        continue;
2✔
490

491
                /* split key/value */
492
                value = line;
493
                while (*value && !strchr8(sep, *value))
160✔
494
                        value++;
140✔
495
                if (*value == '\0')
20✔
496
                        continue;
1✔
497
                *value = '\0';
19✔
498
                value++;
19✔
499
                while (*value && strchr8(sep, *value))
20✔
500
                        value++;
1✔
501

502
                /* unquote */
503
                if (strchr8(QUOTES, value[0]) && line[linelen - 1] == value[0]) {
19✔
504
                        value++;
10✔
505
                        line[linelen - 1] = '\0';
10✔
506
                }
507

508
                *ret_key = line;
19✔
509
                *ret_value = value;
19✔
510
                return line;
19✔
511
        }
512
}
513

514
char16_t *hexdump(const void *data, size_t size) {
4✔
515
        const char *hex = LOWERCASE_HEXDIGITS;
4✔
516
        const uint8_t *d = data;
4✔
517

518
        assert(data || size == 0);
4✔
519

520
        char16_t *buf = xnew(char16_t, size * 2 + 1);
4✔
521

522
        for (size_t i = 0; i < size; i++) {
15✔
523
                buf[i * 2] = hex[d[i] >> 4];
11✔
524
                buf[i * 2 + 1] = hex[d[i] & 0x0F];
11✔
525
        }
526

527
        buf[size * 2] = 0;
4✔
528
        return buf;
4✔
529
}
530

531
static const char * const warn_table[] = {
532
        [EFI_SUCCESS]               = "Success",
533
        [EFI_WARN_UNKNOWN_GLYPH]    = "Unknown glyph",
534
        [EFI_WARN_DELETE_FAILURE]   = "Delete failure",
535
        [EFI_WARN_WRITE_FAILURE]    = "Write failure",
536
        [EFI_WARN_BUFFER_TOO_SMALL] = "Buffer too small",
537
        [EFI_WARN_STALE_DATA]       = "Stale data",
538
        [EFI_WARN_FILE_SYSTEM]      = "File system",
539
        [EFI_WARN_RESET_REQUIRED]   = "Reset required",
540
};
541

542
/* Errors have MSB set, remove it to keep the table compact. */
543
#define NOERR(err) ((err) & ~EFI_ERROR_MASK)
544

545
static const char * const err_table[] = {
546
        [NOERR(EFI_ERROR_MASK)]           = "Error",
547
        [NOERR(EFI_LOAD_ERROR)]           = "Load error",
548
        [NOERR(EFI_INVALID_PARAMETER)]    = "Invalid parameter",
549
        [NOERR(EFI_UNSUPPORTED)]          = "Unsupported",
550
        [NOERR(EFI_BAD_BUFFER_SIZE)]      = "Bad buffer size",
551
        [NOERR(EFI_BUFFER_TOO_SMALL)]     = "Buffer too small",
552
        [NOERR(EFI_NOT_READY)]            = "Not ready",
553
        [NOERR(EFI_DEVICE_ERROR)]         = "Device error",
554
        [NOERR(EFI_WRITE_PROTECTED)]      = "Write protected",
555
        [NOERR(EFI_OUT_OF_RESOURCES)]     = "Out of resources",
556
        [NOERR(EFI_VOLUME_CORRUPTED)]     = "Volume corrupt",
557
        [NOERR(EFI_VOLUME_FULL)]          = "Volume full",
558
        [NOERR(EFI_NO_MEDIA)]             = "No media",
559
        [NOERR(EFI_MEDIA_CHANGED)]        = "Media changed",
560
        [NOERR(EFI_NOT_FOUND)]            = "Not found",
561
        [NOERR(EFI_ACCESS_DENIED)]        = "Access denied",
562
        [NOERR(EFI_NO_RESPONSE)]          = "No response",
563
        [NOERR(EFI_NO_MAPPING)]           = "No mapping",
564
        [NOERR(EFI_TIMEOUT)]              = "Time out",
565
        [NOERR(EFI_NOT_STARTED)]          = "Not started",
566
        [NOERR(EFI_ALREADY_STARTED)]      = "Already started",
567
        [NOERR(EFI_ABORTED)]              = "Aborted",
568
        [NOERR(EFI_ICMP_ERROR)]           = "ICMP error",
569
        [NOERR(EFI_TFTP_ERROR)]           = "TFTP error",
570
        [NOERR(EFI_PROTOCOL_ERROR)]       = "Protocol error",
571
        [NOERR(EFI_INCOMPATIBLE_VERSION)] = "Incompatible version",
572
        [NOERR(EFI_SECURITY_VIOLATION)]   = "Security violation",
573
        [NOERR(EFI_CRC_ERROR)]            = "CRC error",
574
        [NOERR(EFI_END_OF_MEDIA)]         = "End of media",
575
        [NOERR(EFI_ERROR_RESERVED_29)]    = "Reserved (29)",
576
        [NOERR(EFI_ERROR_RESERVED_30)]    = "Reserved (30)",
577
        [NOERR(EFI_END_OF_FILE)]          = "End of file",
578
        [NOERR(EFI_INVALID_LANGUAGE)]     = "Invalid language",
579
        [NOERR(EFI_COMPROMISED_DATA)]     = "Compromised data",
580
        [NOERR(EFI_IP_ADDRESS_CONFLICT)]  = "IP address conflict",
581
        [NOERR(EFI_HTTP_ERROR)]           = "HTTP error",
582
};
583

584
static const char *status_to_string(EFI_STATUS status) {
4✔
585
        if (status <= ELEMENTSOF(warn_table) - 1)
4✔
586
                return warn_table[status];
2✔
587
        if (status >= EFI_ERROR_MASK && status <= ((ELEMENTSOF(err_table) - 1) | EFI_ERROR_MASK))
2✔
588
                return err_table[NOERR(status)];
1✔
589
        return NULL;
590
}
591

592
typedef struct {
593
        size_t padded_len; /* Field width in printf. */
594
        size_t len;        /* Precision in printf. */
595
        bool pad_zero;
596
        bool align_left;
597
        bool alternative_form;
598
        bool long_arg;
599
        bool longlong_arg;
600
        bool have_field_width;
601

602
        const char *str;
603
        const wchar_t *wstr;
604

605
        /* For numbers. */
606
        bool is_signed;
607
        bool lowercase;
608
        int8_t base;
609
        char sign_pad; /* For + and (space) flags. */
610
} SpecifierContext;
611

612
typedef struct {
613
        char16_t stack_buf[128]; /* We use stack_buf first to avoid allocations in most cases. */
614
        char16_t *dyn_buf;       /* Allocated buf or NULL if stack_buf is used. */
615
        char16_t *buf;           /* Points to the current active buf. */
616
        size_t n_buf;            /* Len of buf (in char16_t's, not bytes!). */
617
        size_t n;                /* Used len of buf (in char16_t's). This is always <n_buf. */
618

619
        EFI_STATUS status;
620
        const char *format;
621
        va_list ap;
622
} FormatContext;
623

624
static void grow_buf(FormatContext *ctx, size_t need) {
388✔
625
        assert(ctx);
388✔
626

627
        assert_se(INC_SAFE(&need, ctx->n));
388✔
628

629
        if (need < ctx->n_buf)
388✔
630
                return;
631

632
        /* Greedily allocate if we can. */
633
        if (!MUL_SAFE(&ctx->n_buf, need, 2))
7✔
634
                ctx->n_buf = need;
×
635

636
        /* We cannot use realloc here as ctx->buf may be ctx->stack_buf, which we cannot free. */
637
        char16_t *new_buf = xnew(char16_t, ctx->n_buf);
7✔
638
        memcpy(new_buf, ctx->buf, ctx->n * sizeof(*ctx->buf));
7✔
639

640
        free(ctx->dyn_buf);
7✔
641
        ctx->buf = ctx->dyn_buf = new_buf;
7✔
642
}
643

644
static void push_padding(FormatContext *ctx, char pad, size_t len) {
528✔
645
        assert(ctx);
528✔
646
        while (len > 0) {
43,330✔
647
                len--;
42,802✔
648
                ctx->buf[ctx->n++] = pad;
42,802✔
649
        }
650
}
528✔
651

652
static bool push_str(FormatContext *ctx, SpecifierContext *sp) {
248✔
653
        assert(ctx);
248✔
654
        assert(sp);
248✔
655

656
        sp->padded_len = LESS_BY(sp->padded_len, sp->len);
248✔
657

658
        grow_buf(ctx, sp->padded_len + sp->len);
248✔
659

660
        if (!sp->align_left)
248✔
661
                push_padding(ctx, ' ', sp->padded_len);
240✔
662

663
        /* In userspace unit tests we cannot just memcpy() the wide string. */
664
        if (sp->wstr && sizeof(wchar_t) == sizeof(char16_t)) {
248✔
665
                memcpy(ctx->buf + ctx->n, sp->wstr, sp->len * sizeof(*sp->wstr));
666
                ctx->n += sp->len;
667
        } else {
668
                assert(sp->str || sp->wstr);
248✔
669
                for (size_t i = 0; i < sp->len; i++)
704✔
670
                        ctx->buf[ctx->n++] = sp->str ? sp->str[i] : sp->wstr[i];
456✔
671
        }
672

673
        if (sp->align_left)
248✔
674
                push_padding(ctx, ' ', sp->padded_len);
8✔
675

676
        assert(ctx->n < ctx->n_buf);
248✔
677
        return true;
248✔
678
}
679

680
static bool push_num(FormatContext *ctx, SpecifierContext *sp, uint64_t u) {
148✔
681
        const char *digits = sp->lowercase ? LOWERCASE_HEXDIGITS : UPPERCASE_HEXDIGITS;
148✔
682
        char16_t tmp[32];
148✔
683
        size_t n = 0;
148✔
684

685
        assert(ctx);
148✔
686
        assert(sp);
148✔
687
        assert(IN_SET(sp->base, 10, 16));
148✔
688

689
        /* "%.0u" prints nothing if value is 0. */
690
        if (u == 0 && sp->len == 0)
148✔
691
                return true;
148✔
692

693
        if (sp->is_signed && (int64_t) u < 0) {
140✔
694
                /* We cannot just do "u = -(int64_t)u" here because -INT64_MIN overflows. */
695

696
                uint64_t rem = -((int64_t) u % sp->base);
27✔
697
                u = (int64_t) u / -sp->base;
27✔
698
                tmp[n++] = digits[rem];
27✔
699
                sp->sign_pad = '-';
27✔
700
        }
701

702
        while (u > 0 || n == 0) {
965✔
703
                uint64_t rem = u % sp->base;
825✔
704
                u /= sp->base;
825✔
705
                tmp[n++] = digits[rem];
825✔
706
        }
707

708
        /* Note that numbers never get truncated! */
709
        size_t prefix = (sp->sign_pad != 0 ? 1 : 0) + (sp->alternative_form ? 2 : 0);
140✔
710
        size_t number_len = prefix + MAX(n, sp->len);
140✔
711
        grow_buf(ctx, MAX(sp->padded_len, number_len));
140✔
712

713
        size_t padding = 0;
140✔
714
        if (sp->pad_zero)
140✔
715
                /* Leading zeroes go after the sign or 0x prefix. */
716
                number_len = MAX(number_len, sp->padded_len);
10✔
717
        else
718
                padding = LESS_BY(sp->padded_len, number_len);
130✔
719

720
        if (!sp->align_left)
140✔
721
                push_padding(ctx, ' ', padding);
117✔
722

723
        if (sp->sign_pad != 0)
140✔
724
                ctx->buf[ctx->n++] = sp->sign_pad;
31✔
725
        if (sp->alternative_form) {
140✔
726
                ctx->buf[ctx->n++] = '0';
39✔
727
                ctx->buf[ctx->n++] = sp->lowercase ? 'x' : 'X';
56✔
728
        }
729

730
        push_padding(ctx, '0', LESS_BY(number_len, n + prefix));
140✔
731

732
        while (n > 0)
992✔
733
                ctx->buf[ctx->n++] = tmp[--n];
852✔
734

735
        if (sp->align_left)
140✔
736
                push_padding(ctx, ' ', padding);
23✔
737

738
        assert(ctx->n < ctx->n_buf);
140✔
739
        return true;
740
}
741

742
/* This helps unit testing. */
743
#if SD_BOOT
744
#  define NULLSTR "(null)"
745
#  define wcsnlen strnlen16
746
#else
747
#  define NULLSTR "(nil)"
748
#endif
749

750
static bool handle_format_specifier(FormatContext *ctx, SpecifierContext *sp) {
693✔
751
        /* Parses one item from the format specifier in ctx and put the info into sp. If we are done with
752
         * this specifier returns true, otherwise this function should be called again. */
753

754
        /* This implementation assumes 32-bit ints. Also note that all types smaller than int are promoted to
755
         * int in vararg functions, which is why we fetch only ints for any such types. The compiler would
756
         * otherwise warn about fetching smaller types. */
757
        assert_cc(sizeof(int) == 4);
693✔
758
        assert_cc(sizeof(wchar_t) <= sizeof(int));
693✔
759
        assert_cc(sizeof(long long) == sizeof(intmax_t));
693✔
760

761
        assert(ctx);
693✔
762
        assert(sp);
693✔
763

764
        switch (*ctx->format) {
693✔
765
        case '#':
31✔
766
                sp->alternative_form = true;
31✔
767
                return false;
31✔
768
        case '.':
103✔
769
                sp->have_field_width = true;
103✔
770
                return false;
103✔
771
        case '-':
26✔
772
                sp->align_left = true;
26✔
773
                return false;
26✔
774
        case '+':
11✔
775
        case ' ':
776
                sp->sign_pad = *ctx->format;
11✔
777
                return false;
11✔
778

779
        case '0':
20✔
780
                if (!sp->have_field_width) {
20✔
781
                        sp->pad_zero = true;
10✔
782
                        return false;
10✔
783
                }
784

785
                /* If field width has already been provided then 0 is part of precision (%.0s). */
786
                _fallthrough_;
217✔
787

788
        case '*':
789
        case '1' ... '9': {
790
                int64_t i;
217✔
791

792
                if (*ctx->format == '*')
217✔
793
                        i = va_arg(ctx->ap, int);
90✔
794
                else {
795
                        uint64_t u;
127✔
796
                        if (!parse_number8(ctx->format, &u, &ctx->format) || u > INT_MAX)
127✔
797
                                assert_not_reached();
×
798
                        ctx->format--; /* Point it back to the last digit. */
127✔
799
                        i = u;
127✔
800
                }
801

802
                if (sp->have_field_width) {
217✔
803
                        /* Negative precision is ignored. */
804
                        if (i >= 0)
98✔
805
                                sp->len = (size_t) i;
96✔
806
                } else {
807
                        /* Negative field width is treated as positive field width with '-' flag. */
808
                        if (i < 0) {
119✔
809
                                i *= -1;
5✔
810
                                sp->align_left = true;
5✔
811
                        }
812
                        sp->padded_len = i;
119✔
813
                }
814

815
                return false;
816
        }
817

818
        case 'h':
×
819
                if (*(ctx->format + 1) == 'h')
×
820
                        ctx->format++;
×
821
                /* char/short gets promoted to int, nothing to do here. */
822
                return false;
823

824
        case 'l':
52✔
825
                if (*(ctx->format + 1) == 'l') {
52✔
826
                        ctx->format++;
5✔
827
                        sp->longlong_arg = true;
5✔
828
                } else
829
                        sp->long_arg = true;
47✔
830
                return false;
831

832
        case 'z':
4✔
833
                sp->long_arg = sizeof(size_t) == sizeof(long);
4✔
834
                sp->longlong_arg = !sp->long_arg && sizeof(size_t) == sizeof(long long);
4✔
835
                return false;
4✔
836

837
        case 'j':
3✔
838
                sp->long_arg = sizeof(intmax_t) == sizeof(long);
3✔
839
                sp->longlong_arg = !sp->long_arg && sizeof(intmax_t) == sizeof(long long);
3✔
840
                return false;
3✔
841

842
        case 't':
2✔
843
                sp->long_arg = sizeof(ptrdiff_t) == sizeof(long);
2✔
844
                sp->longlong_arg = !sp->long_arg && sizeof(ptrdiff_t) == sizeof(long long);
2✔
845
                return false;
2✔
846

847
        case '%':
3✔
848
                sp->str = "%";
3✔
849
                sp->len = 1;
3✔
850
                return push_str(ctx, sp);
3✔
851

852
        case 'c':
5✔
853
                sp->wstr = &(wchar_t){ va_arg(ctx->ap, int) };
5✔
854
                sp->len = 1;
5✔
855
                return push_str(ctx, sp);
5✔
856

857
        case 's':
73✔
858
                if (sp->long_arg) {
73✔
859
                        sp->wstr = va_arg(ctx->ap, const wchar_t *) ?: L"(null)";
35✔
860
                        sp->len = wcsnlen(sp->wstr, sp->len);
35✔
861
                } else {
862
                        sp->str = va_arg(ctx->ap, const char *) ?: "(null)";
38✔
863
                        sp->len = strnlen8(sp->str, sp->len);
38✔
864
                }
865
                return push_str(ctx, sp);
73✔
866

867
        case 'd':
140✔
868
        case 'i':
869
        case 'u':
870
        case 'x':
871
        case 'X':
872
                sp->lowercase = *ctx->format == 'x';
140✔
873
                sp->is_signed = IN_SET(*ctx->format, 'd', 'i');
140✔
874
                sp->base = IN_SET(*ctx->format, 'x', 'X') ? 16 : 10;
140✔
875
                if (sp->len == SIZE_MAX)
140✔
876
                        sp->len = 1;
94✔
877

878
                uint64_t v;
140✔
879
                if (sp->longlong_arg)
140✔
880
                        v = sp->is_signed ? (uint64_t) va_arg(ctx->ap, long long) :
5✔
881
                                            va_arg(ctx->ap, unsigned long long);
3✔
882
                else if (sp->long_arg)
135✔
883
                        v = sp->is_signed ? (uint64_t) va_arg(ctx->ap, long) : va_arg(ctx->ap, unsigned long);
21✔
884
                else
885
                        v = sp->is_signed ? (uint64_t) va_arg(ctx->ap, int) : va_arg(ctx->ap, unsigned);
114✔
886

887
                return push_num(ctx, sp, v);
140✔
888

889
        case 'p': {
9✔
890
                const void *ptr = va_arg(ctx->ap, const void *);
9✔
891
                if (!ptr) {
9✔
892
                        sp->str = NULLSTR;
2✔
893
                        sp->len = STRLEN(NULLSTR);
2✔
894
                        return push_str(ctx, sp);
2✔
895
                }
896

897
                sp->base = 16;
7✔
898
                sp->lowercase = true;
7✔
899
                sp->alternative_form = true;
7✔
900
                sp->len = 0; /* Precision is ignored for %p. */
7✔
901
                return push_num(ctx, sp, (uintptr_t) ptr);
7✔
902
        }
903

904
        case 'm': {
4✔
905
                sp->str = status_to_string(ctx->status);
4✔
906
                if (sp->str) {
4✔
907
                        sp->len = strlen8(sp->str);
3✔
908
                        return push_str(ctx, sp);
3✔
909
                }
910

911
                sp->base = 16;
1✔
912
                sp->lowercase = true;
1✔
913
                sp->alternative_form = true;
1✔
914
                sp->len = 0;
1✔
915
                return push_num(ctx, sp, ctx->status);
1✔
916
        }
917

918
        default:
×
919
                assert_not_reached();
×
920
        }
921
}
922

923
#if SD_BOOT
924
static void output_string_safe(EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *this, const char16_t *s) {
925
        assert(this);
926
        assert(s);
927

928
        /* This is a color-conscious version of ST->ConOut->OutputString(). Whenever it encounters a newline
929
         * character, it will reset the color to our default, because some UEFI implementations/terminals
930
         * reset the color in that case, and we want our default color to remain in effect */
931

932
        int32_t saved_attribute = ST->ConOut->Mode->Attribute;
933
        for (;;) {
934
                const char16_t *nl = strchr16(s, '\n');
935
                if (!nl) /* No further newline */
936
                        return (void) ST->ConOut->OutputString(ST->ConOut, (char16_t*) s);
937

938
                if (nl[1] == 0) { /* Newline is at the end of the string */
939
                        (void) ST->ConOut->OutputString(ST->ConOut, (char16_t*) s);
940
                        set_attribute_safe(saved_attribute);
941
                        return;
942
                }
943

944
                /* newline is in the middle of the string */
945
                _cleanup_free_ char16_t *x = xstrndup16(s, nl - s + 1);
946
                (void) ST->ConOut->OutputString(ST->ConOut, x);
947
                set_attribute_safe(saved_attribute);
948

949
                s = nl + 1;
950
        }
951
}
952
#endif
953

954
/* printf_internal is largely compatible to userspace vasprintf. Any features omitted should trigger asserts.
955
 *
956
 * Supported:
957
 *  - Flags: #, 0, +, -, space
958
 *  - Lengths: h, hh, l, ll, z, j, t
959
 *  - Specifiers: %, c, s, u, i, d, x, X, p, m
960
 *  - Precision and width (inline or as int arg using *)
961
 *
962
 * Notable differences:
963
 *  - Passing NULL to %s is permitted and will print "(null)"
964
 *  - %p will also use "(null)"
965
 *  - The provided EFI_STATUS is used for %m instead of errno
966
 *  - "\n" is translated to "\r\n" */
967
_printf_(2, 0) static char16_t *printf_internal(EFI_STATUS status, const char *format, va_list ap, bool ret) {
74✔
968
        assert(format);
74✔
969

970
        FormatContext ctx = {
74✔
971
                .buf = ctx.stack_buf,
972
                .n_buf = ELEMENTSOF(ctx.stack_buf),
973
                .format = format,
974
                .status = status,
975
        };
976

977
        /* We cannot put this into the struct without making a copy. */
978
        va_copy(ctx.ap, ap);
74✔
979

980
        while (*ctx.format != '\0') {
470✔
981
                SpecifierContext sp = { .len = SIZE_MAX };
396✔
982

983
                switch (*ctx.format) {
396✔
984
                case '%':
234✔
985
                        ctx.format++;
234✔
986
                        while (!handle_format_specifier(&ctx, &sp))
693✔
987
                                ctx.format++;
459✔
988
                        ctx.format++;
234✔
989
                        break;
234✔
990
                case '\n':
2✔
991
                        ctx.format++;
2✔
992
                        sp.str = "\r\n";
2✔
993
                        sp.len = 2;
2✔
994
                        push_str(&ctx, &sp);
2✔
995
                        break;
996
                default:
160✔
997
                        sp.str = ctx.format++;
160✔
998
                        while (!IN_SET(*ctx.format, '%', '\n', '\0'))
168✔
999
                                ctx.format++;
8✔
1000
                        sp.len = ctx.format - sp.str;
160✔
1001
                        push_str(&ctx, &sp);
160✔
1002
                }
1003
        }
1004

1005
        va_end(ctx.ap);
74✔
1006

1007
        assert(ctx.n < ctx.n_buf);
74✔
1008
        ctx.buf[ctx.n++] = '\0';
74✔
1009

1010
        if (ret) {
74✔
1011
                if (ctx.dyn_buf)
74✔
1012
                        return TAKE_PTR(ctx.dyn_buf);
3✔
1013

1014
                char16_t *ret_buf = xnew(char16_t, ctx.n);
71✔
1015
                memcpy(ret_buf, ctx.buf, ctx.n * sizeof(*ctx.buf));
71✔
1016
                return ret_buf;
71✔
1017
        }
1018

1019
#if SD_BOOT
1020
        output_string_safe(ST->ConOut, ctx.buf);
1021
#endif
1022

1023
        return mfree(ctx.dyn_buf);
×
1024
}
1025

1026
void printf_status(EFI_STATUS status, const char *format, ...) {
×
1027
        va_list ap;
×
1028
        va_start(ap, format);
×
1029
        printf_internal(status, format, ap, false);
×
1030
        va_end(ap);
×
1031
}
×
1032

1033
void vprintf_status(EFI_STATUS status, const char *format, va_list ap) {
×
1034
        printf_internal(status, format, ap, false);
×
1035
}
×
1036

1037
char16_t *xasprintf_status(EFI_STATUS status, const char *format, ...) {
5✔
1038
        va_list ap;
5✔
1039
        va_start(ap, format);
5✔
1040
        char16_t *ret = printf_internal(status, format, ap, true);
5✔
1041
        va_end(ap);
5✔
1042
        return ret;
5✔
1043
}
1044

1045
char16_t *xvasprintf_status(EFI_STATUS status, const char *format, va_list ap) {
69✔
1046
        return printf_internal(status, format, ap, true);
69✔
1047
}
1048

1049
#if SD_BOOT
1050
/* To provide the actual implementation for these we need to remove the redirection to the builtins. */
1051
#  undef memchr
1052
#  undef memcmp
1053
#  undef memcpy
1054
#  undef memset
1055
// NOLINTBEGIN(misc-use-internal-linkage)
1056
_used_ void *memchr(const void *p, int c, size_t n);
1057
_used_ int memcmp(const void *p1, const void *p2, size_t n);
1058
_used_ void *memcpy(void * restrict dest, const void * restrict src, size_t n);
1059
_used_ void *memset(void *p, int c, size_t n);
1060
// NOLINTEND(misc-use-internal-linkage)
1061
#else
1062
/* And for userspace unit testing we need to give them an efi_ prefix. */
1063
#  undef memchr
1064
#  define memchr efi_memchr
1065
#  define memcmp efi_memcmp
1066
#  define memcpy efi_memcpy
1067
#  define memset efi_memset
1068
#endif
1069

1070
void *memchr(const void *p, int c, size_t n) {
10✔
1071
        if (!p || n == 0)
10✔
1072
                return NULL;
1073

1074
        const uint8_t *q = p;
1075
        for (size_t i = 0; i < n; i++)
26✔
1076
                if (q[i] == (unsigned char) c)
24✔
1077
                        return (void *) (q + i);
1078

1079
        return NULL;
1080
}
1081

1082
int memcmp(const void *p1, const void *p2, size_t n) {
15✔
1083
        const uint8_t *up1 = p1, *up2 = p2;
15✔
1084
        int r;
15✔
1085

1086
        if (!p1 || !p2)
15✔
1087
                return CMP(p1, p2);
4✔
1088

1089
        while (n > 0) {
29✔
1090
                r = CMP(*up1, *up2);
24✔
1091
                if (r != 0)
20✔
1092
                        return r;
6✔
1093

1094
                up1++;
18✔
1095
                up2++;
18✔
1096
                n--;
18✔
1097
        }
1098

1099
        return 0;
1100
}
1101

1102
void *memcpy(void * restrict dest, const void * restrict src, size_t n) {
9✔
1103
        if (!dest || !src || n == 0)
9✔
1104
                return dest;
1105

1106
#if SD_BOOT
1107
        /* The firmware-provided memcpy is likely optimized, so use that. The function is guaranteed to be
1108
         * available by the UEFI spec. We still make it depend on the boot services pointer being set just in
1109
         * case the compiler emits a call before it is available. */
1110
        if (_likely_(BS)) {
1111
                BS->CopyMem(dest, (void *) src, n);
1112
                return dest;
1113
        }
1114
#endif
1115

1116
        uint8_t *d = dest;
1117
        const uint8_t *s = src;
1118

1119
        while (n > 0) {
18✔
1120
                *d = *s;
14✔
1121
                d++;
14✔
1122
                s++;
14✔
1123
                n--;
14✔
1124
        }
1125

1126
        return dest;
1127
}
1128

1129
void *memset(void *p, int c, size_t n) {
6✔
1130
        if (!p || n == 0)
6✔
1131
                return p;
1132

1133
#if SD_BOOT
1134
        /* See comment in efi_memcpy. Note that the signature has c and n swapped! */
1135
        if (_likely_(BS)) {
1136
                BS->SetMem(p, n, c);
1137
                return p;
1138
        }
1139
#endif
1140

1141
        uint8_t *q = p;
1142
        while (n > 0) {
18✔
1143
                *q = c;
15✔
1144
                q++;
15✔
1145
                n--;
15✔
1146
        }
1147

1148
        return p;
1149
}
1150

1151
size_t strspn16(const char16_t *p, const char16_t *good) {
7✔
1152
        assert(p);
7✔
1153
        assert(good);
7✔
1154

1155
        const char16_t *i = p;
1156
        for (; *i != 0; i++)
25✔
1157
                if (!strchr16(good, *i))
23✔
1158
                        break;
1159

1160
        return i - p;
7✔
1161
}
1162

1163
size_t strcspn16(const char16_t *p, const char16_t *bad) {
10✔
1164
        assert(p);
10✔
1165
        assert(bad);
10✔
1166

1167
        const char16_t *i = p;
1168
        for (; *i != 0; i++)
41✔
1169
                if (strchr16(bad, *i))
37✔
1170
                        break;
1171

1172
        return i - p;
10✔
1173
}
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