multiboot2 0.28.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
//! Module for [`FramebufferTag`].

use crate::TagType;
use crate::tag::TagHeader;
use core::fmt::Debug;
use core::slice;
use multiboot2_common::{MaybeDynSized, Tag};
use thiserror::Error;
#[cfg(feature = "builder")]
use {alloc::boxed::Box, multiboot2_common::new_boxed};

/// Helper struct to read bytes from a raw pointer and increase the pointer
/// automatically.
struct Reader<'a> {
    buffer: &'a [u8],
    off: usize,
}

impl<'a> Reader<'a> {
    const fn new(buffer: &'a [u8]) -> Self {
        Self { buffer, off: 0 }
    }

    /// Reads the next [`u8`] from the buffer and updates the internal pointer.
    ///
    /// # Panic
    ///
    /// Panics if the index is out of bounds.
    fn read_next_u8(&mut self) -> u8 {
        let val = self
            .buffer
            .get(self.off)
            .cloned()
            // This is not a solution I'm proud of, but at least it is safe.
            // The whole framebuffer tag code originally is not from me.
            // I hope someone from the community wants to improve this overall
            // functionality someday.
            .expect("Embedded framebuffer info should be properly sized and available");
        self.off += 1;
        val
    }

    /// Reads the next [`u16`] from the buffer and updates the internal pointer.
    ///
    /// # Panic
    ///
    /// Panics if the index is out of bounds.
    fn read_next_u16(&mut self) -> u16 {
        let u16_lo = self.read_next_u8() as u16;
        let u16_hi = self.read_next_u8() as u16;
        (u16_hi << 8) | u16_lo
    }

    const fn current_ptr(&self) -> *const u8 {
        self.buffer.as_ptr().wrapping_add(self.off)
    }
}

/// The VBE Framebuffer information tag.
#[derive(ptr_meta::Pointee, Eq)]
#[repr(C, align(8))]
pub struct FramebufferTag {
    header: TagHeader,

    /// Contains framebuffer physical address.
    ///
    /// This field is 64-bit wide but the bootloader should set it under 4GiB if
    /// possible for compatibility with payloads which aren't aware of PAE or
    /// amd64.
    address: u64,

    /// Contains the pitch in bytes.
    pitch: u32,

    /// Contains framebuffer width in pixels.
    width: u32,

    /// Contains framebuffer height in pixels.
    height: u32,

    /// Contains number of bits per pixel.
    bpp: u8,

    /// The type of framebuffer. See [`FramebufferKind`].
    framebuffer_type: FramebufferTypeRaw,

    _padding: u16,

    /// This optional data and its meaning depends on [`FramebufferTypeRaw`].
    buffer: [u8],
}

impl FramebufferTag {
    /// Constructs a new tag.
    #[cfg(feature = "builder")]
    #[must_use]
    pub fn new(
        address: u64,
        pitch: u32,
        width: u32,
        height: u32,
        bpp: u8,
        buffer_type: FramebufferType,
    ) -> Box<Self> {
        let header = TagHeader::new(Self::ID, 0 /* filled by new_boxed */);
        let address = address.to_ne_bytes();
        let pitch = pitch.to_ne_bytes();
        let width = width.to_ne_bytes();
        let height = height.to_ne_bytes();
        let buffer_type_id = buffer_type.id();
        let padding = [0; 2];
        let optional_buffer = buffer_type.serialize();
        new_boxed(
            header,
            &[
                &address,
                &pitch,
                &width,
                &height,
                &[bpp],
                &[buffer_type_id.get()],
                &padding,
                &optional_buffer,
            ],
        )
    }

    /// Contains framebuffer physical address.
    ///
    /// This field is 64-bit wide but the bootloader should set it under 4GiB if
    /// possible for compatibility with payloads which aren't aware of PAE or
    /// amd64.
    #[must_use]
    pub const fn address(&self) -> u64 {
        self.address
    }

    /// Contains the pitch in bytes.
    #[must_use]
    pub const fn pitch(&self) -> u32 {
        self.pitch
    }

    /// Contains framebuffer width in pixels.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Contains framebuffer height in pixels.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// Contains number of bits per pixel.
    #[must_use]
    pub const fn bpp(&self) -> u8 {
        self.bpp
    }

    /// The type of framebuffer, one of: `Indexed`, `RGB` or `Text`.
    pub fn buffer_type(&self) -> Result<FramebufferType<'_>, UnknownFramebufferType> {
        let mut reader = Reader::new(&self.buffer);

