Debian Codegraph @

src/boot/hii.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "efi-log.h"
4 #include "hii.h"
5 #include "proto/hii-database.h"
6 #include "util.h"
7
8 char16_t *hii_query_keyboard_layout_language(void) {
9 EFI_HII_DATABASE_PROTOCOL *hii_db = NULL;
10 EFI_STATUS err;
11
12 err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_HII_DATABASE_PROTOCOL), /* Registration= */ NULL, (void **) &hii_db);
13 if (err != EFI_SUCCESS) {
14 log_debug_status(err, "HII database protocol not available, ignoring: %m");
15 return NULL;
16 }
17
18 /* First call sizes the layout. We pass length=0 / buffer=NULL and expect EFI_BUFFER_TOO_SMALL. */
19 uint16_t length = 0;
20 err = hii_db->GetKeyboardLayout(hii_db, /* KeyGuid= */ NULL, &length, /* KeyboardLayout= */ NULL);
21 if (err != EFI_BUFFER_TOO_SMALL) {
22 log_debug_status(err, "Initial GetKeyboardLayout did not report required buffer size, ignoring: %m");
23 return NULL;
24 }
25 if (length < sizeof(EFI_HII_KEYBOARD_LAYOUT)) {
26 log_debug("Reported keyboard layout size %u is smaller than the header, ignoring.", length);
27 return NULL;
28 }
29
30 _cleanup_free_ EFI_HII_KEYBOARD_LAYOUT *layout = xmalloc(length);
31 err = hii_db->GetKeyboardLayout(hii_db, /* KeyGuid= */ NULL, &length, layout);
32 if (err != EFI_SUCCESS) {
33 log_debug_status(err, "Failed to retrieve current keyboard layout, ignoring: %m");
34 return NULL;
35 }
36
37 if (length < sizeof(EFI_HII_KEYBOARD_LAYOUT)) {
38 log_debug("Reported keyboard layout size %u shrank below the header, ignoring.", length);
39 return NULL;
40 }
41
42 if (layout->LayoutLength != length) {
43 log_debug("Keyboard layout reports inconsistent LayoutLength %u vs %u, ignoring.",
44 layout->LayoutLength, length);
45 return NULL;
46 }
47
48 uint32_t off = layout->LayoutDescriptorStringOffset;
49 if (off > length || length - off < sizeof(EFI_DESCRIPTION_STRING_BUNDLE)) {
50 log_debug("Keyboard layout descriptor string offset %u out of bounds (length %u), ignoring.",
51 off, length);
52 return NULL;
53 }
54
55 const EFI_DESCRIPTION_STRING_BUNDLE *bundle = (const EFI_DESCRIPTION_STRING_BUNDLE *) ((const uint8_t *) layout + off);
56 if (bundle->DescriptionCount == 0) {
57 log_debug("Keyboard layout has no description strings, ignoring.");
58 return NULL;
59 }
60
61 /* Walk Strings[] looking for the U+0020 that terminates the first language tag. */
62 size_t max_chars = (length - off - sizeof(EFI_DESCRIPTION_STRING_BUNDLE)) / sizeof(char16_t);
63 size_t n;
64 for (n = 0; n < max_chars; n++)
65 if (bundle->Strings[n] == u' ')
66 break;
67 if (n == max_chars) {
68 log_debug("Keyboard layout language tag is not terminated by a space, ignoring.");
69 return NULL;
70 }
71 if (n == 0) {
72 log_debug("Keyboard layout language tag is empty, ignoring.");
73 return NULL;
74 }
75
76 char16_t *s = xnew(char16_t, n + 1);
77 memcpy(s, bundle->Strings, n * sizeof(char16_t));
78 s[n] = u'\0';
79 return s;
80 }