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

use crate::{Tag, TagTrait, TagType, TagTypeId};
use core::fmt::Debug;
use core::mem::size_of;
use core::slice;
use derive_more::Display;
#[cfg(feature = "builder")]
use {crate::builder::AsBytes, crate::builder::BoxedDst, alloc::vec::Vec};

/// Helper struct to read bytes from a raw pointer and increase the pointer
/// automatically.
struct Reader {
    ptr: *const u8,
    off: usize,
}

impl Reader {
    fn new<T>(ptr: *const T) -> Reader {
        Reader {
            ptr: ptr as *const u8,
            off: 0,
        }
    }

    fn read_u8(&mut self) -> u8 {
        self.off += 1;
        unsafe { *self.ptr.add(self.off - 1) }
    }

    fn read_u16(&mut self) -> u16 {
        self.read_u8() as u16 | (self.read_u8() as u16) << 8
    }

    fn read_u32(&mut self) -> u32 {
        self.read_u16() as u32 | (self.read_u16() as u32) << 16
    }

    fn current_address(&self) -> usize {
        unsafe { self.ptr.add(self.off) as usize }
    }
}

const METADATA_SIZE: usize = size_of::<TagTypeId>()
    + 4 * size_of::<u32>()
    + size_of::<u64>()
    + size_of::<u16>()
    + 2 * size_of::<u8>();

/// The VBE Framebuffer information tag.
#[derive(ptr_meta::Pointee, Eq)]
#[repr(C)]
pub struct FramebufferTag {
    typ: TagTypeId,
    size: u32,

    /// Contains framebuffer physical address.
    ///
    /// This field is 64-bit wide but 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, one of: `Indexed`, `RGB` or `Text`.
    type_no: u8,

    // In the multiboot spec, it has this listed as a u8 _NOT_ a u16.
    // Reading the GRUB2 source code reveals it is in fact a u16.
    _reserved: u16,

    buffer: [u8],
}

impl FramebufferTag {
    #[cfg(feature = "builder")]
    pub fn new(
        address: u64,
        pitch: u32,
        width: u32,
        height: u32,
        bpp: u8,
        buffer_type: FramebufferType,
    ) -> BoxedDst<Self> {
        let mut bytes: Vec<u8> = address.to_le_bytes().into();
        bytes.extend(pitch.to_le_bytes());
        bytes.extend(width.to_le_bytes());
        bytes.extend(height.to_le_bytes());
        bytes.extend(bpp.to_le_bytes());
        bytes.extend(buffer_type.to_bytes());
        BoxedDst::new(&bytes)
    }

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

    /// Contains the pitch in bytes.
    pub fn pitch(&self) -> u32 {
        self.pitch
    }

    /// Contains framebuffer width in pixels.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Contains framebuffer height in pixels.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Contains number of bits per pixel.
    pub 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.as_ptr());
        let typ = FramebufferTypeId::try_from(self.type_no)?;
        match typ {
            FramebufferTypeId::Indexed => {
                let num_colors = reader.read_u32();
                let palette = unsafe {
                    slice::from_raw_parts(
                        reader.current_address() as *const FramebufferColor,
                        num_colors as usize,
                    )
                } as &'static [FramebufferColor];
                Ok(FramebufferType::Indexed { palette })
            }
            FramebufferTypeId::RGB => {
                let red_pos = reader.read_u8(); // These refer to the bit positions of the LSB of each field
                let red_mask = reader.read_u8(); // And then the length of the field from LSB to MSB
                let green_pos = reader.read_u8();
                let green_mask = reader.read_u8();
                let blue_pos = reader.read_u8();
                let blue_mask = reader.read_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,
                    },
                })
            }
            FramebufferTypeId::Text => Ok(FramebufferType::Text),
        }
    }
}

impl TagTrait for FramebufferTag {
    const ID: TagType = TagType::Framebuffer;

    fn dst_size(base_tag: &Tag) -> usize {
        assert!(base_tag.size as usize >= METADATA_SIZE);
        base_tag.size as usize - METADATA_SIZE
    }
}

impl Debug for FramebufferTag {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("FramebufferTag")
            .field("typ", &{ self.typ })
            .field("size", &{ self.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.typ } == { other.typ }
            && { self.size } == { other.size }
            && { self.address } == { other.address }
            && { self.pitch } == { other.pitch }
            && { self.width } == { other.width }
            && { self.height } == { other.height }
            && { self.bpp } == { other.bpp }
            && { self.type_no } == { other.type_no }
            && self.buffer == other.buffer)
    }
}

/// Helper struct for [`FramebufferType`].
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
#[allow(clippy::upper_case_acronyms)]
enum FramebufferTypeId {
    Indexed = 0,
    RGB = 1,
    Text = 2,
    // spec says: there may be more variants in the future
}

impl TryFrom<u8> for FramebufferTypeId {
    type Error = UnknownFramebufferType;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::Indexed),
            1 => Ok(Self::RGB),
            2 => Ok(Self::Text),
            val => Err(UnknownFramebufferType(val)),
        }
    }
}

/// The type of framebuffer.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FramebufferType<'a> {
    /// Indexed color.
    Indexed {
        #[allow(missing_docs)]
        palette: &'a [FramebufferColor],
    },

    /// Direct RGB color.
    #[allow(missing_docs)]
    #[allow(clippy::upper_case_acronyms)]
    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,
}

#[cfg(feature = "builder")]
impl<'a> FramebufferType<'a> {
    fn to_bytes(&self) -> Vec<u8> {
        let mut v = Vec::new();
        match self {
            FramebufferType::Indexed { palette } => {
                v.extend(0u8.to_le_bytes()); // type
                v.extend(0u16.to_le_bytes()); // reserved
                v.extend((palette.len() as u32).to_le_bytes());
                for color in palette.iter() {
                    v.extend(color.as_bytes());
                }
            }
            FramebufferType::RGB { red, green, blue } => {
                v.extend(1u8.to_le_bytes()); // type
                v.extend(0u16.to_le_bytes()); // reserved
                v.extend(red.as_bytes());
                v.extend(green.as_bytes());
                v.extend(blue.as_bytes());
            }
            FramebufferType::Text => {
                v.extend(2u8.to_le_bytes()); // type
                v.extend(0u16.to_le_bytes()); // reserved
            }
        }
        v
    }
}

/// 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,
}

#[cfg(feature = "builder")]
impl AsBytes for FramebufferField {}

/// A framebuffer color descriptor in the palette.
#[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,
}

#[cfg(feature = "builder")]
impl AsBytes for FramebufferColor {}

/// Error when an unknown [`FramebufferTypeId`] is found.
#[derive(Debug, Copy, Clone, Display, PartialEq, Eq)]
#[display(fmt = "Unknown framebuffer type {}", _0)]
pub struct UnknownFramebufferType(u8);

#[cfg(feature = "unstable")]
impl core::error::Error for UnknownFramebufferType {}

#[cfg(test)]
mod tests {
    use super::*;

    // Compile time test
    #[test]
    fn test_size() {
        assert_eq!(size_of::<FramebufferColor>(), 3)
    }
}