        match FramebufferKind::from(self.framebuffer_type) {
            FramebufferKind::Indexed => {
                // TODO we can create a struct for this and implement
                //  DynSizedStruct for it to leverage the already existing
                //  functionality
                let num_colors = reader.read_next_u16();

                let palette = {
                    // Ensure the slice can be created without causing UB
                    assert_eq!(size_of::<FramebufferColor>(), 3);
                    let palette_len = num_colors as usize * size_of::<FramebufferColor>();
                    assert!(
                        self.buffer.len() - reader.off >= palette_len,
                        "indexed framebuffer palette must fit in the tag"
                    );
                    // SAFETY: The memory we are using is valid.
                    unsafe {
                        slice::from_raw_parts(
                            reader.current_ptr().cast::<FramebufferColor>(),
                            num_colors as usize,
                        )
                    }
                };
                Ok(FramebufferType::Indexed { palette })
            }
            FramebufferKind::RGB => {
                let red_pos = reader.read_next_u8(); // These refer to the bit positions of the LSB of each field
                let red_mask = reader.read_next_u8(); // And then the length of the field from LSB to MSB
                let green_pos = reader.read_next_u8();
                let green_mask = reader.read_next_u8();
                let blue_pos = reader.read_next_u8();
                let blue_mask = reader.read_next_u8();
                Ok(FramebufferType::RGB {
                    red: FramebufferField {
                        position: red_pos,
                        size: red_mask,
                    },
                    green: FramebufferField {
                        position: green_pos,
                        size: green_mask,
                    },
                    blue: FramebufferField {
                        position: blue_pos,
                        size: blue_mask,
                    },
                })
            }
            FramebufferKind::Text => Ok(FramebufferType::Text),
            FramebufferKind::Custom(val) => Err(UnknownFramebufferType(val)),
        }
    }
}

// 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 FramebufferTag {
    type Header = TagHeader;

    const BASE_SIZE: usize = size_of::<TagHeader>()
        + size_of::<u64>()
        + 3 * size_of::<u32>()
        + 2 * size_of::<u8>()
        + size_of::<u16>();

    fn dst_len(header: &TagHeader) -> usize {
        assert!(header.size as usize >= Self::BASE_SIZE);
        header.size as usize - Self::BASE_SIZE
    }
}

impl Tag for FramebufferTag {
    type IDType = TagType;

    const ID: TagType = TagType::Framebuffer;
}

impl Debug for FramebufferTag {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("FramebufferTag")
            .field("typ", &self.header.typ)
            .field("size", &self.header.size)
            .field("buffer_type", &self.buffer_type())
            .field("address", &self.address)
            .field("pitch", &self.pitch)
            .field("width", &self.width)
            .field("height", &self.height)
            .field("bpp", &self.bpp)
            .finish()
    }
}

impl PartialEq for FramebufferTag {
    fn eq(&self, other: &Self) -> bool {
        self.header == other.header
            && self.address == { other.address }
            && self.pitch == { other.pitch }
            && self.width == { other.width }
            && self.height == { other.height }
            && self.bpp == { other.bpp }
            && self.framebuffer_type == { other.framebuffer_type }
            && self.buffer == other.buffer
    }
}

multiboot2_common::raw_type! {
    /// ABI compatible representation of the framebuffer type of the
    /// framebuffer tag.
    ///
    /// This type matches the binary representation (`u8`).
    pub struct FramebufferTypeRaw(u8);

    /// The kind of framebuffer described by the framebuffer tag according to
    /// the Multiboot2 spec.
    ///
    /// This is a higher level abstraction for [`FramebufferTypeRaw`]. Unlike
    /// [`FramebufferType`], it only describes the kind of framebuffer and
    /// not its payload.
    #[allow(clippy::upper_case_acronyms)]
    pub enum FramebufferKind {
        /// Indexed color.
        Indexed = 0,
        /// Direct RGB color.
        RGB = 1,
        /// EGA Text.
        Text = 2,
        // spec says: there may be more variants in the future
    }
}

impl From<FramebufferType<'_>> for FramebufferTypeRaw {
    fn from(value: FramebufferType) -> Self {
        value.id()
    }
}

/// Structured accessory to the provided framebuffer type that is not ABI
/// compatible.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FramebufferType<'a> {
    /// Indexed color.
    Indexed {
        #[expect(missing_docs)]
        palette: &'a [FramebufferColor],
    },

    /// Direct RGB color.
    #[expect(missing_docs)]
    RGB {
        red: FramebufferField,
        green: FramebufferField,
        blue: FramebufferField,
    },

    /// EGA Text.
    ///
    /// In this case the framebuffer width and height are expressed in
    /// characters and not in pixels.
    ///
    /// The bpp is equal 16 (16 bits per character) and pitch is expressed in bytes per text line.
    Text,
}

