Debian Codegraph @

src/boot/efi-string.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "efi-string.h"
4 #include "string-util.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);
38 DEFINE_STRNLEN(char16_t, strnlen16);
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);
56 DEFINE_STRTOLOWER(char16_t, strtolower16);
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);
81 DEFINE_STRNCASECMP(char16_t, strncmp16, false);
82 DEFINE_STRNCASECMP(char, strncasecmp8, true);
83 DEFINE_STRNCASECMP(char16_t, strncasecmp16, true);
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);
105 DEFINE_STRCPY(char16_t, strcpy16);
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);
122 DEFINE_STRCHR(char16_t, strchr16);
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);
141 DEFINE_STRNDUP(char16_t, xstrndup16, strnlen16);
142
143 static unsigned utf8_to_unichar(const char *utf8, size_t n, char32_t *c) {
144 char32_t unichar;
145 unsigned len;
146
147 assert(utf8);
148 assert(c);
149
150 if (!(utf8[0] & 0x80)) {
151 *c = utf8[0];
152 return 1;
153 } else if ((utf8[0] & 0xe0) == 0xc0) {
154 len = 2;
155 unichar = utf8[0] & 0x1f;
156 } else if ((utf8[0] & 0xf0) == 0xe0) {
157 len = 3;
158 unichar = utf8[0] & 0x0f;
159 } else if ((utf8[0] & 0xf8) == 0xf0) {
160 len = 4;
161 unichar = utf8[0] & 0x07;
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) {
174 *c = UINT32_MAX;
175 return len;
176 }
177
178 for (unsigned i = 1; i < len; i++) {
179 if ((utf8[i] & 0xc0) != 0x80) {
180 *c = UINT32_MAX;
181 return len;
182 }
183 unichar <<= 6;
184 unichar |= utf8[i] & 0x3f;
185 }
186
187 *c = unichar;
188 return len;
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) {
193 assert(str8 || n == 0);
194
195 if (n == SIZE_MAX)
196 n = strlen8(str8);
197
198 size_t i = 0;
199 char16_t *str16 = xnew(char16_t, n + 1);
200
201 while (n > 0 && *str8 != '\0') {
202 char32_t unichar;
203
204 size_t utf8len = utf8_to_unichar(str8, n, &unichar);
205 str8 += utf8len;
206 n = LESS_BY(n, utf8len);
207
208 switch (unichar) {
209 case 0 ... 0xd7ffU:
210 case 0xe000U ... 0xffffU:
211 str16[i++] = unichar;
212 break;
213 }
214 }
215
216 str16[i] = u'\0';
217 return str16;
218 }
219
220 char *xstrn16_to_ascii(const char16_t *str16, size_t n) {
221 assert(str16 || n == 0);
222
223 if (n == SIZE_MAX)
224 n = strlen16(str16);
225
226 _cleanup_free_ char *str8 = xnew(char, n + 1);
227
228 size_t i = 0;
229 while (n > 0 && *str16 != u'\0') {
230
231 if ((uint16_t) *str16 > 127U) /* Not ASCII? Fail! */
232 return NULL;
233
234 str8[i++] = (char) (uint16_t) *str16;
235
236 str16++;
237 n--;
238 }
239
240 str8[i] = '\0';
241 return TAKE_PTR(str8);
242 }
243
244 char* startswith8(const char *s, const char *prefix) {
245 size_t l;
246
247 assert(prefix);
248
249 if (!s)
250 return NULL;
251
252 l = strlen8(prefix);
253 if (!strneq8(s, prefix, l))
254 return NULL;
255
256 return (char*) s + l;
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) {
260 assert(p);
261 assert(h);
262 assert(ret_p);
263 assert(ret_h);
264
265 for (;; p++, h++)
266 switch (*p) {
267 case '\0':
268 /* End of pattern. Check that haystack is now empty. */
269 return *h == '\0';
270
271 case '\\':
272 p++;
273 if (*p == '\0' || *p != *h)
274 /* Trailing escape or no match. */
275 return false;
276 break;
277
278 case '?':
279 if (*h == '\0')
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 == '*')
287 p++;
288 *ret_p = p;
289 *ret_h = h;
290 return true;
291
292 case '[':
293 if (*h == '\0')
294 /* Early end of haystack. */
295 return false;
296
297 bool first = true, can_range = true, match = false;
298 for (;; first = false) {
299 p++;
300 if (*p == '\0')
301 return false;
302
303 if (*p == '\\') {
304 p++;
305 if (*p == '\0')
306 return false;
307 if (*p == *h)
308 match = true;
309 can_range = true;
310 continue;
311 }
312
313 /* End of set unless it's the first char. */
314 if (*p == ']' && !first)
315 break;
316
317 /* Range pattern if '-' is not first or last in set. */
318 if (*p == '-' && can_range && !first && *(p + 1) != ']') {
319 char16_t low = *(p - 1);
320 p++;
321 if (*p == '\\')
322 p++;
323 if (*p == '\0')
324 return false;
325
326 if (low <= *h && *h <= *p)
327 match = true;
328
329 /* Ranges cannot be chained: [a-c-f] == [-abcf] */
330 can_range = false;
331 continue;
332 }
333
334 if (*p == *h)
335 match = true;
336 can_range = true;
337 }
338
339 if (!match)
340 return false;
341 break;
342
343 default:
344 if (*p != *h)
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) {
352 assert(haystack);
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;;) {
364 const char16_t *pattern_tail = NULL, *haystack_tail = NULL;
365 bool match = efi_fnmatch_prefix(pattern, haystack, &pattern_tail, &haystack_tail);
366 if (first) {
367 if (!match)
368 /* Initial simple pattern must match. */
369 return false;
370 if (!pattern_tail)
371 /* No '*' was in pattern, we can return early. */
372 return true;
373 first = false;
374 }
375
376 if (pattern_tail) {
377 assert(match);
378 pattern = pattern_tail;
379 haystack = haystack_tail;
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')
385 return match;
386
387 /* Match one character using '*'. */
388 haystack++;
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);
423 DEFINE_PARSE_NUMBER(char16_t, parse_number16);
424
425 bool parse_boolean(const char *v, bool *ret) {
426 assert(ret);
427
428 if (!v)
429 return false;
430
431 if (streq8(v, "1") || streq8(v, "yes") || streq8(v, "y") || streq8(v, "true") || streq8(v, "t") ||
432 streq8(v, "on")) {
433 *ret = true;
434 return true;
435 }
436
437 if (streq8(v, "0") || streq8(v, "no") || streq8(v, "n") || streq8(v, "false") || streq8(v, "f") ||
438 streq8(v, "off")) {
439 *ret = false;
440 return true;
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) {
447 char *line, *value;
448 size_t linelen;
449
450 assert(s);
451 assert(sep);
452 assert(pos);
453 assert(ret_key);
454 assert(ret_value);
455
456 for (;;) {
457 line = s + *pos;
458 if (*line == '\0')
459 return NULL;
460
461 linelen = 0;
462 while (line[linelen] && !strchr8("\n\r", line[linelen]))
463 linelen++;
464
465 /* move pos to next line */
466 *pos += linelen;
467 if (s[*pos])
468 (*pos)++;
469
470 /* empty line */
471 if (linelen == 0)
472 continue;
473
474 /* terminate line */
475 line[linelen] = '\0';
476
477 /* remove leading whitespace */
478 while (linelen > 0 && strchr8(" \t", *line)) {
479 line++;
480 linelen--;
481 }
482
483 /* remove trailing whitespace */
484 while (linelen > 0 && strchr8(" \t", line[linelen - 1]))
485 linelen--;
486 line[linelen] = '\0';
487
488 if (*line == '#')
489 continue;
490
491 /* split key/value */
492 value = line;
493 while (*value && !strchr8(sep, *value))
494 value++;
495 if (*value == '\0')
496 continue;
497 *value = '\0';
498 value++;
499 while (*value && strchr8(sep, *value))
500 value++;
501
502 /* unquote */
503 if (strchr8(QUOTES, value[0]) && line[linelen - 1] == value[0]) {
504 value++;
505 line[linelen - 1] = '\0';
506 }
507
508 *ret_key = line;
509 *ret_value = value;
510 return line;
511 }
512 }
513
514 char16_t *hexdump(const void *data, size_t size) {
515 const char *hex = LOWERCASE_HEXDIGITS;
516 const uint8_t *d = data;
517
518 assert(data || size == 0);
519
520 char16_t *buf = xnew(char16_t, size * 2 + 1);
521
522 for (size_t i = 0; i < size; i++) {
523 buf[i * 2] = hex[d[i] >> 4];
524 buf[i * 2 + 1] = hex[d[i] & 0x0F];
525 }
526
527 buf[size * 2] = 0;
528 return buf;
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) {
585 if (status <= ELEMENTSOF(warn_table) - 1)
586 return warn_table[status];
587 if (status >= EFI_ERROR_MASK && status <= ((ELEMENTSOF(err_table) - 1) | EFI_ERROR_MASK))
588 return err_table[NOERR(status)];
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) {
625 assert(ctx);
626
627 assert_se(INC_SAFE(&need, ctx->n));
628
629 if (need < ctx->n_buf)
630 return;
631
632 /* Greedily allocate if we can. */
633 if (!MUL_SAFE(&ctx->n_buf, need, 2))
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);
638 memcpy(new_buf, ctx->buf, ctx->n * sizeof(*ctx->buf));
639
640 free(ctx->dyn_buf);
641 ctx->buf = ctx->dyn_buf = new_buf;
642 }
643
644 static void push_padding(FormatContext *ctx, char pad, size_t len) {
645 assert(ctx);
646 while (len > 0) {
647 len--;
648 ctx->buf[ctx->n++] = pad;
649 }
650 }
651
652 static bool push_str(FormatContext *ctx, SpecifierContext *sp) {
653 assert(ctx);
654 assert(sp);
655
656 sp->padded_len = LESS_BY(sp->padded_len, sp->len);
657
658 grow_buf(ctx, sp->padded_len + sp->len);
659
660 if (!sp->align_left)
661 push_padding(ctx, ' ', sp->padded_len);
662
663 /* In userspace unit tests we cannot just memcpy() the wide string. */
664 if (sp->wstr && sizeof(wchar_t) == sizeof(char16_t)) {
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);
669 for (size_t i = 0; i < sp->len; i++)
670 ctx->buf[ctx->n++] = sp->str ? sp->str[i] : sp->wstr[i];
671 }
672
673 if (sp->align_left)
674 push_padding(ctx, ' ', sp->padded_len);
675
676 assert(ctx->n < ctx->n_buf);
677 return true;
678 }
679
680 static bool push_num(FormatContext *ctx, SpecifierContext *sp, uint64_t u) {
681 const char *digits = sp->lowercase ? LOWERCASE_HEXDIGITS : UPPERCASE_HEXDIGITS;
682 char16_t tmp[32];
683 size_t n = 0;
684
685 assert(ctx);
686 assert(sp);
687 assert(IN_SET(sp->base, 10, 16));
688
689 /* "%.0u" prints nothing if value is 0. */
690 if (u == 0 && sp->len == 0)
691 return true;
692
693 if (sp->is_signed && (int64_t) u < 0) {
694 /* We cannot just do "u = -(int64_t)u" here because -INT64_MIN overflows. */
695
696 uint64_t rem = -((int64_t) u % sp->base);
697 u = (int64_t) u / -sp->base;
698 tmp[n++] = digits[rem];
699 sp->sign_pad = '-';
700 }
701
702 while (u > 0 || n == 0) {
703 uint64_t rem = u % sp->base;
704 u /= sp->base;
705 tmp[n++] = digits[rem];
706 }
707
708 /* Note that numbers never get truncated! */
709 size_t prefix = (sp->sign_pad != 0 ? 1 : 0) + (sp->alternative_form ? 2 : 0);
710 size_t number_len = prefix + MAX(n, sp->len);
711 grow_buf(ctx, MAX(sp->padded_len, number_len));
712
713 size_t padding = 0;
714 if (sp->pad_zero)
715 /* Leading zeroes go after the sign or 0x prefix. */
716 number_len = MAX(number_len, sp->padded_len);
717 else
718 padding = LESS_BY(sp->padded_len, number_len);
719
720 if (!sp->align_left)
721 push_padding(ctx, ' ', padding);
722
723 if (sp->sign_pad != 0)
724 ctx->buf[ctx->n++] = sp->sign_pad;
725 if (sp->alternative_form) {
726 ctx->buf[ctx->n++] = '0';
727 ctx->buf[ctx->n++] = sp->lowercase ? 'x' : 'X';
728 }
729
730 push_padding(ctx, '0', LESS_BY(number_len, n + prefix));
731
732 while (n > 0)
733 ctx->buf[ctx->n++] = tmp[--n];
734
735 if (sp->align_left)
736 push_padding(ctx, ' ', padding);
737
738 assert(ctx->n < ctx->n_buf);
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) {
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);
758 assert_cc(sizeof(wchar_t) <= sizeof(int));
759 assert_cc(sizeof(long long) == sizeof(intmax_t));
760
761 assert(ctx);
762 assert(sp);
763
764 switch (*ctx->format) {
765 case '#':
766 sp->alternative_form = true;
767 return false;
768 case '.':
769 sp->have_field_width = true;
770 return false;
771 case '-':
772 sp->align_left = true;
773 return false;
774 case '+':
775 case ' ':
776 sp->sign_pad = *ctx->format;
777 return false;
778
779 case '0':
780 if (!sp->have_field_width) {
781 sp->pad_zero = true;
782 return false;
783 }
784
785 /* If field width has already been provided then 0 is part of precision (%.0s). */
786 _fallthrough_;
787
788 case '*':
789 case '1' ... '9': {
790 int64_t i;
791
792 if (*ctx->format == '*')
793 i = va_arg(ctx->ap, int);
794 else {
795 uint64_t u;
796 if (!parse_number8(ctx->format, &u, &ctx->format) || u > INT_MAX)
797 assert_not_reached();
798 ctx->format--; /* Point it back to the last digit. */
799 i = u;
800 }
801
802 if (sp->have_field_width) {
803 /* Negative precision is ignored. */
804 if (i >= 0)
805 sp->len = (size_t) i;
806 } else {
807 /* Negative field width is treated as positive field width with '-' flag. */
808 if (i < 0) {
809 i *= -1;
810 sp->align_left = true;
811 }
812 sp->padded_len = i;
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':
825 if (*(ctx->format + 1) == 'l') {
826 ctx->format++;
827 sp->longlong_arg = true;
828 } else
829 sp->long_arg = true;
830 return false;
831
832 case 'z':
833 sp->long_arg = sizeof(size_t) == sizeof(long);
834 sp->longlong_arg = !sp->long_arg && sizeof(size_t) == sizeof(long long);
835 return false;
836
837 case 'j':
838 sp->long_arg = sizeof(intmax_t) == sizeof(long);
839 sp->longlong_arg = !sp->long_arg && sizeof(intmax_t) == sizeof(long long);
840 return false;
841
842 case 't':
843 sp->long_arg = sizeof(ptrdiff_t) == sizeof(long);
844 sp->longlong_arg = !sp->long_arg && sizeof(ptrdiff_t) == sizeof(long long);
845 return false;
846
847 case '%':
848 sp->str = "%";
849 sp->len = 1;
850 return push_str(ctx, sp);
851
852 case 'c':
853 sp->wstr = &(wchar_t){ va_arg(ctx->ap, int) };
854 sp->len = 1;
855 return push_str(ctx, sp);
856
857 case 's':
858 if (sp->long_arg) {
859 sp->wstr = va_arg(ctx->ap, const wchar_t *) ?: L"(null)";
860 sp->len = wcsnlen(sp->wstr, sp->len);
861 } else {
862 sp->str = va_arg(ctx->ap, const char *) ?: "(null)";
863 sp->len = strnlen8(sp->str, sp->len);
864 }
865 return push_str(ctx, sp);
866
867 case 'd':
868 case 'i':
869 case 'u':
870 case 'x':
871 case 'X':
872 sp->lowercase = *ctx->format == 'x';
873 sp->is_signed = IN_SET(*ctx->format, 'd', 'i');
874 sp->base = IN_SET(*ctx->format, 'x', 'X') ? 16 : 10;
875 if (sp->len == SIZE_MAX)
876 sp->len = 1;
877
878 uint64_t v;
879 if (sp->longlong_arg)
880 v = sp->is_signed ? (uint64_t) va_arg(ctx->ap, long long) :
881 va_arg(ctx->ap, unsigned long long);
882 else if (sp->long_arg)
883 v = sp->is_signed ? (uint64_t) va_arg(ctx->ap, long) : va_arg(ctx->ap, unsigned long);
884 else
885 v = sp->is_signed ? (uint64_t) va_arg(ctx->ap, int) : va_arg(ctx->ap, unsigned);
886
887 return push_num(ctx, sp, v);
888
889 case 'p': {
890 const void *ptr = va_arg(ctx->ap, const void *);
891 if (!ptr) {
892 sp->str = NULLSTR;
893 sp->len = STRLEN(NULLSTR);
894 return push_str(ctx, sp);
895 }
896
897 sp->base = 16;
898 sp->lowercase = true;
899 sp->alternative_form = true;
900 sp->len = 0; /* Precision is ignored for %p. */
901 return push_num(ctx, sp, (uintptr_t) ptr);
902 }
903
904 case 'm': {
905 sp->str = status_to_string(ctx->status);
906 if (sp->str) {
907 sp->len = strlen8(sp->str);
908 return push_str(ctx, sp);
909 }
910
911 sp->base = 16;
912 sp->lowercase = true;
913 sp->alternative_form = true;
914 sp->len = 0;
915 return push_num(ctx, sp, ctx->status);
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) {
968 assert(format);
969
970 FormatContext ctx = {
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);
979
980 while (*ctx.format != '\0') {
981 SpecifierContext sp = { .len = SIZE_MAX };
982
983 switch (*ctx.format) {
984 case '%':
985 ctx.format++;
986 while (!handle_format_specifier(&ctx, &sp))
987 ctx.format++;
988 ctx.format++;
989 break;
990 case '\n':
991 ctx.format++;
992 sp.str = "\r\n";
993 sp.len = 2;
994 push_str(&ctx, &sp);
995 break;
996 default:
997 sp.str = ctx.format++;
998 while (!IN_SET(*ctx.format, '%', '\n', '\0'))
999 ctx.format++;
1000 sp.len = ctx.format - sp.str;
1001 push_str(&ctx, &sp);
1002 }
1003 }
1004
1005 va_end(ctx.ap);
1006
1007 assert(ctx.n < ctx.n_buf);
1008 ctx.buf[ctx.n++] = '\0';
1009
1010 if (ret) {
1011 if (ctx.dyn_buf)
1012 return TAKE_PTR(ctx.dyn_buf);
1013
1014 char16_t *ret_buf = xnew(char16_t, ctx.n);
1015 memcpy(ret_buf, ctx.buf, ctx.n * sizeof(*ctx.buf));
1016 return ret_buf;
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, ...) {
1038 va_list ap;
1039 va_start(ap, format);
1040 char16_t *ret = printf_internal(status, format, ap, true);
1041 va_end(ap);
1042 return ret;
1043 }
1044
1045 char16_t *xvasprintf_status(EFI_STATUS status, const char *format, va_list ap) {
1046 return printf_internal(status, format, ap, true);
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) {
1071 if (!p || n == 0)
1072 return NULL;
1073
1074 const uint8_t *q = p;
1075 for (size_t i = 0; i < n; i++)
1076 if (q[i] == (unsigned char) c)
1077 return (void *) (q + i);
1078
1079 return NULL;
1080 }
1081
1082 int memcmp(const void *p1, const void *p2, size_t n) {
1083 const uint8_t *up1 = p1, *up2 = p2;
1084 int r;
1085
1086 if (!p1 || !p2)
1087 return CMP(p1, p2);
1088
1089 while (n > 0) {
1090 r = CMP(*up1, *up2);
1091 if (r != 0)
1092 return r;
1093
1094 up1++;
1095 up2++;
1096 n--;
1097 }
1098
1099 return 0;
1100 }
1101
1102 void *memcpy(void * restrict dest, const void * restrict src, size_t n) {
1103 if (!dest || !src || n == 0)
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) {
1120 *d = *s;
1121 d++;
1122 s++;
1123 n--;
1124 }
1125
1126 return dest;
1127 }
1128
1129 void *memset(void *p, int c, size_t n) {
1130 if (!p || n == 0)
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) {
1143 *q = c;
1144 q++;
1145 n--;
1146 }
1147
1148 return p;
1149 }
1150
1151 size_t strspn16(const char16_t *p, const char16_t *good) {
1152 assert(p);
1153 assert(good);
1154
1155 const char16_t *i = p;
1156 for (; *i != 0; i++)
1157 if (!strchr16(good, *i))
1158 break;
1159
1160 return i - p;
1161 }
1162
1163 size_t strcspn16(const char16_t *p, const char16_t *bad) {
1164 assert(p);
1165 assert(bad);
1166
1167 const char16_t *i = p;
1168 for (; *i != 0; i++)
1169 if (strchr16(bad, *i))
1170 break;
1171
1172 return i - p;
1173 }