header.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. //! Exports item [`HeaderBuilder`].
  2. use crate::builder::information_request::InformationRequestHeaderTagBuilder;
  3. use crate::builder::traits::StructAsBytes;
  4. use crate::HeaderTagISA;
  5. use crate::{
  6. AddressHeaderTag, ConsoleHeaderTag, EfiBootServiceHeaderTag, EndHeaderTag,
  7. EntryAddressHeaderTag, EntryEfi32HeaderTag, EntryEfi64HeaderTag, FramebufferHeaderTag,
  8. ModuleAlignHeaderTag, Multiboot2BasicHeader, RelocatableHeaderTag,
  9. };
  10. use alloc::vec::Vec;
  11. use core::mem::size_of;
  12. use core::ops::Deref;
  13. /// Holds the raw bytes of a boot information built with [`HeaderBuilder`]
  14. /// on the heap. The bytes returned by [`HeaderBytes::as_bytes`] are
  15. /// guaranteed to be properly aligned.
  16. #[derive(Clone, Debug)]
  17. pub struct HeaderBytes {
  18. // Offset into the bytes where the header starts. This is necessary to
  19. // guarantee alignment at the moment.
  20. offset: usize,
  21. structure_len: usize,
  22. bytes: Vec<u8>,
  23. }
  24. impl HeaderBytes {
  25. /// Returns the bytes. They are guaranteed to be correctly aligned.
  26. pub fn as_bytes(&self) -> &[u8] {
  27. let slice = &self.bytes[self.offset..self.offset + self.structure_len];
  28. // At this point, the alignment is guaranteed. If not, something is
  29. // broken fundamentally.
  30. assert_eq!(slice.as_ptr().align_offset(8), 0);
  31. slice
  32. }
  33. }
  34. impl Deref for HeaderBytes {
  35. type Target = [u8];
  36. fn deref(&self) -> &Self::Target {
  37. self.as_bytes()
  38. }
  39. }
  40. /// Builder to construct a valid Multiboot2 header dynamically at runtime.
  41. /// The tags will appear in the order of their corresponding enumeration,
  42. /// except for the END tag.
  43. #[derive(Clone, Debug, PartialEq, Eq)]
  44. pub struct HeaderBuilder {
  45. arch: HeaderTagISA,
  46. // first
  47. information_request_tag: Option<InformationRequestHeaderTagBuilder>,
  48. // second
  49. address_tag: Option<AddressHeaderTag>,
  50. // third
  51. entry_tag: Option<EntryAddressHeaderTag>,
  52. // fourth
  53. console_tag: Option<ConsoleHeaderTag>,
  54. // fifth
  55. framebuffer_tag: Option<FramebufferHeaderTag>,
  56. // sixth
  57. module_align_tag: Option<ModuleAlignHeaderTag>,
  58. // seventh
  59. efi_bs_tag: Option<EfiBootServiceHeaderTag>,
  60. // eighth
  61. efi_32_tag: Option<EntryEfi32HeaderTag>,
  62. // ninth
  63. efi_64_tag: Option<EntryEfi64HeaderTag>,
  64. // tenth (last)
  65. relocatable_tag: Option<RelocatableHeaderTag>,
  66. }
  67. impl HeaderBuilder {
  68. pub const fn new(arch: HeaderTagISA) -> Self {
  69. Self {
  70. arch,
  71. information_request_tag: None,
  72. address_tag: None,
  73. entry_tag: None,
  74. console_tag: None,
  75. framebuffer_tag: None,
  76. module_align_tag: None,
  77. efi_bs_tag: None,
  78. efi_32_tag: None,
  79. efi_64_tag: None,
  80. relocatable_tag: None,
  81. }
  82. }
  83. /// Returns the size, if the value is a multiple of 8 or returns
  84. /// the next number that is a multiple of 8. With this, one can
  85. /// easily calculate the size of a Multiboot2 header, where
  86. /// all the tags are 8-byte aligned.
  87. const fn size_or_up_aligned(size: usize) -> usize {
  88. (size + 7) & !7
  89. }
  90. /// Returns the expected length of the Multiboot2 header, when the
  91. /// [`Self::build`]-method gets called.
  92. pub fn expected_len(&self) -> usize {
  93. let base_len = size_of::<Multiboot2BasicHeader>();
  94. // size_or_up_aligned not required, because basic header length is 16 and the
  95. // begin is 8 byte aligned => first tag automatically 8 byte aligned
  96. let mut len = Self::size_or_up_aligned(base_len);
  97. if let Some(tag_builder) = self.information_request_tag.as_ref() {
  98. // we use size_or_up_aligned, because each tag will start at an 8 byte aligned address.
  99. // Attention: expected len from builder, not the size of the builder itself!
  100. len += Self::size_or_up_aligned(tag_builder.expected_len())
  101. }
  102. if self.address_tag.is_some() {
  103. // we use size_or_up_aligned, because each tag will start at an 8 byte aligned address
  104. len += Self::size_or_up_aligned(size_of::<AddressHeaderTag>())
  105. }
  106. if self.entry_tag.is_some() {
  107. len += Self::size_or_up_aligned(size_of::<EntryAddressHeaderTag>())
  108. }
  109. if self.console_tag.is_some() {
  110. len += Self::size_or_up_aligned(size_of::<ConsoleHeaderTag>())
  111. }
  112. if self.framebuffer_tag.is_some() {
  113. len += Self::size_or_up_aligned(size_of::<FramebufferHeaderTag>())
  114. }
  115. if self.module_align_tag.is_some() {
  116. len += Self::size_or_up_aligned(size_of::<ModuleAlignHeaderTag>())
  117. }
  118. if self.efi_bs_tag.is_some() {
  119. len += Self::size_or_up_aligned(size_of::<EfiBootServiceHeaderTag>())
  120. }
  121. if self.efi_32_tag.is_some() {
  122. len += Self::size_or_up_aligned(size_of::<EntryEfi32HeaderTag>())
  123. }
  124. if self.efi_64_tag.is_some() {
  125. len += Self::size_or_up_aligned(size_of::<EntryEfi64HeaderTag>())
  126. }
  127. if self.relocatable_tag.is_some() {
  128. len += Self::size_or_up_aligned(size_of::<RelocatableHeaderTag>())
  129. }
  130. // only here size_or_up_aligned is not important, because it is the last tag
  131. len += size_of::<EndHeaderTag>();
  132. len
  133. }
  134. /// Adds the bytes of a tag to the final Multiboot2 header byte vector.
  135. fn build_add_bytes(dest: &mut Vec<u8>, source: &[u8], is_end_tag: bool) {
  136. let vec_next_write_ptr = unsafe { dest.as_ptr().add(dest.len()) };
  137. // At this point, the alignment is guaranteed. If not, something is
  138. // broken fundamentally.
  139. assert_eq!(vec_next_write_ptr.align_offset(8), 0);
  140. dest.extend(source);
  141. if !is_end_tag {
  142. let size = source.len();
  143. let size_to_8_align = Self::size_or_up_aligned(size);
  144. let size_to_8_align_diff = size_to_8_align - size;
  145. // fill zeroes so that next data block is 8-byte aligned
  146. dest.extend([0].repeat(size_to_8_align_diff));
  147. }
  148. }
  149. /// Constructs the bytes for a valid Multiboot2 header with the given properties.
  150. pub fn build(mut self) -> HeaderBytes {
  151. const ALIGN: usize = 8;
  152. // PHASE 1/2: Prepare Vector
  153. // We allocate more than necessary so that we can ensure an correct
  154. // alignment within this data.
  155. let expected_len = self.expected_len();
  156. let alloc_len = expected_len + 7;
  157. let mut bytes = Vec::<u8>::with_capacity(alloc_len);
  158. // Pointer to check that no relocation happened.
  159. let alloc_ptr = bytes.as_ptr();
  160. // As long as there is no nice way in stable Rust to guarantee the
  161. // alignment of a vector, I add zero bytes at the beginning and the
  162. // header might not start at the start of the allocation.
  163. //
  164. // Unfortunately, it is not possible to reliably test this in a unit
  165. // test as long as the allocator_api feature is not stable.
  166. // Due to my manual testing, however, it works.
  167. let offset = bytes.as_ptr().align_offset(ALIGN);
  168. bytes.extend([0].repeat(offset));
  169. // -----------------------------------------------
  170. // PHASE 2/2: Add Tags
  171. self.build_add_tags(&mut bytes);
  172. assert_eq!(
  173. alloc_ptr,
  174. bytes.as_ptr(),
  175. "Vector was reallocated. Alignment of header probably broken!"
  176. );
  177. assert_eq!(
  178. bytes[0..offset].iter().sum::<u8>(),
  179. 0,
  180. "The offset to alignment area should be zero."
  181. );
  182. HeaderBytes {
  183. offset,
  184. bytes,
  185. structure_len: expected_len,
  186. }
  187. }
  188. /// Helper method that adds all the tags to the given vector.
  189. fn build_add_tags(&mut self, bytes: &mut Vec<u8>) {
  190. Self::build_add_bytes(
  191. bytes,
  192. // important that we write the correct expected length into the header!
  193. &Multiboot2BasicHeader::new(self.arch, self.expected_len() as u32).struct_as_bytes(),
  194. false,
  195. );
  196. if let Some(irs) = self.information_request_tag.clone() {
  197. Self::build_add_bytes(bytes, &irs.build(), false)
  198. }
  199. if let Some(tag) = self.address_tag.as_ref() {
  200. Self::build_add_bytes(bytes, &tag.struct_as_bytes(), false)
  201. }
  202. if let Some(tag) = self.entry_tag.as_ref() {
  203. Self::build_add_bytes(bytes, &tag.struct_as_bytes(), false)
  204. }
  205. if let Some(tag) = self.console_tag.as_ref() {
  206. Self::build_add_bytes(bytes, &tag.struct_as_bytes(), false)
  207. }
  208. if let Some(tag) = self.framebuffer_tag.as_ref() {
  209. Self::build_add_bytes(bytes, &tag.struct_as_bytes(), false)
  210. }
  211. if let Some(tag) = self.module_align_tag.as_ref() {
  212. Self::build_add_bytes(bytes, &tag.struct_as_bytes(), false)
  213. }
  214. if let Some(tag) = self.efi_bs_tag.as_ref() {
  215. Self::build_add_bytes(bytes, &tag.struct_as_bytes(), false)
  216. }
  217. if let Some(tag) = self.efi_32_tag.as_ref() {
  218. Self::build_add_bytes(bytes, &tag.struct_as_bytes(), false)
  219. }
  220. if let Some(tag) = self.efi_64_tag.as_ref() {
  221. Self::build_add_bytes(bytes, &tag.struct_as_bytes(), false)
  222. }
  223. if let Some(tag) = self.relocatable_tag.as_ref() {
  224. Self::build_add_bytes(bytes, &tag.struct_as_bytes(), false)
  225. }
  226. Self::build_add_bytes(bytes, &EndHeaderTag::new().struct_as_bytes(), true);
  227. }
  228. // clippy thinks this can be a const fn but the compiler denies it
  229. #[allow(clippy::missing_const_for_fn)]
  230. pub fn information_request_tag(
  231. mut self,
  232. information_request_tag: InformationRequestHeaderTagBuilder,
  233. ) -> Self {
  234. self.information_request_tag = Some(information_request_tag);
  235. self
  236. }
  237. pub const fn address_tag(mut self, address_tag: AddressHeaderTag) -> Self {
  238. self.address_tag = Some(address_tag);
  239. self
  240. }
  241. pub const fn entry_tag(mut self, entry_tag: EntryAddressHeaderTag) -> Self {
  242. self.entry_tag = Some(entry_tag);
  243. self
  244. }
  245. pub const fn console_tag(mut self, console_tag: ConsoleHeaderTag) -> Self {
  246. self.console_tag = Some(console_tag);
  247. self
  248. }
  249. pub const fn framebuffer_tag(mut self, framebuffer_tag: FramebufferHeaderTag) -> Self {
  250. self.framebuffer_tag = Some(framebuffer_tag);
  251. self
  252. }
  253. pub const fn module_align_tag(mut self, module_align_tag: ModuleAlignHeaderTag) -> Self {
  254. self.module_align_tag = Some(module_align_tag);
  255. self
  256. }
  257. pub const fn efi_bs_tag(mut self, efi_bs_tag: EfiBootServiceHeaderTag) -> Self {
  258. self.efi_bs_tag = Some(efi_bs_tag);
  259. self
  260. }
  261. pub const fn efi_32_tag(mut self, efi_32_tag: EntryEfi32HeaderTag) -> Self {
  262. self.efi_32_tag = Some(efi_32_tag);
  263. self
  264. }
  265. pub const fn efi_64_tag(mut self, efi_64_tag: EntryEfi64HeaderTag) -> Self {
  266. self.efi_64_tag = Some(efi_64_tag);
  267. self
  268. }
  269. pub const fn relocatable_tag(mut self, relocatable_tag: RelocatableHeaderTag) -> Self {
  270. self.relocatable_tag = Some(relocatable_tag);
  271. self
  272. }
  273. }
  274. #[cfg(test)]
  275. mod tests {
  276. use crate::builder::header::HeaderBuilder;
  277. use crate::builder::information_request::InformationRequestHeaderTagBuilder;
  278. use crate::{
  279. HeaderTagFlag, HeaderTagISA, MbiTagType, Multiboot2Header, RelocatableHeaderTag,
  280. RelocatableHeaderTagPreference,
  281. };
  282. fn create_builder() -> HeaderBuilder {
  283. let builder = HeaderBuilder::new(HeaderTagISA::I386);
  284. // Multiboot2 basic header + end tag
  285. let mut expected_len = 16 + 8;
  286. assert_eq!(builder.expected_len(), expected_len);
  287. // add information request tag
  288. let ifr_builder =
  289. InformationRequestHeaderTagBuilder::new(HeaderTagFlag::Required).add_irs(&[
  290. MbiTagType::EfiMmap,
  291. MbiTagType::Cmdline,
  292. MbiTagType::ElfSections,
  293. ]);
  294. let ifr_tag_size_with_padding = ifr_builder.expected_len() + 4;
  295. assert_eq!(
  296. ifr_tag_size_with_padding % 8,
  297. 0,
  298. "the length of the IFR tag with padding must be a multiple of 8"
  299. );
  300. expected_len += ifr_tag_size_with_padding;
  301. let builder = builder.information_request_tag(ifr_builder);
  302. assert_eq!(builder.expected_len(), expected_len);
  303. let builder = builder.relocatable_tag(RelocatableHeaderTag::new(
  304. HeaderTagFlag::Required,
  305. 0x1337,
  306. 0xdeadbeef,
  307. 4096,
  308. RelocatableHeaderTagPreference::None,
  309. ));
  310. expected_len += 0x18;
  311. assert_eq!(builder.expected_len(), expected_len);
  312. builder
  313. }
  314. #[test]
  315. fn test_size_or_up_aligned() {
  316. assert_eq!(0, HeaderBuilder::size_or_up_aligned(0));
  317. assert_eq!(8, HeaderBuilder::size_or_up_aligned(1));
  318. assert_eq!(8, HeaderBuilder::size_or_up_aligned(8));
  319. assert_eq!(16, HeaderBuilder::size_or_up_aligned(9));
  320. }
  321. /// Test of the `build` method in isolation specifically for miri to check
  322. /// for memory issues.
  323. #[test]
  324. fn test_builder_miri() {
  325. let builder = create_builder();
  326. let expected_len = builder.expected_len();
  327. assert_eq!(builder.build().as_bytes().len(), expected_len);
  328. }
  329. #[test]
  330. #[cfg_attr(miri, ignore)]
  331. fn test_builder() {
  332. // Step 1/2: Build Header
  333. let mb2_hdr_data = create_builder().build();
  334. // Step 2/2: Test the built Header
  335. let mb2_hdr = mb2_hdr_data.as_ptr().cast();
  336. let mb2_hdr = unsafe { Multiboot2Header::load(mb2_hdr) }
  337. .expect("the generated header to be loadable");
  338. println!("{:#?}", mb2_hdr);
  339. assert_eq!(
  340. mb2_hdr.relocatable_tag().unwrap().flags(),
  341. HeaderTagFlag::Required
  342. );
  343. assert_eq!(mb2_hdr.relocatable_tag().unwrap().min_addr(), 0x1337);
  344. assert_eq!(mb2_hdr.relocatable_tag().unwrap().max_addr(), 0xdeadbeef);
  345. assert_eq!(mb2_hdr.relocatable_tag().unwrap().align(), 4096);
  346. assert_eq!(
  347. mb2_hdr.relocatable_tag().unwrap().preference(),
  348. RelocatableHeaderTagPreference::None
  349. );
  350. // Printing the header transitively ensures that a lot of stuff works.
  351. println!("{:#?}", mb2_hdr);
  352. /* you can write the binary to a file and a tool such as crate "bootinfo"
  353. will be able to fully parse the MB2 header
  354. let mut file = std::file::File::create("mb2_hdr.bin").unwrap();
  355. use std::io::Write;
  356. file.write_all(mb2_hdr_data.as_slice()).unwrap();*/
  357. }
  358. }