interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi / src / proto / driver / component_name.rs

515 lines · 17457 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3// This module defines the `ComponentName1` type and marks it deprecated. That
4// causes warnings for uses within this module (e.g. the `impl ComponentName1`
5// block), so turn off deprecated warnings. It's not yet possible to make this
6// allow more fine-grained, see https://github.com/rust-lang/rust/issues/62398.
7#![allow(deprecated)]
8
9use crate::boot::{self, ScopedProtocol};
10use crate::proto::unsafe_protocol;
11use crate::{CStr16, Error, Handle, Result, Status, StatusExt};
12use core::fmt::{self, Debug, Display, Formatter};
13use core::{error, ptr, result, slice, str};
14use uefi_raw::protocol::driver::ComponentName2Protocol;
15
16/// Component Name1 [`Protocol`].
17///
18/// Protocol that provides human-readable names for a driver and for each of the
19/// controllers that the driver is managing.
20///
21/// This protocol was deprecated in UEFI 2.1 in favor of the new
22/// [`ComponentName2`] protocol. The two protocols are identical except the
23/// encoding of supported languages changed from [ISO 639-2] to [RFC 4646]. The
24/// [`ComponentName`] wrapper can be used to automatically select
25/// [`ComponentName2`] if available, and otherwise fall back to
26/// [`ComponentName1`].
27///
28/// The corresponding C type is `EFI_COMPONENT_NAME_PROTOCOL`.
29///
30/// [ISO 639-2]: https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes
31/// [RFC 4646]: https://www.rfc-editor.org/rfc/rfc4646
32/// [`Protocol`]: uefi::proto::Protocol
33#[deprecated = "deprecated in UEFI 2.1; use ComponentName2 where possible"]
34#[unsafe_protocol(ComponentName2Protocol::DEPRECATED_COMPONENT_NAME_GUID)]
35#[derive(Debug)]
36#[repr(transparent)]
37pub struct ComponentName1(
38 // The layout of the protocol is the same as ComponentName2, only the format
39 // of the language string changed.
40 ComponentName2Protocol,
41);
42
43impl ComponentName1 {
44 /// Get an iterator over supported languages. Each language is identified by
45 /// a three-letter ASCII string specified in [ISO 639-2]. For example,
46 /// English is encoded as "eng".
47 ///
48 /// [ISO 639-2]: https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes
49 pub const fn supported_languages(&self) -> result::Result<LanguageIter<'_>, LanguageError> {
50 LanguageIter::new(self.0.supported_languages, LanguageIterKind::V1)
51 }
52
53 /// Get the human-readable name of the driver in the given language.
54 ///
55 /// `language` must be one of the languages returned by [`supported_languages`].
56 ///
57 /// [`supported_languages`]: Self::supported_languages
58 pub fn driver_name(&self, language: &str) -> Result<&CStr16> {
59 let language = language_to_cstr(language)?;
60 let mut driver_name = ptr::null();
61 // SAFETY: The memory is valid.
62 unsafe { (self.0.get_driver_name)(&self.0, language.as_ptr(), &mut driver_name) }
63 .to_result()?;
64 // SAFETY: The firmware wrote NULL or a valid string pointer.
65 unsafe { name_from_ptr(driver_name) }
66 }
67
68 /// Get the human-readable name of a controller in the given language.
69 ///
70 /// `language` must be one of the languages returned by [`supported_languages`].
71 ///
72 /// [`supported_languages`]: Self::supported_languages
73 pub fn controller_name(
74 &self,
75 controller_handle: Handle,
76 child_handle: Option<Handle>,
77 language: &str,
78 ) -> Result<&CStr16> {
79 let language = language_to_cstr(language)?;
80 let mut driver_name = ptr::null();
81 // SAFETY: The memory is valid.
82 unsafe {
83 (self.0.get_controller_name)(
84 &self.0,
85 controller_handle.as_ptr(),
86 Handle::opt_to_ptr(child_handle),
87 language.as_ptr(),
88 &mut driver_name,
89 )
90 }
91 .to_result()?;
92 // SAFETY: The firmware wrote NULL or a valid string pointer.
93 unsafe { name_from_ptr(driver_name) }
94 }
95}
96
97/// Component Name2 [`Protocol`].
98///
99/// Protocol that provides human-readable names for a driver and for each of the
100/// controllers that the driver is managing.
101///
102/// This protocol was introduced in UEFI 2.1 to replace the now-deprecated
103/// [`ComponentName1`] protocol. The two protocols are identical except the
104/// encoding of supported languages changed from [ISO 639-2] to [RFC 4646]. The
105/// [`ComponentName`] wrapper can be used to automatically select
106/// [`ComponentName2`] if available, and otherwise fall back to
107/// [`ComponentName1`].
108///
109/// The corresponding C type is `EFI_COMPONENT_NAME2_PROTOCOL`.
110///
111/// [ISO 639-2]: https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes
112/// [RFC 4646]: https://www.rfc-editor.org/rfc/rfc4646
113/// [`Protocol`]: uefi::proto::Protocol
114#[unsafe_protocol(ComponentName2Protocol::GUID)]
115#[derive(Debug)]
116#[repr(transparent)]
117pub struct ComponentName2(ComponentName2Protocol);
118
119impl ComponentName2 {
120 /// Get an iterator over supported languages. Each language is identified by
121 /// an ASCII string specified in [RFC 4646]. For example, English is encoded
122 /// as "en".
123 ///
124 /// [RFC 4646]: https://www.rfc-editor.org/rfc/rfc4646
125 pub const fn supported_languages(&self) -> result::Result<LanguageIter<'_>, LanguageError> {
126 LanguageIter::new(self.0.supported_languages, LanguageIterKind::V2)
127 }
128
129 /// Get the human-readable name of the driver in the given language.
130 ///
131 /// `language` must be one of the languages returned by [`supported_languages`].
132 ///
133 /// [`supported_languages`]: Self::supported_languages
134 pub fn driver_name(&self, language: &str) -> Result<&CStr16> {
135 let language = language_to_cstr(language)?;
136 let mut driver_name = ptr::null();
137 // SAFETY: The memory is valid.
138 unsafe { (self.0.get_driver_name)(&self.0, language.as_ptr(), &mut driver_name) }
139 .to_result()?;
140 // SAFETY: The firmware wrote NULL or a valid string pointer.
141 unsafe { name_from_ptr(driver_name) }
142 }
143
144 /// Get the human-readable name of a controller in the given language.
145 ///
146 /// `language` must be one of the languages returned by [`supported_languages`].
147 ///
148 /// [`supported_languages`]: Self::supported_languages
149 pub fn controller_name(
150 &self,
151 controller_handle: Handle,
152 child_handle: Option<Handle>,
153 language: &str,
154 ) -> Result<&CStr16> {
155 let language = language_to_cstr(language)?;
156 let mut driver_name = ptr::null();
157 // SAFETY: The memory is valid.
158 unsafe {
159 (self.0.get_controller_name)(
160 &self.0,
161 controller_handle.as_ptr(),
162 Handle::opt_to_ptr(child_handle),
163 language.as_ptr(),
164 &mut driver_name,
165 )
166 }
167 .to_result()?;
168 // SAFETY: The firmware wrote NULL or a valid string pointer.
169 unsafe { name_from_ptr(driver_name) }
170 }
171}
172
173/// Wrapper around [`ComponentName1`] and [`ComponentName2`]. This will use
174/// [`ComponentName2`] if available, otherwise it will back to
175/// [`ComponentName1`].
176pub enum ComponentName {
177 /// Opened [`ComponentName1`] protocol.
178 V1(ScopedProtocol<ComponentName1>),
179
180 /// Opened [`ComponentName2`] protocol.
181 V2(ScopedProtocol<ComponentName2>),
182}
183
184impl ComponentName {
185 /// Open the [`ComponentName2`] protocol if available, otherwise fall back to
186 /// [`ComponentName1`].
187 pub fn open(handle: Handle) -> Result<Self> {
188 if let Ok(cn2) = boot::open_protocol_exclusive::<ComponentName2>(handle) {
189 Ok(Self::V2(cn2))
190 } else {
191 Ok(Self::V1(boot::open_protocol_exclusive::<ComponentName1>(
192 handle,
193 )?))
194 }
195 }
196
197 /// Get an iterator over supported languages. Each language is identified by
198 /// an ASCII string. If the opened protocol is [`ComponentName1`] this will
199 /// be an [ISO 639-2] string. If the opened protocol is [`ComponentName2`]
200 /// it will be an [RFC 4646] string. For example, English is encoded as
201 /// "eng" in ISO 639-2, and "en" in RFC 4646.
202 ///
203 /// [ISO 639-2]: https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes
204 /// [RFC 4646]: https://www.rfc-editor.org/rfc/rfc4646
205 pub fn supported_languages(&self) -> result::Result<LanguageIter<'_>, LanguageError> {
206 match self {
207 Self::V1(cn1) => cn1.supported_languages(),
208 Self::V2(cn2) => cn2.supported_languages(),
209 }
210 }
211
212 /// Get the human-readable name of the driver in the given language.
213 ///
214 /// `language` must be one of the languages returned by [`supported_languages`].
215 ///
216 /// [`supported_languages`]: Self::supported_languages
217 pub fn driver_name(&self, language: &str) -> Result<&CStr16> {
218 match self {
219 Self::V1(cn1) => cn1.driver_name(language),
220 Self::V2(cn2) => cn2.driver_name(language),
221 }
222 }
223
224 /// Get the human-readable name of a controller in the given language.
225 ///
226 /// `language` must be one of the languages returned by [`supported_languages`].
227 ///
228 /// [`supported_languages`]: Self::supported_languages
229 pub fn controller_name(
230 &self,
231 controller_handle: Handle,
232 child_handle: Option<Handle>,
233 language: &str,
234 ) -> Result<&CStr16> {
235 match self {
236 Self::V1(cn1) => cn1.controller_name(controller_handle, child_handle, language),
237 Self::V2(cn2) => cn2.controller_name(controller_handle, child_handle, language),
238 }
239 }
240}
241
242impl Debug for ComponentName {
243 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
244 match self {
245 Self::V1(_) => f.debug_tuple("V1").finish(),
246 Self::V2(_) => f.debug_tuple("V2").finish(),
247 }
248 }
249}
250
251/// Error returned by [`ComponentName1::supported_languages`] and
252/// [`ComponentName2::supported_languages`].
253#[derive(Debug, Eq, PartialEq)]
254pub enum LanguageError {
255 /// The supported languages list contains a non-ASCII character at the
256 /// specified index.
257 Ascii {
258 /// Index of the invalid character.
259 index: usize,
260 },
261}
262
263impl Display for LanguageError {
264 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
265 match self {
266 Self::Ascii { index } => write!(f, "invalid character at index: {index}"),
267 }
268 }
269}
270
271impl error::Error for LanguageError {}
272
273#[derive(Debug, PartialEq)]
274enum LanguageIterKind {
275 V1,
276 V2,
277}
278
279/// Iterator returned by [`ComponentName1::supported_languages`] and
280/// [`ComponentName2::supported_languages`].
281#[derive(Debug)]
282pub struct LanguageIter<'a> {
283 languages: &'a [u8],
284 kind: LanguageIterKind,
285}
286
287impl LanguageIter<'_> {
288 const fn new(
289 languages: *const u8,
290 kind: LanguageIterKind,
291 ) -> result::Result<Self, LanguageError> {
292 // Firmware that reports no languages leaves the pointer null.
293 if languages.is_null() {
294 return Ok(Self {
295 languages: &[],
296 kind,
297 });
298 }
299 let mut index = 0;
300 loop {
301 // SAFETY: The memory is valid.
302 let c = unsafe { languages.add(index).read() };
303 if c == 0 {
304 break;
305 } else if !c.is_ascii() {
306 return Err(LanguageError::Ascii { index });
307 } else {
308 index += 1;
309 }
310 }
311
312 Ok(Self {
313 // SAFETY: The pointer is valid for the requested slice length.
314 languages: unsafe { slice::from_raw_parts(languages, index) },
315 kind,
316 })
317 }
318}
319
320impl<'a> Iterator for LanguageIter<'a> {
321 type Item = &'a str;
322
323 fn next(&mut self) -> Option<Self::Item> {
324 if self.languages.is_empty() {
325 return None;
326 }
327
328 let lang;
329 match self.kind {
330 LanguageIterKind::V1 => {
331 if self.languages.len() <= 3 {
332 lang = self.languages;
333 self.languages = &[];
334 } else {
335 lang = &self.languages[..3];
336 self.languages = &self.languages[3..];
337 }
338 }
339 LanguageIterKind::V2 => {
340 if let Some(index) = self.languages.iter().position(|c| *c == b';') {
341 lang = &self.languages[..index];
342 self.languages = &self.languages[index + 1..];
343 } else {
344 lang = self.languages;
345 self.languages = &[];
346 }
347 }
348 }
349
350 // OK to unwrap because we already checked the string is ASCII.
351 Some(str::from_utf8(lang).unwrap())
352 }
353}
354
355/// Statically-sized buffer used to convert a `str` to a null-terminated C
356/// string. The buffer should be at least 42 characters per
357/// <https://www.rfc-editor.org/rfc/rfc4646#section-4.3.1>, plus one for the
358/// null terminator. Round up to 64 bytes just for aesthetics.
359type LanguageCStr = [u8; 64];
360
361fn language_to_cstr(language: &str) -> Result<LanguageCStr> {
362 let mut lang_cstr: LanguageCStr = [0; 64];
363 // Ensure there's room for a null-terminator.
364 if language.len() >= lang_cstr.len() - 1 {
365 return Err(Error::from(Status::BUFFER_TOO_SMALL));
366 }
367 lang_cstr[..language.len()].copy_from_slice(language.as_bytes());
368 // Assert that it's null-terminated.
369 assert_eq!(*lang_cstr.last().unwrap(), 0);
370 Ok(lang_cstr)
371}
372
373/// Converts a name pointer written by the firmware to a string.
374///
375/// Firmware that reports success without providing a name violates the
376/// spec. Report this as [`Status::NOT_FOUND`] instead of dereferencing NULL.
377///
378/// # Safety
379///
380/// `ptr` must be NULL or point to a NUL-terminated string that is valid for
381/// the returned lifetime.
382unsafe fn name_from_ptr<'a>(ptr: *const u16) -> Result<&'a CStr16> {
383 if ptr.is_null() {
384 return Err(Error::from(Status::NOT_FOUND));
385 }
386 // SAFETY: Guaranteed by the caller.
387 Ok(unsafe { CStr16::from_ptr(ptr.cast()) })
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393 use LanguageIterKind::{V1, V2};
394 use alloc::vec::Vec;
395
396 #[test]
397 fn test_language_iter_v1() {
398 // Empty string.
399 let data = "\0";
400 assert!(
401 LanguageIter::new(data.as_ptr(), V1)
402 .unwrap()
403 .next()
404 .is_none()
405 );
406
407 // Two languages.
408 let data = "engfra\0";
409 assert_eq!(
410 LanguageIter::new(data.as_ptr(), V1)
411 .unwrap()
412 .collect::<Vec<_>>(),
413 ["eng", "fra"]
414 );
415
416 // Truncated data.
417 let data = "en\0";
418 assert_eq!(
419 LanguageIter::new(data.as_ptr(), V1)
420 .unwrap()
421 .collect::<Vec<_>>(),
422 ["en"]
423 );
424
425 // Non-ASCII.
426 let data = "engæ\0";
427 assert_eq!(
428 LanguageIter::new(data.as_ptr(), V1).err().unwrap(),
429 LanguageError::Ascii { index: 3 },
430 );
431 }
432
433 #[test]
434 fn test_language_iter_v2() {
435 // Empty string.
436 let data = "\0";
437 assert!(
438 LanguageIter::new(data.as_ptr(), V2)
439 .unwrap()
440 .next()
441 .is_none()
442 );
443
444 // Two languages.
445 let data = "en;fr\0";
446 assert_eq!(
447 LanguageIter::new(data.as_ptr(), V2)
448 .unwrap()
449 .collect::<Vec<_>>(),
450 ["en", "fr"]
451 );
452
453 // Non-ASCII.
454 let data = "engæ\0";
455 assert_eq!(
456 LanguageIter::new(data.as_ptr(), V2).err().unwrap(),
457 LanguageError::Ascii { index: 3 },
458 );
459 }
460
461 /// Mock of `ComponentName2Protocol::get_driver_name` that reports
462 /// success without providing a name.
463 unsafe extern "efiapi" fn mock_get_driver_name_null(
464 _this: *const ComponentName2Protocol,
465 _language: *const u8,
466 driver_name: *mut *const u16,
467 ) -> Status {
468 // SAFETY: Guaranteed by the caller.
469 unsafe { driver_name.write(ptr::null()) };
470 Status::SUCCESS
471 }
472
473 extern "efiapi" fn stub_get_controller_name(
474 _: *const ComponentName2Protocol,
475 _: uefi_raw::Handle,
476 _: uefi_raw::Handle,
477 _: *const u8,
478 _: *mut *const u16,
479 ) -> Status {
480 unimplemented!()
481 }
482
483 #[test]
484 fn test_driver_name_null_on_success() {
485 let raw = ComponentName2Protocol {
486 get_driver_name: mock_get_driver_name_null,
487 get_controller_name: stub_get_controller_name,
488 supported_languages: c"en".as_ptr().cast(),
489 };
490 // SAFETY: `ComponentName2` is a transparent wrapper.
491 let cn = unsafe { &*ptr::from_ref(&raw).cast::<ComponentName2>() };
492 assert_eq!(
493 cn.driver_name("en").unwrap_err().status(),
494 Status::NOT_FOUND
495 );
496 }
497
498 #[test]
499 fn test_language_to_cstr() {
500 let mut expected = [0; 64];
501 expected[0] = b'e';
502 expected[1] = b'n';
503 assert_eq!(language_to_cstr("en"), Ok(expected));
504
505 assert_eq!(
506 language_to_cstr(
507 "0123456789012345678901234567890123456789012345678901234567890123456789"
508 )
509 .err()
510 .unwrap()
511 .status(),
512 Status::BUFFER_TOO_SMALL
513 );
514 }
515}