impl FramebufferType<'_> {
    #[must_use]
    const fn id(&self) -> FramebufferTypeRaw {
        let kind = match self {
            FramebufferType::Indexed { .. } => FramebufferKind::Indexed,
            FramebufferType::RGB { .. } => FramebufferKind::RGB,
            FramebufferType::Text => FramebufferKind::Text,
        };
        FramebufferTypeRaw::new(kind.val())
    }

    #[must_use]
    #[cfg(feature = "builder")]
    fn serialize(&self) -> alloc::vec::Vec<u8> {
        let mut data = alloc::vec::Vec::new();
        match self {
            FramebufferType::Indexed { palette } => {
                // TODO we can create a struct for this and implement
                //  DynSizedStruct for it to leverage the already existing
                //  functionality
                let num_colors = palette.len() as u16;
                data.extend(&num_colors.to_ne_bytes());
                for color in *palette {
                    let serialized_color = [color.red, color.green, color.blue];
                    data.extend(&serialized_color);
                }
            }
            FramebufferType::RGB { red, green, blue } => data.extend(&[
                red.position,
                red.size,
                green.position,
                green.size,
                blue.position,
                blue.size,
            ]),
            FramebufferType::Text => {}
        }
        data
    }
}

/// An RGB color type field.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct FramebufferField {
    /// Color field position.
    pub position: u8,

    /// Color mask size.
    pub size: u8,
}

/// A framebuffer color descriptor in the palette.
///
/// On the ABI level, multiple values are consecutively without padding bytes.
/// The spec is not precise in that regard, but looking at Limine's and GRUB's
/// source code confirm that.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)] // no align(8) here is correct
pub struct FramebufferColor {
    /// The Red component of the color.
    pub red: u8,

    /// The Green component of the color.
    pub green: u8,

    /// The Blue component of the color.
    pub blue: u8,
}

const _: () = assert!(size_of::<FramebufferColor>() == 3);

/// Error when an unknown framebuffer type is found.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Error)]
#[error("Unknown framebuffer type {0}")]
pub struct UnknownFramebufferType(u8);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::GenericInfoTag;
    use core::borrow::Borrow;
    use multiboot2_common::test_utils::AlignedBytes;

    #[test]
    #[cfg(feature = "builder")]
    fn create_new() {
        let tag = FramebufferTag::new(0x1000, 1, 1024, 1024, 8, FramebufferType::Text);
        // Good test for Miri
        dbg!(tag);

        let tag = FramebufferTag::new(
            0x1000,
            1,
            1024,
            1024,
            8,
            FramebufferType::Indexed {
                palette: &[
                    FramebufferColor {
                        red: 255,
                        green: 255,
                        blue: 255,
                    },
                    FramebufferColor {
                        red: 127,
                        green: 42,
                        blue: 73,
                    },
                ],
            },
        );
        // Good test for Miri
        dbg!(tag);

        let tag = FramebufferTag::new(
            0x1000,
            1,
            1024,
            1024,
            8,
            FramebufferType::RGB {
                red: FramebufferField {
                    position: 0,
                    size: 0,
                },
                green: FramebufferField {
                    position: 10,
                    size: 20,
                },
                blue: FramebufferField {
                    position: 30,
                    size: 40,
                },
            },
        );
        // Good test for Miri
        dbg!(tag);
    }

    /// A tag with a framebuffer type unknown to the specification must be
    /// parsable without undefined behavior and report the unknown type as
    /// an error.
    #[test]
    fn unknown_framebuffer_type_is_not_ub() {
        #[rustfmt::skip]
        let bytes = AlignedBytes::new([
            /* typ = framebuffer */
            8, 0, 0, 0,
            /* size = base size */
            32, 0, 0, 0,
            /* address */
            0, 0, 0, 0, 0, 0, 0, 0,
            /* pitch, width, height */
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            /* bpp, type = 0x40 (unknown), padding */
            0, 0x40, 0, 0,
        ]);
        let tag = GenericInfoTag::ref_from_slice(bytes.borrow())
            .unwrap()
            .cast::<FramebufferTag>();

        assert_eq!(tag.buffer_type(), Err(UnknownFramebufferType(0x40)));
        // The Debug implementation must also cope with unknown values.
        let debug = format!("{tag:?}");
        assert!(debug.contains("UnknownFramebufferType"));
    }

    #[test]
    #[should_panic(expected = "indexed framebuffer palette must fit in the tag")]
    fn indexed_palette_must_fit_in_tag() {
        #[rustfmt::skip]
        let bytes = AlignedBytes::new([
            /* typ = framebuffer */
            8, 0, 0, 0,
            /* size = base size + num_colors + one palette entry */
            37, 0, 0, 0,
            /* address */
            0, 0, 0, 0, 0, 0, 0, 0,
            /* pitch, width, height */
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            /* bpp, type = indexed, padding */
            0, 0, 0, 0,
            /* num_colors = 2 */
            2, 0,
            /* only one 3-byte palette entry follows */
            1, 2, 3,
            /* padding */
            0, 0, 0,
        ]);
        let tag = GenericInfoTag::ref_from_slice(bytes.borrow())
            .unwrap()
            .cast::<FramebufferTag>();

        let _ = tag.buffer_type();
    }
}