multiboot2 0.27.0

Convenient and safe parsing of Multiboot2 Boot Information (MBI) structures and the contained information tags. Usable in `no_std` environments, such as a kernel. The default `builder` feature also allows the construction of the corresponding structures.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! Module for [`BootInformation`].

use crate::framebuffer::UnknownFramebufferType;
use crate::tag::TagHeader;
use crate::{
    ApmTag, BasicMemoryInfoTag, BootLoaderNameTag, BootdevTag, CommandLineTag,
    EFIBootServicesNotExitedTag, EFIImageHandle32Tag, EFIImageHandle64Tag, EFIMemoryMapTag,
    EFISdt32Tag, EFISdt64Tag, ElfSectionIter, ElfSectionsTag, EndTag, FramebufferTag,
    ImageLoadPhysAddrTag, MemoryMapTag, ModuleIter, NetworkTag, RsdpV1Tag, RsdpV2Tag, SmbiosTag,
    TagIter, TagType, VBEInfoTag, module,
};
use core::fmt;
use core::ptr::NonNull;
use multiboot2_common::{
    DynSizedStructure, Header, MaybeDynSized, MemoryError, Tag, validate_tag_sequence,
};
use thiserror::Error;

/// Errors that occur when a chunk of memory can't be parsed as
/// [`BootInformation`].
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Error)]
pub enum LoadError {
    /// The provided memory can't be parsed as [`BootInformation`].
    /// See [`MemoryError`].
    #[error("memory can't be parsed as boot information")]
    Memory(#[source] MemoryError),
    /// Missing mandatory end tag.
    #[error("missing mandatory end tag")]
    NoEndTag,
}

/// The basic header of a [`BootInformation`] as sized Rust type.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C, align(8))]
pub struct BootInformationHeader {
    // size is multiple of 8
    total_size: u32,
    _reserved: u32,
    // Followed by the boot information tags.
}

impl BootInformationHeader {
    #[cfg(feature = "builder")]
    pub(crate) const fn new(total_size: u32) -> Self {
        Self {
            total_size,
            _reserved: 0,
        }
    }

    /// Returns the total size of the structure.
    #[must_use]
    pub const fn total_size(&self) -> u32 {
        self.total_size
    }
}

// SAFETY: The header is a padding-free repr(C) struct of raw integers, and
// any bit pattern is valid for it.
unsafe impl Header for BootInformationHeader {
    fn total_size(&self) -> usize {
        self.total_size as usize
    }

    fn set_size(&mut self, total_size: usize) {
        self.total_size = total_size as u32;
    }
}

/// A Multiboot 2 Boot Information (MBI) accessor.
#[repr(transparent)]
#[derive(PartialEq, Eq)]
pub struct BootInformation<'a>(&'a DynSizedStructure<BootInformationHeader>);

impl<'a> BootInformation<'a> {
    /// Loads the [`BootInformation`] from a pointer.
    ///
    /// If the boot information is invalid, it returns a [`LoadError`].
    /// This may be because:
    /// - `ptr` is a null pointer
    /// - `ptr` is not 8-byte aligned
    /// - the reported total size is invalid
    /// - the tag sequence is incomplete or malformed
    /// - the mandatory end tag is missing
    ///
    /// ## Example
    ///
    /// ```rust
    /// use multiboot2::{BootInformation, BootInformationHeader};
    ///
    /// fn kernel_entry(mb_magic: u32, mbi_ptr: u32) {
    ///     if mb_magic == multiboot2::MAGIC {
    ///         let boot_info = unsafe { BootInformation::load(mbi_ptr as *const BootInformationHeader).unwrap() };
    ///         let _cmd = boot_info.command_line_tag();
    ///     } else { /* Panic or use multiboot1 flow. */ }
    /// }
    /// ```
    ///
    /// # Safety
    ///
    /// * `ptr` must be valid for reading the complete reported boot
    ///   information size. Otherwise, this function might cause invalid machine
    ///   state or crash your binary.
    /// * The memory at `ptr` must not be modified after calling `load` or the
    ///   program may observe unsynchronized mutation.
    pub unsafe fn load(ptr: *const BootInformationHeader) -> Result<Self, LoadError> {
        let ptr = NonNull::new(ptr.cast_mut()).ok_or(LoadError::Memory(MemoryError::Null))?;
        // SAFETY: `ptr` was checked for null and `ref_from_ptr` validates the
        // reported total size before constructing the DST reference.
        let inner = unsafe { DynSizedStructure::ref_from_ptr(ptr).map_err(LoadError::Memory)? };

        let this = Self(inner);
        if !this.has_valid_tag_sequence().map_err(LoadError::Memory)? {
            return Err(LoadError::NoEndTag);
        }
        Ok(this)
    }

