Patches the kernel image as qemu does.
(
kernel_data: &[u8],
initrd_size: u32,
mem_size: u64,
acpi_data_size: u32,
)
| 117 | |
| 118 | /// Patches the kernel image as qemu does. |
| 119 | fn patch_kernel( |
| 120 | kernel_data: &[u8], |
| 121 | initrd_size: u32, |
| 122 | mem_size: u64, |
| 123 | acpi_data_size: u32, |
| 124 | ) -> Result<Vec<u8>> { |
| 125 | const MIN_KERNEL_LENGTH: usize = 0x1000; |
| 126 | if kernel_data.len() < MIN_KERNEL_LENGTH { |
| 127 | bail!("the kernel image is too short"); |
| 128 | } |
| 129 | |
| 130 | let mut kd = kernel_data.to_vec(); |
| 131 | |
| 132 | let protocol = u16::from_le_bytes(kd[0x206..0x208].try_into().context("impossible failure")?); |
| 133 | |
| 134 | let (real_addr, cmdline_addr) = if protocol < 0x200 || (kd[0x211] & 0x01) == 0 { |
| 135 | (0x90000_u32, 0x9a000_u32) |
| 136 | } else { |
| 137 | (0x10000_u32, 0x20000_u32) |
| 138 | }; |
| 139 | |
| 140 | if protocol >= 0x200 { |
| 141 | kd[0x210] = 0xb0; // type_of_loader = Qemu v0 |
| 142 | } |
| 143 | if protocol >= 0x201 { |
| 144 | kd[0x211] |= 0x80; // loadflags |= CAN_USE_HEAP |
| 145 | let heap_end_ptr = cmdline_addr.saturating_sub(real_addr).saturating_sub(0x200); |
| 146 | kd[0x224..0x228].copy_from_slice(&heap_end_ptr.to_le_bytes()); |
| 147 | } |
| 148 | if protocol >= 0x202 { |
| 149 | kd[0x228..0x22C].copy_from_slice(&cmdline_addr.to_le_bytes()); |
| 150 | } else { |
| 151 | kd[0x20..0x22].copy_from_slice(&0xa33f_u16.to_le_bytes()); |
| 152 | let offset = cmdline_addr.saturating_sub(real_addr) as u16; |
| 153 | kd[0x22..0x24].copy_from_slice(&offset.to_le_bytes()); |
| 154 | } |
| 155 | |
| 156 | if initrd_size > 0 { |
| 157 | if protocol < 0x200 { |
| 158 | bail!("the kernel image is too old for ramdisk"); |
| 159 | } |
| 160 | let mut initrd_max = if protocol >= 0x20c { |
| 161 | let xlf = |
| 162 | u16::from_le_bytes(kd[0x236..0x238].try_into().context("impossible failure")?); |
| 163 | if (xlf & 0x40) != 0 { |
| 164 | u32::MAX |
| 165 | } else { |
| 166 | 0x37ffffff |
| 167 | } |
| 168 | } else if protocol >= 0x203 { |
| 169 | let max = |
| 170 | u32::from_le_bytes(kd[0x22c..0x230].try_into().context("impossible failure")?); |
| 171 | if max == 0 { |
| 172 | 0x37ffffff |
| 173 | } else { |
| 174 | max |
| 175 | } |
| 176 | } else { |