1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include "alloc-util.h"
8 #include "dirent-util.h"
9 #include "efi-loader.h"
13 #include "parse-util.h"
14 #include "sort-util.h"
15 #include "stat-util.h"
16 #include "stdio-util.h"
17 #include "string-util.h"
23 #define LOAD_OPTION_ACTIVE 0x00000001
24 #define MEDIA_DEVICE_PATH 0x04
25 #define MEDIA_HARDDRIVE_DP 0x01
26 #define MEDIA_FILEPATH_DP 0x04
27 #define SIGNATURE_TYPE_GUID 0x02
28 #define MBR_TYPE_EFI_PARTITION_TABLE_HEADER 0x02
29 #define END_DEVICE_PATH_TYPE 0x7f
30 #define END_ENTIRE_DEVICE_PATH_SUBTYPE 0xff
31 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001
33 #define boot_option__contents \
40 struct boot_option boot_option__contents
;
41 struct boot_option__packed boot_option__contents _packed_
;
42 assert_cc(offsetof(struct boot_option
, title
) == offsetof(struct boot_option__packed
, title
));
43 /* sizeof(struct boot_option) != sizeof(struct boot_option__packed), so
44 * the *size* of the structure should not be used anywhere below. */
52 uint8_t signature_type
;
55 #define device_path__contents \
62 struct drive_path drive; \
66 struct device_path device_path__contents
;
67 struct device_path__packed device_path__contents _packed_
;
68 assert_cc(sizeof(struct device_path
) == sizeof(struct device_path__packed
));
70 int efi_reboot_to_firmware_supported(void) {
71 _cleanup_free_
void *v
= NULL
;
72 static int cache
= -1;
85 r
= efi_get_variable(EFI_GLOBAL_VARIABLE(OsIndicationsSupported
), NULL
, &v
, &s
);
87 goto not_supported
; /* variable doesn't exist? it's not supported then */
90 if (s
!= sizeof(uint64_t))
94 if (!(b
& EFI_OS_INDICATIONS_BOOT_TO_FW_UI
))
95 goto not_supported
; /* bit unset? it's not supported then */
105 static int get_os_indications(uint64_t *ret
) {
106 static struct stat cache_stat
= {};
107 _cleanup_free_
void *v
= NULL
;
108 static uint64_t cache
;
109 struct stat new_stat
;
115 /* Let's verify general support first */
116 r
= efi_reboot_to_firmware_supported();
120 /* stat() the EFI variable, to see if the mtime changed. If it did we need to cache again. */
121 if (stat(EFIVAR_PATH(EFI_GLOBAL_VARIABLE(OsIndications
)), &new_stat
) < 0) {
125 /* Doesn't exist? Then we can exit early (also see below) */
129 } else if (stat_inode_unmodified(&new_stat
, &cache_stat
)) {
130 /* inode didn't change, we can return the cached value */
135 r
= efi_get_variable(EFI_GLOBAL_VARIABLE(OsIndications
), NULL
, &v
, &s
);
137 /* Some firmware implementations that do support OsIndications and report that with
138 * OsIndicationsSupported will remove the OsIndications variable when it is unset. Let's
139 * pretend it's 0 then, to hide this implementation detail. Note that this call will return
140 * -ENOENT then only if the support for OsIndications is missing entirely, as determined by
141 * efi_reboot_to_firmware_supported() above. */
147 if (s
!= sizeof(uint64_t))
150 cache_stat
= new_stat
;
151 *ret
= cache
= *(uint64_t *)v
;
155 int efi_get_reboot_to_firmware(void) {
159 r
= get_os_indications(&b
);
163 return !!(b
& EFI_OS_INDICATIONS_BOOT_TO_FW_UI
);
166 int efi_set_reboot_to_firmware(bool value
) {
170 r
= get_os_indications(&b
);
174 b_new
= UPDATE_FLAG(b
, EFI_OS_INDICATIONS_BOOT_TO_FW_UI
, value
);
176 /* Avoid writing to efi vars store if we can due to firmware bugs. */
178 return efi_set_variable(EFI_GLOBAL_VARIABLE(OsIndications
), &b_new
, sizeof(uint64_t));
183 static ssize_t
utf16_size(const uint16_t *s
, size_t buf_len_bytes
) {
186 /* Returns the size of the string in bytes without the terminating two zero bytes */
188 if (buf_len_bytes
% sizeof(uint16_t) != 0)
191 while (l
< buf_len_bytes
/ sizeof(uint16_t)) {
193 return (l
+ 1) * sizeof(uint16_t);
197 return -EINVAL
; /* The terminator was not found */
207 static void efi_guid_to_id128(const void *guid
, sd_id128_t
*id128
) {
210 const struct guid
*uuid
= guid
;
212 memcpy(&u1
, &uuid
->u1
, sizeof(uint32_t));
213 id128
->bytes
[0] = (u1
>> 24) & 0xff;
214 id128
->bytes
[1] = (u1
>> 16) & 0xff;
215 id128
->bytes
[2] = (u1
>> 8) & 0xff;
216 id128
->bytes
[3] = u1
& 0xff;
217 memcpy(&u2
, &uuid
->u2
, sizeof(uint16_t));
218 id128
->bytes
[4] = (u2
>> 8) & 0xff;
219 id128
->bytes
[5] = u2
& 0xff;
220 memcpy(&u3
, &uuid
->u3
, sizeof(uint16_t));
221 id128
->bytes
[6] = (u3
>> 8) & 0xff;
222 id128
->bytes
[7] = u3
& 0xff;
223 memcpy(&id128
->bytes
[8], uuid
->u4
, sizeof(uuid
->u4
));
226 int efi_get_boot_option(
229 sd_id128_t
*part_uuid
,
233 char variable
[STRLEN(EFI_GLOBAL_VARIABLE_STR("Boot")) + 4 + 1];
234 _cleanup_free_
uint8_t *buf
= NULL
;
236 struct boot_option
*header
;
238 _cleanup_free_
char *s
= NULL
, *p
= NULL
;
239 sd_id128_t p_uuid
= SD_ID128_NULL
;
245 xsprintf(variable
, EFI_GLOBAL_VARIABLE_STR("Boot%04X"), id
);
246 r
= efi_get_variable(variable
, NULL
, (void **)&buf
, &l
);
249 if (l
< offsetof(struct boot_option
, title
))
252 header
= (struct boot_option
*)buf
;
253 title_size
= utf16_size(header
->title
, l
- offsetof(struct boot_option
, title
));
258 s
= utf16_to_utf8(header
->title
, title_size
);
263 if (header
->path_len
> 0) {
267 doff
= offsetof(struct boot_option
, title
) + title_size
;
269 if (header
->path_len
> l
- doff
)
273 while (dnext
< header
->path_len
) {
274 struct device_path
*dpath
;
276 dpath
= (struct device_path
*)(dbuf
+ dnext
);
277 if (dpath
->length
< 4)
280 /* Type 0x7F – End of Hardware Device Path, Sub-Type 0xFF – End Entire Device Path */
281 if (dpath
->type
== END_DEVICE_PATH_TYPE
&& dpath
->sub_type
== END_ENTIRE_DEVICE_PATH_SUBTYPE
)
284 dnext
+= dpath
->length
;
286 /* Type 0x04 – Media Device Path */
287 if (dpath
->type
!= MEDIA_DEVICE_PATH
)
290 /* Sub-Type 1 – Hard Drive */
291 if (dpath
->sub_type
== MEDIA_HARDDRIVE_DP
) {
292 /* 0x02 – GUID Partition Table */
293 if (dpath
->drive
.mbr_type
!= MBR_TYPE_EFI_PARTITION_TABLE_HEADER
)
296 /* 0x02 – GUID signature */
297 if (dpath
->drive
.signature_type
!= SIGNATURE_TYPE_GUID
)
301 efi_guid_to_id128(dpath
->drive
.signature
, &p_uuid
);
305 /* Sub-Type 4 – File Path */
306 if (dpath
->sub_type
== MEDIA_FILEPATH_DP
&& !p
&& path
) {
307 p
= utf16_to_utf8(dpath
->path
, dpath
->length
-4);
311 efi_tilt_backslashes(p
);
318 *title
= TAKE_PTR(s
);
324 *active
= header
->attr
& LOAD_OPTION_ACTIVE
;
329 static void to_utf16(uint16_t *dest
, const char *src
) {
332 for (i
= 0; src
[i
] != '\0'; i
++)
337 static void id128_to_efi_guid(sd_id128_t id
, void *guid
) {
339 .u1
= id
.bytes
[0] << 24 | id
.bytes
[1] << 16 | id
.bytes
[2] << 8 | id
.bytes
[3],
340 .u2
= id
.bytes
[4] << 8 | id
.bytes
[5],
341 .u3
= id
.bytes
[6] << 8 | id
.bytes
[7],
343 memcpy(uuid
.u4
, id
.bytes
+8, sizeof(uuid
.u4
));
344 memcpy(guid
, &uuid
, sizeof(uuid
));
347 static uint16_t *tilt_slashes(uint16_t *s
) {
348 for (uint16_t *p
= s
; *p
; p
++)
355 int efi_add_boot_option(
361 sd_id128_t part_uuid
,
364 size_t size
, title_len
, path_len
;
365 _cleanup_free_
char *buf
= NULL
;
366 struct boot_option
*option
;
367 struct device_path
*devicep
;
368 char variable
[STRLEN(EFI_GLOBAL_VARIABLE_STR("Boot")) + 4 + 1];
373 title_len
= (strlen(title
)+1) * 2;
374 path_len
= (strlen(path
)+1) * 2;
376 buf
= malloc0(offsetof(struct boot_option
, title
) + title_len
+
377 sizeof(struct drive_path
) +
378 sizeof(struct device_path
) + path_len
);
383 option
= (struct boot_option
*)buf
;
384 option
->attr
= LOAD_OPTION_ACTIVE
;
385 option
->path_len
= offsetof(struct device_path
, drive
) + sizeof(struct drive_path
) +
386 offsetof(struct device_path
, path
) + path_len
+
387 offsetof(struct device_path
, path
);
388 to_utf16(option
->title
, title
);
389 size
= offsetof(struct boot_option
, title
) + title_len
;
392 devicep
= (struct device_path
*)(buf
+ size
);
393 devicep
->type
= MEDIA_DEVICE_PATH
;
394 devicep
->sub_type
= MEDIA_HARDDRIVE_DP
;
395 devicep
->length
= offsetof(struct device_path
, drive
) + sizeof(struct drive_path
);
396 memcpy(&devicep
->drive
.part_nr
, &part
, sizeof(uint32_t));
397 memcpy(&devicep
->drive
.part_start
, &pstart
, sizeof(uint64_t));
398 memcpy(&devicep
->drive
.part_size
, &psize
, sizeof(uint64_t));
399 id128_to_efi_guid(part_uuid
, devicep
->drive
.signature
);
400 devicep
->drive
.mbr_type
= MBR_TYPE_EFI_PARTITION_TABLE_HEADER
;
401 devicep
->drive
.signature_type
= SIGNATURE_TYPE_GUID
;
402 size
+= devicep
->length
;
405 devicep
= (struct device_path
*)(buf
+ size
);
406 devicep
->type
= MEDIA_DEVICE_PATH
;
407 devicep
->sub_type
= MEDIA_FILEPATH_DP
;
408 devicep
->length
= offsetof(struct device_path
, path
) + path_len
;
409 to_utf16(devicep
->path
, path
);
410 tilt_slashes(devicep
->path
);
411 size
+= devicep
->length
;
414 devicep
= (struct device_path
*)(buf
+ size
);
415 devicep
->type
= END_DEVICE_PATH_TYPE
;
416 devicep
->sub_type
= END_ENTIRE_DEVICE_PATH_SUBTYPE
;
417 devicep
->length
= offsetof(struct device_path
, path
);
418 size
+= devicep
->length
;
420 xsprintf(variable
, EFI_GLOBAL_VARIABLE_STR("Boot%04X"), id
);
421 return efi_set_variable(variable
, buf
, size
);
424 int efi_remove_boot_option(uint16_t id
) {
425 char variable
[STRLEN(EFI_GLOBAL_VARIABLE_STR("Boot")) + 4 + 1];
430 xsprintf(variable
, EFI_GLOBAL_VARIABLE_STR("Boot%04X"), id
);
431 return efi_set_variable(variable
, NULL
, 0);
434 int efi_get_boot_order(uint16_t **order
) {
435 _cleanup_free_
void *buf
= NULL
;
442 r
= efi_get_variable(EFI_GLOBAL_VARIABLE(BootOrder
), NULL
, &buf
, &l
);
449 if (l
% sizeof(uint16_t) > 0 ||
450 l
/ sizeof(uint16_t) > INT_MAX
)
453 *order
= TAKE_PTR(buf
);
454 return (int) (l
/ sizeof(uint16_t));
457 int efi_set_boot_order(uint16_t *order
, size_t n
) {
462 return efi_set_variable(EFI_GLOBAL_VARIABLE(BootOrder
), order
, n
* sizeof(uint16_t));
465 static int boot_id_hex(const char s
[static 4]) {
470 for (int i
= 0; i
< 4; i
++)
471 if (s
[i
] >= '0' && s
[i
] <= '9')
472 id
|= (s
[i
] - '0') << (3 - i
) * 4;
473 else if (s
[i
] >= 'A' && s
[i
] <= 'F')
474 id
|= (s
[i
] - 'A' + 10) << (3 - i
) * 4;
481 static int cmp_uint16(const uint16_t *a
, const uint16_t *b
) {
485 int efi_get_boot_options(uint16_t **options
) {
486 _cleanup_closedir_
DIR *dir
= NULL
;
487 _cleanup_free_
uint16_t *list
= NULL
;
496 dir
= opendir(EFIVAR_PATH("."));
500 FOREACH_DIRENT(de
, dir
, return -errno
) {
503 if (strncmp(de
->d_name
, "Boot", 4) != 0)
506 if (strlen(de
->d_name
) != 45)
509 if (strcmp(de
->d_name
+ 8, EFI_GLOBAL_VARIABLE_STR("")) != 0) /* generate variable suffix using macro */
512 id
= boot_id_hex(de
->d_name
+ 4);
516 if (!GREEDY_REALLOC(list
, count
+ 1))
522 typesafe_qsort(list
, count
, cmp_uint16
);
524 *options
= TAKE_PTR(list
);
529 static int read_usec(const char *variable
, usec_t
*u
) {
530 _cleanup_free_
char *j
= NULL
;
537 r
= efi_get_variable_string(variable
, &j
);
541 r
= safe_atou64(j
, &x
);
549 int efi_loader_get_boot_usec(usec_t
*firmware
, usec_t
*loader
) {
559 r
= read_usec(EFI_LOADER_VARIABLE(LoaderTimeInitUSec
), &x
);
561 return log_debug_errno(r
, "Failed to read LoaderTimeInitUSec: %m");
563 r
= read_usec(EFI_LOADER_VARIABLE(LoaderTimeExecUSec
), &y
);
565 return log_debug_errno(r
, "Failed to read LoaderTimeExecUSec: %m");
567 if (y
== 0 || y
< x
|| y
- x
> USEC_PER_HOUR
)
568 return log_debug_errno(SYNTHETIC_ERRNO(EIO
),
569 "Bad LoaderTimeInitUSec=%"PRIu64
", LoaderTimeExecUSec=%" PRIu64
"; refusing.",
578 int efi_loader_get_device_part_uuid(sd_id128_t
*u
) {
579 _cleanup_free_
char *p
= NULL
;
585 r
= efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderDevicePartUUID
), &p
);
589 if (sscanf(p
, SD_ID128_UUID_FORMAT_STR
,
590 &parsed
[0], &parsed
[1], &parsed
[2], &parsed
[3],
591 &parsed
[4], &parsed
[5], &parsed
[6], &parsed
[7],
592 &parsed
[8], &parsed
[9], &parsed
[10], &parsed
[11],
593 &parsed
[12], &parsed
[13], &parsed
[14], &parsed
[15]) != 16)
597 for (unsigned i
= 0; i
< ELEMENTSOF(parsed
); i
++)
598 u
->bytes
[i
] = parsed
[i
];
603 int efi_loader_get_entries(char ***ret
) {
604 _cleanup_free_ char16_t
*entries
= NULL
;
605 _cleanup_strv_free_
char **l
= NULL
;
614 r
= efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntries
), NULL
, (void**) &entries
, &size
);
618 /* The variable contains a series of individually NUL terminated UTF-16 strings. */
620 for (size_t i
= 0, start
= 0;; i
++) {
621 _cleanup_free_
char *decoded
= NULL
;
624 /* Is this the end of the variable's data? */
625 end
= i
* sizeof(char16_t
) >= size
;
627 /* Are we in the middle of a string? (i.e. not at the end of the variable, nor at a NUL terminator?) If
628 * so, let's go to the next entry. */
629 if (!end
&& entries
[i
] != 0)
632 /* We reached the end of a string, let's decode it into UTF-8 */
633 decoded
= utf16_to_utf8(entries
+ start
, (i
- start
) * sizeof(char16_t
));
637 if (efi_loader_entry_name_valid(decoded
)) {
638 r
= strv_consume(&l
, TAKE_PTR(decoded
));
642 log_debug("Ignoring invalid loader entry '%s'.", decoded
);
644 /* We reached the end of the variable */
648 /* Continue after the NUL byte */
656 int efi_loader_get_features(uint64_t *ret
) {
657 _cleanup_free_
void *v
= NULL
;
661 if (!is_efi_boot()) {
666 r
= efi_get_variable(EFI_LOADER_VARIABLE(LoaderFeatures
), NULL
, &v
, &s
);
668 _cleanup_free_
char *info
= NULL
;
670 /* The new (v240+) LoaderFeatures variable is not supported, let's see if it's systemd-boot at all */
671 r
= efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderInfo
), &info
);
676 /* Variable not set, definitely means not systemd-boot */
678 } else if (first_word(info
, "systemd-boot")) {
680 /* An older systemd-boot version. Let's hardcode the feature set, since it was pretty
681 * static in all its versions. */
683 *ret
= EFI_LOADER_FEATURE_CONFIG_TIMEOUT
|
684 EFI_LOADER_FEATURE_ENTRY_DEFAULT
|
685 EFI_LOADER_FEATURE_ENTRY_ONESHOT
;
690 /* No features supported */
697 if (s
!= sizeof(uint64_t))
698 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
699 "LoaderFeatures EFI variable doesn't have the right size.");
701 memcpy(ret
, v
, sizeof(uint64_t));
705 int efi_loader_get_config_timeout_one_shot(usec_t
*ret
) {
706 _cleanup_free_
char *v
= NULL
;
707 static struct stat cache_stat
= {};
708 struct stat new_stat
;
715 /* stat() the EFI variable, to see if the mtime changed. If it did, we need to cache again. */
716 if (stat(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot
)), &new_stat
) < 0)
719 if (stat_inode_unmodified(&new_stat
, &cache_stat
)) {
724 r
= efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot
), &v
);
728 r
= safe_atou64(v
, &sec
);
731 if (sec
> USEC_INFINITY
/ USEC_PER_SEC
)
734 cache_stat
= new_stat
;
735 *ret
= cache
= sec
* USEC_PER_SEC
; /* return in µs */
739 int efi_loader_update_entry_one_shot_cache(char **cache
, struct stat
*cache_stat
) {
740 _cleanup_free_
char *v
= NULL
;
741 struct stat new_stat
;
747 /* stat() the EFI variable, to see if the mtime changed. If it did we need to cache again. */
748 if (stat(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderEntryOneShot
)), &new_stat
) < 0)
751 if (stat_inode_unmodified(&new_stat
, cache_stat
))
754 r
= efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderEntryOneShot
), &v
);
758 if (!efi_loader_entry_name_valid(v
))
761 *cache_stat
= new_stat
;
762 free_and_replace(*cache
, v
);
767 bool efi_has_tpm2(void) {
768 static int cache
= -1;
770 /* Returns whether the system has a TPM2 chip which is known to the EFI firmware. */
774 /* First, check if we are on an EFI boot at all. */
778 /* Then, check if the ACPI table "TPM2" exists, which is the TPM2 event log table, see:
779 * https://trustedcomputinggroup.org/wp-content/uploads/TCG_ACPIGeneralSpecification_v1.20_r8.pdf
780 * This table exists whenever the firmware is hooked up to TPM2. */
781 cache
= access("/sys/firmware/acpi/tables/TPM2", F_OK
) >= 0;
782 if (!cache
&& errno
!= ENOENT
)
783 log_debug_errno(errno
, "Unable to test whether /sys/firmware/acpi/tables/TPM2 exists, assuming it doesn't: %m");
792 bool efi_loader_entry_name_valid(const char *s
) {
793 if (!filename_is_valid(s
)) /* Make sure entry names fit in filenames */
796 return in_charset(s
, ALPHANUMERICAL
"+-_.");
799 char *efi_tilt_backslashes(char *s
) {
800 for (char *p
= s
; *p
; p
++)