1 /* SPDX-License-Identifier: LGPL-2.1+ */
16 #include "alloc-util.h"
17 #include "chattr-util.h"
18 #include "dirent-util.h"
23 #include "parse-util.h"
24 #include "sort-util.h"
25 #include "stdio-util.h"
27 #include "time-util.h"
33 #define LOAD_OPTION_ACTIVE 0x00000001
34 #define MEDIA_DEVICE_PATH 0x04
35 #define MEDIA_HARDDRIVE_DP 0x01
36 #define MEDIA_FILEPATH_DP 0x04
37 #define SIGNATURE_TYPE_GUID 0x02
38 #define MBR_TYPE_EFI_PARTITION_TABLE_HEADER 0x02
39 #define END_DEVICE_PATH_TYPE 0x7f
40 #define END_ENTIRE_DEVICE_PATH_SUBTYPE 0xff
41 #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x0000000000000001
43 #define boot_option__contents { \
49 struct boot_option boot_option__contents
;
50 struct boot_option__packed boot_option__contents _packed_
;
51 assert_cc(offsetof(struct boot_option
, title
) == offsetof(struct boot_option__packed
, title
));
52 /* sizeof(struct boot_option) != sizeof(struct boot_option__packed), so
53 * the *size* of the structure should not be used anywhere below. */
61 uint8_t signature_type
;
64 #define device_path__contents { \
70 struct drive_path drive; \
74 struct device_path device_path__contents
;
75 struct device_path__packed device_path__contents _packed_
;
76 assert_cc(sizeof(struct device_path
) == sizeof(struct device_path__packed
));
78 bool is_efi_boot(void) {
79 if (detect_container() > 0)
82 return access("/sys/firmware/efi/", F_OK
) >= 0;
85 static int read_flag(const char *varname
) {
86 _cleanup_free_
void *v
= NULL
;
91 if (!is_efi_boot()) /* If this is not an EFI boot, assume the queried flags are zero */
94 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, varname
, NULL
, &v
, &s
);
105 bool is_efi_secure_boot(void) {
106 return read_flag("SecureBoot") > 0;
109 bool is_efi_secure_boot_setup_mode(void) {
110 return read_flag("SetupMode") > 0;
113 int efi_reboot_to_firmware_supported(void) {
114 _cleanup_free_
void *v
= NULL
;
122 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, "OsIndicationsSupported", NULL
, &v
, &s
);
123 if (r
== -ENOENT
) /* variable doesn't exist? it's not supported then */
127 if (s
!= sizeof(uint64_t))
131 if (!(b
& EFI_OS_INDICATIONS_BOOT_TO_FW_UI
))
132 return -EOPNOTSUPP
; /* bit unset? it's not supported then */
137 static int get_os_indications(uint64_t *os_indication
) {
138 _cleanup_free_
void *v
= NULL
;
142 /* Let's verify general support first */
143 r
= efi_reboot_to_firmware_supported();
147 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, "OsIndications", NULL
, &v
, &s
);
149 /* Some firmware implementations that do support OsIndications and report that with
150 * OsIndicationsSupported will remove the OsIndications variable when it is unset. Let's pretend it's 0
151 * then, to hide this implementation detail. Note that this call will return -ENOENT then only if the
152 * support for OsIndications is missing entirely, as determined by efi_reboot_to_firmware_supported()
158 else if (s
!= sizeof(uint64_t))
161 *os_indication
= *(uint64_t *)v
;
165 int efi_get_reboot_to_firmware(void) {
169 r
= get_os_indications(&b
);
173 return !!(b
& EFI_OS_INDICATIONS_BOOT_TO_FW_UI
);
176 int efi_set_reboot_to_firmware(bool value
) {
180 r
= get_os_indications(&b
);
185 b_new
= b
| EFI_OS_INDICATIONS_BOOT_TO_FW_UI
;
187 b_new
= b
& ~EFI_OS_INDICATIONS_BOOT_TO_FW_UI
;
189 /* Avoid writing to efi vars store if we can due to firmware bugs. */
191 return efi_set_variable(EFI_VENDOR_GLOBAL
, "OsIndications", &b_new
, sizeof(uint64_t));
196 int efi_get_variable(
203 _cleanup_close_
int fd
= -1;
204 _cleanup_free_
char *p
= NULL
;
208 _cleanup_free_
void *buf
= NULL
;
215 "/sys/firmware/efi/efivars/%s-%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
216 name
, SD_ID128_FORMAT_VAL(vendor
)) < 0)
219 fd
= open(p
, O_RDONLY
|O_NOCTTY
|O_CLOEXEC
);
223 if (fstat(fd
, &st
) < 0)
227 if (st
.st_size
> 4*1024*1024 + 4)
230 n
= read(fd
, &a
, sizeof(a
));
236 buf
= malloc(st
.st_size
- 4 + 2);
240 n
= read(fd
, buf
, (size_t) st
.st_size
- 4);
243 if (n
!= (ssize_t
) st
.st_size
- 4)
246 /* Always NUL terminate (2 bytes, to protect UTF-16) */
247 ((char*) buf
)[st
.st_size
- 4] = 0;
248 ((char*) buf
)[st
.st_size
- 4 + 1] = 0;
250 *value
= TAKE_PTR(buf
);
251 *size
= (size_t) st
.st_size
- 4;
259 int efi_get_variable_string(sd_id128_t vendor
, const char *name
, char **p
) {
260 _cleanup_free_
void *s
= NULL
;
265 r
= efi_get_variable(vendor
, name
, NULL
, &s
, &ss
);
269 x
= utf16_to_utf8(s
, ss
);
277 int efi_set_variable(
286 } _packed_
* _cleanup_free_ buf
= NULL
;
287 _cleanup_free_
char *p
= NULL
;
288 _cleanup_close_
int fd
= -1;
289 bool saved_flags_valid
= false;
290 unsigned saved_flags
;
294 assert(value
|| size
== 0);
297 "/sys/firmware/efi/efivars/%s-%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
298 name
, SD_ID128_FORMAT_VAL(vendor
)) < 0)
301 /* Newer efivarfs protects variables that are not in a whitelist with FS_IMMUTABLE_FL by default, to protect
302 * them for accidental removal and modification. We are not changing these variables accidentally however,
303 * hence let's unset the bit first. */
305 r
= chattr_path(p
, 0, FS_IMMUTABLE_FL
, &saved_flags
);
306 if (r
< 0 && r
!= -ENOENT
)
307 log_debug_errno(r
, "Failed to drop FS_IMMUTABLE_FL flag from '%s', ignoring: %m", p
);
309 saved_flags_valid
= r
>= 0;
320 fd
= open(p
, O_WRONLY
|O_CREAT
|O_NOCTTY
|O_CLOEXEC
, 0644);
326 buf
= malloc(sizeof(uint32_t) + size
);
332 buf
->attr
= EFI_VARIABLE_NON_VOLATILE
|EFI_VARIABLE_BOOTSERVICE_ACCESS
|EFI_VARIABLE_RUNTIME_ACCESS
;
333 memcpy(buf
->buf
, value
, size
);
335 r
= loop_write(fd
, buf
, sizeof(uint32_t) + size
, false);
342 if (saved_flags_valid
) {
345 /* Restore the original flags field, just in case */
347 q
= chattr_path(p
, saved_flags
, FS_IMMUTABLE_FL
, NULL
);
349 q
= chattr_fd(fd
, saved_flags
, FS_IMMUTABLE_FL
, NULL
);
351 log_debug_errno(q
, "Failed to restore FS_IMMUTABLE_FL on '%s', ignoring: %m", p
);
357 int efi_set_variable_string(sd_id128_t vendor
, const char *name
, const char *v
) {
358 _cleanup_free_ char16_t
*u16
= NULL
;
360 u16
= utf8_to_utf16(v
, strlen(v
));
364 return efi_set_variable(vendor
, name
, u16
, (char16_strlen(u16
) + 1) * sizeof(char16_t
));
367 static ssize_t
utf16_size(const uint16_t *s
, size_t buf_len_bytes
) {
370 /* Returns the size of the string in bytes without the terminating two zero bytes */
372 if (buf_len_bytes
% sizeof(uint16_t) != 0)
375 while (l
< buf_len_bytes
/ sizeof(uint16_t)) {
377 return (l
+ 1) * sizeof(uint16_t);
381 return -EINVAL
; /* The terminator was not found */
391 static void efi_guid_to_id128(const void *guid
, sd_id128_t
*id128
) {
394 const struct guid
*uuid
= guid
;
396 memcpy(&u1
, &uuid
->u1
, sizeof(uint32_t));
397 id128
->bytes
[0] = (u1
>> 24) & 0xff;
398 id128
->bytes
[1] = (u1
>> 16) & 0xff;
399 id128
->bytes
[2] = (u1
>> 8) & 0xff;
400 id128
->bytes
[3] = u1
& 0xff;
401 memcpy(&u2
, &uuid
->u2
, sizeof(uint16_t));
402 id128
->bytes
[4] = (u2
>> 8) & 0xff;
403 id128
->bytes
[5] = u2
& 0xff;
404 memcpy(&u3
, &uuid
->u3
, sizeof(uint16_t));
405 id128
->bytes
[6] = (u3
>> 8) & 0xff;
406 id128
->bytes
[7] = u3
& 0xff;
407 memcpy(&id128
->bytes
[8], uuid
->u4
, sizeof(uuid
->u4
));
410 int efi_get_boot_option(
413 sd_id128_t
*part_uuid
,
418 _cleanup_free_
uint8_t *buf
= NULL
;
420 struct boot_option
*header
;
422 _cleanup_free_
char *s
= NULL
, *p
= NULL
;
423 sd_id128_t p_uuid
= SD_ID128_NULL
;
429 xsprintf(boot_id
, "Boot%04X", id
);
430 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, boot_id
, NULL
, (void **)&buf
, &l
);
433 if (l
< offsetof(struct boot_option
, title
))
436 header
= (struct boot_option
*)buf
;
437 title_size
= utf16_size(header
->title
, l
- offsetof(struct boot_option
, title
));
442 s
= utf16_to_utf8(header
->title
, title_size
);
447 if (header
->path_len
> 0) {
451 doff
= offsetof(struct boot_option
, title
) + title_size
;
453 if (header
->path_len
> l
- doff
)
457 while (dnext
< header
->path_len
) {
458 struct device_path
*dpath
;
460 dpath
= (struct device_path
*)(dbuf
+ dnext
);
461 if (dpath
->length
< 4)
464 /* Type 0x7F – End of Hardware Device Path, Sub-Type 0xFF – End Entire Device Path */
465 if (dpath
->type
== END_DEVICE_PATH_TYPE
&& dpath
->sub_type
== END_ENTIRE_DEVICE_PATH_SUBTYPE
)
468 dnext
+= dpath
->length
;
470 /* Type 0x04 – Media Device Path */
471 if (dpath
->type
!= MEDIA_DEVICE_PATH
)
474 /* Sub-Type 1 – Hard Drive */
475 if (dpath
->sub_type
== MEDIA_HARDDRIVE_DP
) {
476 /* 0x02 – GUID Partition Table */
477 if (dpath
->drive
.mbr_type
!= MBR_TYPE_EFI_PARTITION_TABLE_HEADER
)
480 /* 0x02 – GUID signature */
481 if (dpath
->drive
.signature_type
!= SIGNATURE_TYPE_GUID
)
485 efi_guid_to_id128(dpath
->drive
.signature
, &p_uuid
);
489 /* Sub-Type 4 – File Path */
490 if (dpath
->sub_type
== MEDIA_FILEPATH_DP
&& !p
&& path
) {
491 p
= utf16_to_utf8(dpath
->path
, dpath
->length
-4);
495 efi_tilt_backslashes(p
);
502 *title
= TAKE_PTR(s
);
508 *active
= !!(header
->attr
& LOAD_OPTION_ACTIVE
);
513 static void to_utf16(uint16_t *dest
, const char *src
) {
516 for (i
= 0; src
[i
] != '\0'; i
++)
521 static void id128_to_efi_guid(sd_id128_t id
, void *guid
) {
523 .u1
= id
.bytes
[0] << 24 | id
.bytes
[1] << 16 | id
.bytes
[2] << 8 | id
.bytes
[3],
524 .u2
= id
.bytes
[4] << 8 | id
.bytes
[5],
525 .u3
= id
.bytes
[6] << 8 | id
.bytes
[7],
527 memcpy(uuid
.u4
, id
.bytes
+8, sizeof(uuid
.u4
));
528 memcpy(guid
, &uuid
, sizeof(uuid
));
531 static uint16_t *tilt_slashes(uint16_t *s
) {
541 int efi_add_boot_option(
547 sd_id128_t part_uuid
,
550 size_t size
, title_len
, path_len
;
551 _cleanup_free_
char *buf
= NULL
;
552 struct boot_option
*option
;
553 struct device_path
*devicep
;
559 title_len
= (strlen(title
)+1) * 2;
560 path_len
= (strlen(path
)+1) * 2;
562 buf
= malloc0(offsetof(struct boot_option
, title
) + title_len
+
563 sizeof(struct drive_path
) +
564 sizeof(struct device_path
) + path_len
);
569 option
= (struct boot_option
*)buf
;
570 option
->attr
= LOAD_OPTION_ACTIVE
;
571 option
->path_len
= offsetof(struct device_path
, drive
) + sizeof(struct drive_path
) +
572 offsetof(struct device_path
, path
) + path_len
+
573 offsetof(struct device_path
, path
);
574 to_utf16(option
->title
, title
);
575 size
= offsetof(struct boot_option
, title
) + title_len
;
578 devicep
= (struct device_path
*)(buf
+ size
);
579 devicep
->type
= MEDIA_DEVICE_PATH
;
580 devicep
->sub_type
= MEDIA_HARDDRIVE_DP
;
581 devicep
->length
= offsetof(struct device_path
, drive
) + sizeof(struct drive_path
);
582 memcpy(&devicep
->drive
.part_nr
, &part
, sizeof(uint32_t));
583 memcpy(&devicep
->drive
.part_start
, &pstart
, sizeof(uint64_t));
584 memcpy(&devicep
->drive
.part_size
, &psize
, sizeof(uint64_t));
585 id128_to_efi_guid(part_uuid
, devicep
->drive
.signature
);
586 devicep
->drive
.mbr_type
= MBR_TYPE_EFI_PARTITION_TABLE_HEADER
;
587 devicep
->drive
.signature_type
= SIGNATURE_TYPE_GUID
;
588 size
+= devicep
->length
;
591 devicep
= (struct device_path
*)(buf
+ size
);
592 devicep
->type
= MEDIA_DEVICE_PATH
;
593 devicep
->sub_type
= MEDIA_FILEPATH_DP
;
594 devicep
->length
= offsetof(struct device_path
, path
) + path_len
;
595 to_utf16(devicep
->path
, path
);
596 tilt_slashes(devicep
->path
);
597 size
+= devicep
->length
;
600 devicep
= (struct device_path
*)(buf
+ size
);
601 devicep
->type
= END_DEVICE_PATH_TYPE
;
602 devicep
->sub_type
= END_ENTIRE_DEVICE_PATH_SUBTYPE
;
603 devicep
->length
= offsetof(struct device_path
, path
);
604 size
+= devicep
->length
;
606 xsprintf(boot_id
, "Boot%04X", id
);
607 return efi_set_variable(EFI_VENDOR_GLOBAL
, boot_id
, buf
, size
);
610 int efi_remove_boot_option(uint16_t id
) {
616 xsprintf(boot_id
, "Boot%04X", id
);
617 return efi_set_variable(EFI_VENDOR_GLOBAL
, boot_id
, NULL
, 0);
620 int efi_get_boot_order(uint16_t **order
) {
621 _cleanup_free_
void *buf
= NULL
;
628 r
= efi_get_variable(EFI_VENDOR_GLOBAL
, "BootOrder", NULL
, &buf
, &l
);
635 if (l
% sizeof(uint16_t) > 0 ||
636 l
/ sizeof(uint16_t) > INT_MAX
)
639 *order
= TAKE_PTR(buf
);
640 return (int) (l
/ sizeof(uint16_t));
643 int efi_set_boot_order(uint16_t *order
, size_t n
) {
648 return efi_set_variable(EFI_VENDOR_GLOBAL
, "BootOrder", order
, n
* sizeof(uint16_t));
651 static int boot_id_hex(const char s
[static 4]) {
654 for (i
= 0; i
< 4; i
++)
655 if (s
[i
] >= '0' && s
[i
] <= '9')
656 id
|= (s
[i
] - '0') << (3 - i
) * 4;
657 else if (s
[i
] >= 'A' && s
[i
] <= 'F')
658 id
|= (s
[i
] - 'A' + 10) << (3 - i
) * 4;
665 static int cmp_uint16(const uint16_t *a
, const uint16_t *b
) {
669 int efi_get_boot_options(uint16_t **options
) {
670 _cleanup_closedir_
DIR *dir
= NULL
;
671 _cleanup_free_
uint16_t *list
= NULL
;
681 dir
= opendir("/sys/firmware/efi/efivars/");
685 FOREACH_DIRENT(de
, dir
, return -errno
) {
688 if (strncmp(de
->d_name
, "Boot", 4) != 0)
691 if (strlen(de
->d_name
) != 45)
694 if (strcmp(de
->d_name
+ 8, "-8be4df61-93ca-11d2-aa0d-00e098032b8c") != 0)
697 id
= boot_id_hex(de
->d_name
+ 4);
701 if (!GREEDY_REALLOC(list
, alloc
, count
+ 1))
707 typesafe_qsort(list
, count
, cmp_uint16
);
709 *options
= TAKE_PTR(list
);
714 static int read_usec(sd_id128_t vendor
, const char *name
, usec_t
*u
) {
715 _cleanup_free_
char *j
= NULL
;
722 r
= efi_get_variable_string(EFI_VENDOR_LOADER
, name
, &j
);
726 r
= safe_atou64(j
, &x
);
734 int efi_loader_get_boot_usec(usec_t
*firmware
, usec_t
*loader
) {
744 r
= read_usec(EFI_VENDOR_LOADER
, "LoaderTimeInitUSec", &x
);
748 r
= read_usec(EFI_VENDOR_LOADER
, "LoaderTimeExecUSec", &y
);
755 if (y
> USEC_PER_HOUR
)
764 int efi_loader_get_device_part_uuid(sd_id128_t
*u
) {
765 _cleanup_free_
char *p
= NULL
;
771 r
= efi_get_variable_string(EFI_VENDOR_LOADER
, "LoaderDevicePartUUID", &p
);
775 if (sscanf(p
, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
776 &parsed
[0], &parsed
[1], &parsed
[2], &parsed
[3],
777 &parsed
[4], &parsed
[5], &parsed
[6], &parsed
[7],
778 &parsed
[8], &parsed
[9], &parsed
[10], &parsed
[11],
779 &parsed
[12], &parsed
[13], &parsed
[14], &parsed
[15]) != 16)
785 for (i
= 0; i
< ELEMENTSOF(parsed
); i
++)
786 u
->bytes
[i
] = parsed
[i
];
792 int efi_loader_get_entries(char ***ret
) {
793 _cleanup_free_ char16_t
*entries
= NULL
;
794 _cleanup_strv_free_
char **l
= NULL
;
795 size_t size
, i
, start
;
803 r
= efi_get_variable(EFI_VENDOR_LOADER
, "LoaderEntries", NULL
, (void**) &entries
, &size
);
807 /* The variable contains a series of individually NUL terminated UTF-16 strings. */
809 for (i
= 0, start
= 0;; i
++) {
810 _cleanup_free_
char *decoded
= NULL
;
813 /* Is this the end of the variable's data? */
814 end
= i
* sizeof(char16_t
) >= size
;
816 /* Are we in the middle of a string? (i.e. not at the end of the variable, nor at a NUL terminator?) If
817 * so, let's go to the next entry. */
818 if (!end
&& entries
[i
] != 0)
821 /* We reached the end of a string, let's decode it into UTF-8 */
822 decoded
= utf16_to_utf8(entries
+ start
, (i
- start
) * sizeof(char16_t
));
826 if (efi_loader_entry_name_valid(decoded
)) {
827 r
= strv_consume(&l
, TAKE_PTR(decoded
));
831 log_debug("Ignoring invalid loader entry '%s'.", decoded
);
833 /* We reached the end of the variable */
837 /* Continue after the NUL byte */
845 int efi_loader_get_features(uint64_t *ret
) {
846 _cleanup_free_
void *v
= NULL
;
850 if (!is_efi_boot()) {
855 r
= efi_get_variable(EFI_VENDOR_LOADER
, "LoaderFeatures", NULL
, &v
, &s
);
857 _cleanup_free_
char *info
= NULL
;
859 /* The new (v240+) LoaderFeatures variable is not supported, let's see if it's systemd-boot at all */
860 r
= efi_get_variable_string(EFI_VENDOR_LOADER
, "LoaderInfo", &info
);
865 /* Variable not set, definitely means not systemd-boot */
867 } else if (first_word(info
, "systemd-boot")) {
869 /* An older systemd-boot version. Let's hardcode the feature set, since it was pretty
870 * static in all its versions. */
872 *ret
= EFI_LOADER_FEATURE_CONFIG_TIMEOUT
|
873 EFI_LOADER_FEATURE_ENTRY_DEFAULT
|
874 EFI_LOADER_FEATURE_ENTRY_ONESHOT
;
879 /* No features supported */
886 if (s
!= sizeof(uint64_t))
887 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
888 "LoaderFeatures EFI variable doesn't have the right size.");
890 memcpy(ret
, v
, sizeof(uint64_t));
896 bool efi_loader_entry_name_valid(const char *s
) {
900 if (strlen(s
) > FILENAME_MAX
) /* Make sure entry names fit in filenames */
903 return in_charset(s
, ALPHANUMERICAL
"-_.");
906 char *efi_tilt_backslashes(char *s
) {