    /// Checks if the MBI has a valid, complete tag sequence.
    fn has_valid_tag_sequence(&self) -> Result<bool, MemoryError> {
        validate_tag_sequence(self.0.payload(), |tag| {
            let typ = u32::from_le_bytes(tag[0..4].try_into().unwrap());
            let size = u32::from_le_bytes(tag[4..8].try_into().unwrap()) as usize;

            typ == TagType::End.val() && size == size_of::<EndTag>()
        })
    }

    /// Get the start address of the boot info.
    #[must_use]
    // TODO deprecated and use pointers only (see provenance discussions)
    pub fn start_address(&self) -> usize {
        self.as_ptr() as usize
    }

    /// Get the start address of the boot info as pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *const () {
        (&raw const *self.0).cast()
    }

    /// Get the end address of the boot info.
    ///
    /// This is the same as doing:
    ///
    /// ```rust,no_run
    /// # use multiboot2::{BootInformation, BootInformationHeader};
    /// # let ptr = 0xdeadbeef as *const BootInformationHeader;
    /// # let boot_info = unsafe { BootInformation::load(ptr).unwrap() };
    /// let end_addr = boot_info.start_address() + boot_info.total_size();
    /// ```
    #[must_use]
    // TODO deprecated and use pointers only (see provenance discussions)
    pub fn end_address(&self) -> usize {
        self.start_address() + self.total_size()
    }

    /// Get the total size of the boot info struct.
    #[must_use]
    pub const fn total_size(&self) -> usize {
        self.0.header().total_size as usize
    }

    // ######################################################
    // ### BEGIN OF TAG GETTERS (in alphabetical order)

    /// Returns the first [`ApmTag`], if present.
    #[must_use]
    pub fn apm_tag(&self) -> Option<&ApmTag> {
        self.get_tag::<ApmTag>()
    }

    /// Returns the first [`BasicMemoryInfoTag`], if present.
    #[must_use]
    pub fn basic_memory_info_tag(&self) -> Option<&BasicMemoryInfoTag> {
        self.get_tag::<BasicMemoryInfoTag>()
    }

    /// Returns the first [`BootLoaderNameTag`], if present.
    #[must_use]
    pub fn boot_loader_name_tag(&self) -> Option<&BootLoaderNameTag> {
        self.get_tag::<BootLoaderNameTag>()
    }

    /// Returns the first [`BootdevTag`], if present.
    #[must_use]
    pub fn bootdev_tag(&self) -> Option<&BootdevTag> {
        self.get_tag::<BootdevTag>()
    }

    /// Returns the first [`CommandLineTag`], if present.
    #[must_use]
    pub fn command_line_tag(&self) -> Option<&CommandLineTag> {
        self.get_tag::<CommandLineTag>()
    }

    /// Returns the first [`EFIBootServicesNotExitedTag`], if present.
    #[must_use]
    pub fn efi_bs_not_exited_tag(&self) -> Option<&EFIBootServicesNotExitedTag> {
        self.get_tag::<EFIBootServicesNotExitedTag>()
    }

    /// Returns the first [`EFIMemoryMapTag`], if the boot services were exited.
    /// Otherwise, if the [`TagType::EfiBs`] tag is present, this returns `None`
    /// as it is strictly recommended to get the memory map from `uefi`
    /// instead.
    ///
    /// [`TagType::EfiBs`]: crate::TagType::EfiBs
    #[must_use]
    pub fn efi_memory_map_tag(&self) -> Option<&EFIMemoryMapTag> {
        // If the EFIBootServicesNotExited is present, then we should not use
        // the memory map, as it could still be in use.
        self.get_tag::<EFIBootServicesNotExitedTag>().map_or_else(
            || self.get_tag::<EFIMemoryMapTag>(), |_tag| {
                            log::debug!("The EFI memory map is present but the UEFI Boot Services Not Existed Tag is present. Returning None.");
                             None
                        })
    }

    /// Returns the first [`EFISdt32Tag`], if present.
    #[must_use]
    pub fn efi_sdt32_tag(&self) -> Option<&EFISdt32Tag> {
        self.get_tag::<EFISdt32Tag>()
    }

    /// Returns the first [`EFISdt64Tag`], if present.
    #[must_use]
    pub fn efi_sdt64_tag(&self) -> Option<&EFISdt64Tag> {
        self.get_tag::<EFISdt64Tag>()
    }

    /// Returns the first [`EFIImageHandle32Tag`], if present.
    #[must_use]
    pub fn efi_ih32_tag(&self) -> Option<&EFIImageHandle32Tag> {
        self.get_tag::<EFIImageHandle32Tag>()
    }

    /// Returns the first [`EFIImageHandle64Tag`], if present.
    #[must_use]
    pub fn efi_ih64_tag(&self) -> Option<&EFIImageHandle64Tag> {
        self.get_tag::<EFIImageHandle64Tag>()
    }

    /// Returns an [`ElfSectionIter`] iterator over the ELF Sections, if the
    /// [`ElfSectionsTag`] is present.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use multiboot2::{BootInformation, BootInformationHeader};
    /// # let ptr = 0xdeadbeef as *const BootInformationHeader;
    /// # let boot_info = unsafe { BootInformation::load(ptr).unwrap() };
    /// if let Some(sections) = boot_info.elf_sections_tag().map(|tag| tag.sections()) {
    ///     let mut total = 0;
    ///     for section in sections {
    ///         println!("Section: {:?}", section);
    ///         total += 1;
    ///     }
    /// }
    /// ```
    #[must_use]
    #[deprecated = "Use elf_sections_tag() instead and corresponding getters"]
    pub fn elf_sections(&self) -> Option<ElfSectionIter<'_>> {
        let tag = self.get_tag::<ElfSectionsTag>();
        tag.map(|t| {
            assert!((t.entry_size() * t.shndx()) <= t.header().size);
            t.sections()
        })
    }

    /// Returns the first [`ElfSectionsTag`], if present.
    #[must_use]
    pub fn elf_sections_tag(&self) -> Option<&ElfSectionsTag> {
        self.get_tag()
    }

    /// Returns the first [`FramebufferTag`], if present. The result is
    /// `Some(Err(e))` if its framebuffer type is unknown.
    #[must_use]
    pub fn framebuffer_tag(&self) -> Option<Result<&FramebufferTag, UnknownFramebufferType>> {
        self.get_tag::<FramebufferTag>()
            .map(|tag| match tag.buffer_type() {
                Ok(_) => Ok(tag),
                Err(e) => Err(e),
            })
    }

    /// Returns the first [`ImageLoadPhysAddrTag`], if present.
    #[must_use]
    pub fn load_base_addr_tag(&self) -> Option<&ImageLoadPhysAddrTag> {
        self.get_tag::<ImageLoadPhysAddrTag>()
    }

    /// Returns the first [`MemoryMapTag`], if present.
    #[must_use]
    pub fn memory_map_tag(&self) -> Option<&MemoryMapTag> {
        self.get_tag::<MemoryMapTag>()
    }

    /// Get an iterator of all [`ModuleTag`]s.
    ///
    /// [`ModuleTag`]: crate::ModuleTag
    #[must_use]
    pub fn module_tags(&self) -> ModuleIter<'_> {
        module::module_iter(self.tags())
    }

    /// Returns an iterator over all [`NetworkTag`]s.
    ///
    /// The Multiboot2 specification permits one network tag per network card.
    pub fn network_tags(&self) -> impl Iterator<Item = &NetworkTag> + Clone {
        self.get_tags::<NetworkTag>()
    }

    /// Returns the first [`NetworkTag`], if present.
    ///
    /// Use [`Self::network_tags`] to access the tags for all network cards.
    #[must_use]
    #[deprecated = "use `network_tags()` to access all network tags"]
    pub fn network_tag(&self) -> Option<&NetworkTag> {
        self.get_tag::<NetworkTag>()
    }

    /// Returns the first [`RsdpV1Tag`], if present.
    #[must_use]
    pub fn rsdp_v1_tag(&self) -> Option<&RsdpV1Tag> {
        self.get_tag::<RsdpV1Tag>()
    }

    /// Returns the first [`RsdpV2Tag`], if present.
    #[must_use]
    pub fn rsdp_v2_tag(&self) -> Option<&RsdpV2Tag> {
        self.get_tag::<RsdpV2Tag>()
    }

    /// Returns an iterator over all [`SmbiosTag`]s.
    pub fn smbios_tags(&self) -> impl Iterator<Item = &SmbiosTag> + Clone {
        self.get_tags::<SmbiosTag>()
    }

    /// Returns the first [`SmbiosTag`], if present.
    ///
    /// Use [`Self::smbios_tags`] to access all SMBIOS tags.
    #[must_use]
    #[deprecated = "use `smbios_tags()` to access all SMBIOS tags"]
    pub fn smbios_tag(&self) -> Option<&SmbiosTag> {
        self.get_tag::<SmbiosTag>()
    }

    /// Returns the first [`VBEInfoTag`], if present.
    #[must_use]
    pub fn vbe_info_tag(&self) -> Option<&VBEInfoTag> {
        self.get_tag::<VBEInfoTag>()
    }

    // ### END OF TAG GETTERS
    // ######################################################

    /// Returns the first Multiboot tag of type `T`, including specified and
    /// custom tags.
    ///
    /// # Specified or Custom Tags
    /// The Multiboot2 specification specifies a list of tags, see [`TagType`].
    /// However, it doesn't forbid to use custom tags. Because of this, there
    /// exists the [`TagType`] abstraction. It is recommended to use this
    /// getter only for custom tags. For specified tags, use getters, such as
    /// [`Self::efi_ih64_tag`]. Use [`Self::get_tags`] if a tag type may occur
    /// multiple times.
    ///
    /// ## Use Custom Tags
    /// The following example shows how you may use this interface to parse
    /// custom tags from the MBI. If they are dynamically sized (DST), a few more
    /// special handling is required. This is reflected by code-comments.
    ///
    /// ```no_run
    /// use std::mem;
    /// use multiboot2::{BootInformation, BootInformationHeader, parse_slice_as_string, StringError, TagHeader, TagType, TagTypeRaw};    ///
    /// use multiboot2_common::{MaybeDynSized, Tag};
    ///
    /// #[repr(C)]
    /// #[derive(multiboot2::Pointee)] // Only needed for DSTs.
    /// struct CustomTag {
    ///     header: TagHeader,
    ///     some_other_prop: u32,
    ///     // Begin of C string, for example.
    ///     name: [u8],
    /// }
    ///
    /// impl CustomTag {
    ///     fn name(&self) -> Result<&str, StringError> {
    ///         parse_slice_as_string(&self.name)
    ///     }
    /// }
    ///
    /// // Give the library hints how big this tag is.
    /// // SAFETY: The tag is repr(C) with the header as first field, any bit
    /// // pattern is valid, and `BASE_SIZE`/`dst_len` match the ABI.
    /// unsafe impl MaybeDynSized for CustomTag {
    ///     type Header = TagHeader;
    ///     const BASE_SIZE: usize = size_of::<TagHeader>() + size_of::<u32>();
    ///
    ///     // This differs for DSTs and normal structs. See function
    ///     // documentation.
    ///     fn dst_len(header: &TagHeader) -> usize {
    ///         assert!(header.size >= Self::BASE_SIZE as u32);
    ///         header.size as usize - Self::BASE_SIZE
    ///     }
    /// }
    ///
    /// // Make the Tag identifiable.
    /// impl Tag for CustomTag {
    ///     type IDType = TagType;
    ///     const ID: TagType = TagType::Custom(0x1337);
    /// }
    ///
    /// let mbi_ptr = 0xdeadbeef as *const BootInformationHeader;
    /// let mbi = unsafe { BootInformation::load(mbi_ptr).unwrap() };
    ///
    /// let tag = mbi
    ///     .get_tag::<CustomTag>()
    ///     .unwrap();
    /// assert_eq!(tag.name(), Ok("name"));
    /// ```
    ///
    /// [`TagType`]: crate::TagType
    #[must_use]
    pub fn get_tag<T: Tag<IDType = TagType, Header = TagHeader> + ?Sized + 'a>(
        &'a self,
    ) -> Option<&'a T>
    where
        T::Metadata: Default,
    {
        self.get_tags::<T>().next()
    }

    /// Returns an iterator over all Multiboot tags of type `T`, including
    /// specified and custom tags.
    ///
    /// Tags are returned lazily in their original wire order. This is the
    /// typed counterpart to [`Self::tags`]. It performs no allocation and does
    /// not apply the additional policies of convenience getters such as
    /// [`Self::efi_memory_map_tag`] or [`Self::framebuffer_tag`].
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use multiboot2::{BootInformation, BootInformationHeader, NetworkTag};
    /// # let ptr = 0xdeadbeef as *const BootInformationHeader;
    /// # let boot_info = unsafe { BootInformation::load(ptr).unwrap() };
    /// for network in boot_info.get_tags::<NetworkTag>() {
    ///     println!("Network information: {network:?}");
    /// }
    /// ```
    pub fn get_tags<'b, T>(&'b self) -> impl Iterator<Item = &'b T> + Clone
    where
        T: Tag<IDType = TagType, Header = TagHeader> + ?Sized + 'b,
        T::Metadata: Default,
    {
        self.tags()
            .filter(|tag| tag.header().typ == T::ID)
            .map(|tag| tag.cast::<T>())
    }

    /// Returns an untyped iterator over all tags.
    ///
    /// Prefer [`Self::get_tags`] when all occurrences of a known standard or
    /// custom tag type are needed. This lower-level iterator is useful when tag
    /// types are not known in advance.
    #[must_use]
    pub fn tags(&self) -> TagIter<'_> {
        // SAFETY: We validated the chain of tags beforehand.
        unsafe { TagIter::new(self.0.payload()) }
    }
}

