Debian Codegraph @

src/boot/util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "device-path-util.h"
4
5 #include "efi-log.h"
6 #include "efi-string.h"
7 #include "memory-util.h"
8 #include "proto/device-path.h"
9 #include "proto/simple-text-io.h"
10 #include "string-util.h"
11 #include "util.h"
12 #include "version.h"
13
14 /* Never try to read more than 16G into memory (and on 32bit 1G) */
15 #define FILE_READ_MAX MIN(SIZE_MAX/4, UINT64_C(16)*1024U*1024U*1024U)
16
17 void free(void *p) {
18 if (!p)
19 return;
20
21 /* Debugging an invalid free requires trace logging to find the call site or a debugger attached. For
22 * release builds it is not worth the bother to even warn when we cannot even print a call stack. */
23 #ifdef EFI_DEBUG
24 assert_se(BS->FreePool(p) == EFI_SUCCESS);
25 #else
26 (void) BS->FreePool(p);
27 #endif
28 }
29
30 void convert_efi_path(char16_t *path) {
31 assert(path);
32
33 for (size_t i = 0, fixed = 0;; i++) {
34 /* Fix device path node separator. */
35 path[fixed] = (path[i] == '/') ? '\\' : path[i];
36
37 /* Double '\' is not allowed in EFI file paths. */
38 if (fixed > 0 && path[fixed - 1] == '\\' && path[fixed] == '\\')
39 continue;
40
41 if (path[i] == '\0')
42 break;
43
44 fixed++;
45 }
46 }
47
48 char16_t *xstr8_to_path(const char *str8) {
49 assert(str8);
50 char16_t *path = xstr8_to_16(str8);
51 convert_efi_path(path);
52 return path;
53 }
54
55 static bool shall_be_whitespace(char16_t c) {
56 return c <= 0x20U || c == 0x7FU; /* All control characters + space */
57 }
58
59 char16_t* mangle_stub_cmdline(char16_t *cmdline) {
60 if (!cmdline)
61 return cmdline;
62
63 /* Skip initial whitespace */
64 const char16_t *p = cmdline;
65 while (*p != 0 && shall_be_whitespace(*p))
66 p++;
67
68 /* Turn inner control characters into proper spaces */
69 char16_t *e = cmdline;
70 for (char16_t *q = cmdline; *p != 0; p++) {
71 if (shall_be_whitespace(*p)) {
72 *(q++) = ' ';
73 continue;
74 }
75
76 *(q++) = *p;
77 e = q; /* remember last non-whitespace char */
78 }
79
80 /* Chop off trailing whitespace */
81 *e = 0;
82 return cmdline;
83 }
84
85 EFI_STATUS chunked_read(EFI_FILE *file, size_t *size, void *buf) {
86 EFI_STATUS err;
87
88 assert(file);
89 assert(size);
90 assert(buf);
91
92 /* This is a drop-in replacement for EFI_FILE->Read() with the same API behavior.
93 * Some broken firmwares cannot handle large file reads and will instead return
94 * an error. As a workaround, read such files in small chunks.
95 * Note that we cannot just try reading the whole file first on such firmware as
96 * that will permanently break the handle even if it is reopened.
97 *
98 * https://github.com/systemd/systemd/issues/25911 */
99
100 if (*size == 0)
101 return EFI_SUCCESS;
102
103 size_t read = 0, remaining = *size;
104 while (remaining > 0) {
105 size_t chunk = MIN(1024U * 1024U, remaining);
106
107 err = file->Read(file, &chunk, (uint8_t *) buf + read);
108 if (err != EFI_SUCCESS)
109 return err;
110 if (chunk == 0)
111 /* Caller requested more bytes than are in file. */
112 break;
113
114 assert(chunk <= remaining);
115 read += chunk;
116 remaining -= chunk;
117 }
118
119 *size = read;
120 return EFI_SUCCESS;
121 }
122
123 EFI_STATUS file_handle_read(
124 EFI_FILE *handle,
125 uint64_t offset,
126 size_t size,
127 char **ret,
128 size_t *ret_size) {
129
130 _cleanup_free_ char *buf = NULL;
131 EFI_STATUS err;
132
133 assert(handle);
134 assert(ret);
135
136 if (size == 0) {
137 _cleanup_free_ EFI_FILE_INFO *info = NULL;
138
139 err = get_file_info(handle, &info, NULL);
140 if (err != EFI_SUCCESS)
141 return err;
142
143 if (info->FileSize > SIZE_MAX) /* overflow check */
144 return EFI_BAD_BUFFER_SIZE;
145
146 size = info->FileSize;
147 }
148
149 if (size > FILE_READ_MAX) /* make sure we don't read unbounded data into RAM */
150 return EFI_BAD_BUFFER_SIZE;
151
152 if (offset > 0) {
153 err = handle->SetPosition(handle, offset);
154 if (err != EFI_SUCCESS)
155 return err;
156 }
157
158 /* Allocate some extra bytes to guarantee the result is NUL-terminated for char and char16_t strings. */
159 size_t extra = size % sizeof(char16_t) + sizeof(char16_t);
160
161 buf = xmalloc(size + extra);
162 err = chunked_read(handle, &size, buf);
163 if (err != EFI_SUCCESS)
164 return err;
165
166 /* Note that chunked_read() changes size to reflect the actual bytes read. */
167 memzero(buf + size, extra);
168
169 *ret = TAKE_PTR(buf);
170 if (ret_size)
171 *ret_size = size;
172
173 return err;
174 }
175
176 EFI_STATUS file_read(
177 EFI_FILE *dir,
178 const char16_t *name,
179 uint64_t offset,
180 size_t size,
181 char **ret,
182 size_t *ret_size) {
183
184 EFI_STATUS err;
185
186 assert(dir);
187 assert(name);
188 assert(ret);
189
190 _cleanup_file_close_ EFI_FILE *handle = NULL;
191 err = dir->Open(dir, &handle, (char16_t*) name, EFI_FILE_MODE_READ, 0ULL);
192 if (err != EFI_SUCCESS)
193 return err;
194
195 return file_handle_read(handle, offset, size, ret, ret_size);
196 }
197
198 EFI_STATUS load_file_from_simple_filesystem(const EFI_DEVICE_PATH *device_path, char **file_buffer, size_t *file_size) {
199 EFI_STATUS err;
200 EFI_HANDLE device_handle;
201 EFI_DEVICE_PATH *file_dp = (EFI_DEVICE_PATH *) device_path;
202
203 assert(device_path);
204 assert(file_buffer);
205 assert(file_size);
206
207 err = BS->LocateDevicePath(MAKE_GUID_PTR(EFI_SIMPLE_FILE_SYSTEM_PROTOCOL), &file_dp, &device_handle);
208 if (err != EFI_SUCCESS)
209 return err;
210
211 _cleanup_file_close_ EFI_FILE *root = NULL;
212 err = open_volume(device_handle, &root);
213 if (err != EFI_SUCCESS)
214 return err;
215
216 _cleanup_free_ char16_t *dp_str = NULL;
217 err = device_path_to_str(file_dp, &dp_str);
218 if (err != EFI_SUCCESS)
219 return err;
220
221 return file_read(root, dp_str, 0, 0, file_buffer, file_size);
222 }
223
224 void set_attribute_safe(size_t attr) {
225 /* Various UEFI implementations suppress color changes from a color to the same color. Often, we want
226 * to force out the color change though, hence change the color here once, and then back. We simply
227 * mark the color as bright for a moment, and then revert that. */
228
229 attr ^= 0x08;
230 ST->ConOut->SetAttribute(ST->ConOut, attr);
231 attr ^= 0x08;
232 ST->ConOut->SetAttribute(ST->ConOut, attr);
233 }
234
235 void print_at(size_t x, size_t y, size_t attr, const char16_t *str) {
236 assert(str);
237 ST->ConOut->SetCursorPosition(ST->ConOut, x, y);
238 set_attribute_safe(attr);
239 ST->ConOut->OutputString(ST->ConOut, (char16_t *) str);
240 }
241
242 void clear_screen(size_t attr) {
243 log_wait();
244 set_attribute_safe(attr);
245 ST->ConOut->ClearScreen(ST->ConOut);
246 }
247
248 void sort_pointer_array(
249 void **array,
250 size_t n_members,
251 compare_pointer_func_t compare) {
252
253 assert(array || n_members == 0);
254 assert(compare);
255
256 if (n_members <= 1)
257 return;
258
259 for (size_t i = 1; i < n_members; i++) {
260 size_t k;
261 void *entry = array[i];
262
263 for (k = i; k > 0; k--) {
264 if (compare(array[k - 1], entry) <= 0)
265 break;
266
267 array[k] = array[k - 1];
268 }
269
270 array[k] = entry;
271 }
272 }
273
274 EFI_STATUS get_file_info(EFI_FILE *handle, EFI_FILE_INFO **ret, size_t *ret_size) {
275 size_t size = EFI_FILE_INFO_MIN_SIZE;
276 _cleanup_free_ EFI_FILE_INFO *fi = NULL;
277 EFI_STATUS err;
278
279 assert(handle);
280 assert(ret);
281
282 fi = xmalloc(size);
283 err = handle->GetInfo(handle, MAKE_GUID_PTR(EFI_FILE_INFO), &size, fi);
284 if (err == EFI_BUFFER_TOO_SMALL) {
285 free(fi);
286 fi = xmalloc(size); /* GetInfo tells us the required size, let's use that now */
287 err = handle->GetInfo(handle, MAKE_GUID_PTR(EFI_FILE_INFO), &size, fi);
288 }
289
290 if (err != EFI_SUCCESS)
291 return err;
292
293 *ret = TAKE_PTR(fi);
294
295 if (ret_size)
296 *ret_size = size;
297
298 return EFI_SUCCESS;
299 }
300
301 EFI_STATUS readdir(
302 EFI_FILE *handle,
303 EFI_FILE_INFO **buffer,
304 size_t *buffer_size) {
305
306 EFI_STATUS err;
307 size_t sz;
308
309 assert(handle);
310 assert(buffer);
311 assert(buffer_size);
312
313 /* buffer/buffer_size are both in and output parameters. Should be zero-initialized initially, and
314 * the specified buffer needs to be freed by caller, after final use. */
315
316 if (!*buffer) {
317 sz = EFI_FILE_INFO_MIN_SIZE;
318 *buffer = xmalloc(sz);
319 *buffer_size = sz;
320 } else
321 sz = *buffer_size;
322
323 err = handle->Read(handle, &sz, *buffer);
324 if (err == EFI_BUFFER_TOO_SMALL) {
325 free(*buffer);
326 *buffer = xmalloc(sz);
327 *buffer_size = sz;
328 err = handle->Read(handle, &sz, *buffer);
329 }
330 if (err != EFI_SUCCESS)
331 return err;
332
333 if (sz == 0) {
334 /* End of directory */
335 *buffer = mfree(*buffer);
336 *buffer_size = 0;
337 }
338
339 return EFI_SUCCESS;
340 }
341
342 bool is_ascii(const char16_t *f) {
343 if (!f)
344 return false;
345
346 for (; *f != 0; f++)
347 if (*f > 127)
348 return false;
349
350 return true;
351 }
352
353 char16_t **strv_free(char16_t **l) {
354 if (!l)
355 return NULL;
356
357 for (char16_t **i = l; *i; i++)
358 free(*i);
359
360 return mfree(l);
361 }
362
363 EFI_STATUS open_directory(
364 EFI_FILE *root,
365 const char16_t *path,
366 EFI_FILE **ret) {
367
368 _cleanup_file_close_ EFI_FILE *dir = NULL;
369 _cleanup_free_ EFI_FILE_INFO *file_info = NULL;
370 EFI_STATUS err;
371
372 assert(root);
373 assert(ret);
374
375 /* Opens a file, and then verifies it is actually a directory */
376
377 err = root->Open(root, &dir, (char16_t *) path, EFI_FILE_MODE_READ, 0);
378 if (err != EFI_SUCCESS)
379 return err;
380
381 err = get_file_info(dir, &file_info, NULL);
382 if (err != EFI_SUCCESS)
383 return err;
384 if (!FLAGS_SET(file_info->Attribute, EFI_FILE_DIRECTORY))
385 return EFI_LOAD_ERROR;
386
387 *ret = TAKE_PTR(dir);
388 return EFI_SUCCESS;
389 }
390
391 __attribute__((noinline)) void notify_debugger(const char *identity, volatile bool wait) {
392 #ifdef EFI_DEBUG
393 printf("%s@%p %s\n", identity, __executable_start, GIT_VERSION);
394 if (wait)
395 printf("Waiting for debugger to attach...\n");
396
397 /* This is a poor programmer's breakpoint to wait until a debugger
398 * has attached to us. Just "set variable wait = 0" or "return" to continue. */
399 while (wait)
400 /* Prefer asm based stalling so that gdb has a source location to present. */
401 # if defined(__i386__) || defined(__x86_64__)
402 asm volatile("pause");
403 # elif defined(__aarch64__)
404 asm volatile("wfi");
405 # else
406 BS->Stall(5000);
407 # endif
408 #endif
409 }
410
411 #if defined(__i386__) || defined(__x86_64__)
412 static uint8_t inb(uint16_t port) {
413 uint8_t value;
414 asm volatile("inb %1, %0" : "=a"(value) : "Nd"(port));
415 return value;
416 }
417
418 static void outb(uint16_t port, uint8_t value) {
419 asm volatile("outb %0, %1" : : "a"(value), "Nd"(port));
420 }
421
422 void beep(unsigned beep_count) {
423 enum {
424 PITCH = 500,
425 BEEP_DURATION_USEC = 100 * 1000,
426 WAIT_DURATION_USEC = 400 * 1000,
427
428 PIT_FREQUENCY = 0x1234dd,
429 SPEAKER_CONTROL_PORT = 0x61,
430 SPEAKER_ON_MASK = 0x03,
431 TIMER_PORT_MAGIC = 0xB6,
432 TIMER_CONTROL_PORT = 0x43,
433 TIMER_CONTROL2_PORT = 0x42,
434 };
435
436 /* Set frequency. */
437 uint32_t counter = PIT_FREQUENCY / PITCH;
438 outb(TIMER_CONTROL_PORT, TIMER_PORT_MAGIC);
439 outb(TIMER_CONTROL2_PORT, counter & 0xFF);
440 outb(TIMER_CONTROL2_PORT, (counter >> 8) & 0xFF);
441
442 uint8_t value = inb(SPEAKER_CONTROL_PORT);
443
444 while (beep_count > 0) {
445 /* Turn speaker on. */
446 value |= SPEAKER_ON_MASK;
447 outb(SPEAKER_CONTROL_PORT, value);
448
449 BS->Stall(BEEP_DURATION_USEC);
450
451 /* Turn speaker off. */
452 value &= ~SPEAKER_ON_MASK;
453 outb(SPEAKER_CONTROL_PORT, value);
454
455 beep_count--;
456 if (beep_count > 0)
457 BS->Stall(WAIT_DURATION_USEC);
458 }
459 }
460 #endif
461
462 EFI_STATUS open_volume(EFI_HANDLE device, EFI_FILE **ret_file) {
463 EFI_STATUS err;
464 EFI_FILE *file;
465 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *volume;
466
467 assert(ret_file);
468
469 err = BS->HandleProtocol(device, MAKE_GUID_PTR(EFI_SIMPLE_FILE_SYSTEM_PROTOCOL), (void **) &volume);
470 if (err != EFI_SUCCESS)
471 return err;
472
473 err = volume->OpenVolume(volume, &file);
474 if (err != EFI_SUCCESS)
475 return err;
476
477 *ret_file = file;
478 return EFI_SUCCESS;
479 }
480
481 void *find_configuration_table(const EFI_GUID *guid) {
482 for (size_t i = 0; i < ST->NumberOfTableEntries; i++)
483 if (efi_guid_equal(&ST->ConfigurationTable[i].VendorGuid, guid))
484 return ST->ConfigurationTable[i].VendorTable;
485
486 return NULL;
487 }
488
489 static void remove_boot_count(char16_t *path) {
490 char16_t *prefix_end;
491 const char16_t *tail;
492 uint64_t ignored;
493
494 assert(path);
495
496 prefix_end = strchr16(path, '+');
497 if (!prefix_end)
498 return;
499
500 tail = prefix_end + 1;
501
502 if (!parse_number16(tail, &ignored, &tail))
503 return;
504
505 if (*tail == '-') {
506 ++tail;
507 if (!parse_number16(tail, &ignored, &tail))
508 return;
509 }
510
511 if (!IN_SET(*tail, '\0', '.'))
512 return;
513
514 strcpy16(prefix_end, tail);
515 }
516
517 char16_t *get_extra_dir(const EFI_DEVICE_PATH *file_path) {
518 if (!file_path)
519 return NULL;
520
521 /* A device path is allowed to have more than one file path node. If that is the case they are
522 * supposed to be concatenated. Unfortunately, the device path to text protocol simply converts the
523 * nodes individually and then combines those with the usual '/' for device path nodes. But this does
524 * not create a legal EFI file path that the file protocol can use. */
525
526 /* Make sure we really only got file paths. */
527 for (const EFI_DEVICE_PATH *node = file_path; !device_path_is_end(node);
528 node = device_path_next_node(node))
529 if (node->Type != MEDIA_DEVICE_PATH || node->SubType != MEDIA_FILEPATH_DP)
530 return NULL;
531
532 _cleanup_free_ char16_t *file_path_str = NULL;
533 if (device_path_to_str(file_path, &file_path_str) != EFI_SUCCESS)
534 return NULL;
535
536 convert_efi_path(file_path_str);
537 remove_boot_count(file_path_str);
538 return xasprintf("%ls.extra.d", file_path_str);
539 }
540
541 void *xmalloc(size_t size) {
542 void *p = NULL;
543 assert_se(BS->AllocatePool(EfiLoaderData, size, &p) == EFI_SUCCESS);
544 return p;
545 }
546
547 Pages xmalloc_aligned_pages(
548 EFI_ALLOCATE_TYPE type,
549 EFI_MEMORY_TYPE memory_type,
550 size_t n_pages,
551 size_t alignment,
552 EFI_PHYSICAL_ADDRESS addr) {
553
554 EFI_PHYSICAL_ADDRESS aligned = addr;
555
556 /* Allow to pass block_io->Media->IoAlign to this function directly.
557 * alignment <= 1 means no alignment is required, in that case just
558 * allocate pages directly.
559 */
560 if (alignment <= 1)
561 alignment = EFI_PAGE_SIZE;
562
563 assert(ISPOWEROF2(alignment));
564
565 if (alignment <= EFI_PAGE_SIZE) {
566 assert_se(BS->AllocatePages(type, memory_type, n_pages, &aligned) == EFI_SUCCESS);
567 return (Pages) {
568 .addr = aligned,
569 .n_pages = n_pages,
570 };
571 }
572
573 size_t total_pages = n_pages + EFI_SIZE_TO_PAGES(alignment);
574 assert_se(BS->AllocatePages(type, memory_type, total_pages, &addr) == EFI_SUCCESS);
575
576 aligned = ALIGN_TO(addr, alignment);
577 size_t unaligned_pages = EFI_SIZE_TO_PAGES(aligned - addr);
578 if (unaligned_pages > 0)
579 assert_se(BS->FreePages(addr, unaligned_pages) == EFI_SUCCESS);
580
581 addr = aligned + n_pages * EFI_PAGE_SIZE;
582 unaligned_pages = total_pages - n_pages - unaligned_pages;
583 if (unaligned_pages > 0)
584 assert_se(BS->FreePages(addr, unaligned_pages) == EFI_SUCCESS);
585
586 return (Pages) {
587 .addr = aligned,
588 .n_pages = n_pages,
589 };
590 }
591
592 bool free_and_xstrdup16(char16_t **p, const char16_t *s) {
593 char16_t *t;
594
595 assert(p);
596
597 /* Replaces a string pointer with a strdup()ed new string,
598 * possibly freeing the old one. */
599
600 if (streq_ptr(*p, s))
601 return false;
602
603 if (s)
604 t = xstrdup16(s);
605 else
606 t = NULL;
607
608 free(*p);
609 *p = t;
610 return true;
611 }
612
613 char16_t *url_replace_last_component(const char16_t *url, const char16_t *filename) {
614 assert(url);
615 assert(filename);
616
617 /* Find colon separating protocol and hostname */
618 const char16_t *d = strchr16(url, ':');
619 if (!d || url == d)
620 return NULL;
621 d++;
622
623 /* Skip slashes after colon */
624 d += strspn(d, u"/");
625
626 /* Skip everything till next slash or end (i.e. the hostname) */
627 size_t n = strcspn(d, u"/?#");
628 if (n == 0)
629 return NULL;
630
631 d += n;
632
633 const char16_t *e = d + strcspn(d, u"?#"); /* Cut off "Query" and "Fragment" */
634
635 while (e > d && e[-1] == '/') /* Eat trailing slashes */
636 e--;
637
638 const char16_t *p = e;
639 while (p > d && p[-1] != '/') /* Find component before that */
640 p--;
641
642 if (e <= p)
643 return NULL;
644
645 _cleanup_free_ char16_t *chopped = xstrndup16(url, p - url);
646
647 return xasprintf("%ls/%ls", chopped, filename);
648 }