impl fmt::Debug for BootInformation<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut debug = f.debug_struct("BootInformation");
        debug
            .field("start_address", &self.start_address())
            .field("end_address", &self.end_address())
            .field("total_size", &self.total_size())
            // now tags in alphabetical order
            .field("apm", &self.apm_tag())
            .field("basic_memory_info", &(self.basic_memory_info_tag()))
            .field("boot_loader_name", &self.boot_loader_name_tag())
            .field("bootdev", &self.bootdev_tag())
            .field("command_line", &self.command_line_tag())
            .field("efi_bs_not_exited", &self.efi_bs_not_exited_tag())
            .field("efi_ih32", &self.efi_ih32_tag())
            .field("efi_ih64", &self.efi_ih64_tag())
            .field("efi_memory_map", &self.efi_memory_map_tag())
            .field("efi_sdt32", &self.efi_sdt32_tag())
            .field("efi_sdt64", &self.efi_sdt64_tag())
            .field("elf_sections", &self.elf_sections_tag())
            .field("framebuffer", &self.framebuffer_tag())
            .field("load_base_addr", &self.load_base_addr_tag())
            .field("memory_map", &self.memory_map_tag())
            .field("modules", &self.module_tags())
            .field("network", &DebugTags(self.network_tags()))
            .field("rsdp_v1", &self.rsdp_v1_tag())
            .field("rsdp_v2", &self.rsdp_v2_tag())
            .field("smbios", &DebugTags(self.smbios_tags()))
            .field("vbe_info", &self.vbe_info_tag())
            // computed fields
            .field("custom_tags_count", &{
                self.tags()
                    .filter(|tag| {
                        let id: TagType = tag.header().typ.into();
                        matches!(id, TagType::Custom(_))
                    })
                    .count()
            })
            .field("tag_headers", &DebugTagHeaders(self.tags()))
            .finish()
    }
}

/// Formats a cloneable iterator without consuming the original value.
struct DebugTags<I>(I);

impl<I> fmt::Debug for DebugTags<I>
where
    I: Iterator + Clone,
    I::Item: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.0.clone()).finish()
    }
}

/// Formats the on-wire boot information tag sequence without dumping payloads.
struct DebugTagHeaders<'a>(TagIter<'a>);

impl fmt::Debug for DebugTagHeaders<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(self.0.clone().map(|tag| tag.header()))
            .finish()
    }
}