Skip to main content

loader/
pe.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Lays out an x86-64 PE/COFF image, such as a Linux bzImage with an EFI
5//! stub, at its section addresses.
6//!
7//! This supports only images that can run at any base address without
8//! relocation. The Linux EFI stub is position independent and has an empty
9//! relocation directory.
10
11use hvdef::HV_PAGE_SIZE;
12use object::LittleEndian as LE;
13use object::pe;
14use object::read::pe::ImageNtHeaders;
15use object::read::pe::ImageOptionalHeader;
16use object::read::pe::PeFile64;
17use thiserror::Error;
18
19/// An error from laying out a PE/COFF image.
20#[derive(Debug, Error)]
21pub enum Error {
22    #[error("invalid PE32+ image")]
23    Parse(#[source] object::read::Error),
24    #[error("the PE/COFF image is not for x86-64 (machine {0:#x})")]
25    WrongMachine(u16),
26    #[error("the PE/COFF section alignment {0:#x} is not a power of two of at least 4 KiB")]
27    BadSectionAlignment(u32),
28    #[error("the PE/COFF headers lie outside the image")]
29    BadHeaders,
30    #[error("PE/COFF section {0} lies outside the image or the file")]
31    BadSection(usize),
32    #[error("the PE/COFF entry point lies outside the image")]
33    BadEntryPoint,
34    #[error("the PE/COFF image needs relocation, which is not supported")]
35    NeedsRelocation,
36}
37
38/// A PE/COFF image laid out at its section addresses.
39#[derive(Debug)]
40pub struct PeImage {
41    /// The image, `SizeOfImage` bytes long, rounded up to a whole page.
42    pub image: Vec<u8>,
43    /// The entry point, as an offset from the start of the image.
44    pub entry_offset: u64,
45    /// The alignment that the image base needs.
46    pub alignment: u64,
47}
48
49/// Returns `true` if `file` is a PE32+ image.
50pub fn is_pe(file: &[u8]) -> bool {
51    PeFile64::parse(file).is_ok()
52}
53
54/// Lays out `file` at its section addresses.
55pub fn layout(file: &[u8]) -> Result<PeImage, Error> {
56    let pe_file = PeFile64::parse(file).map_err(Error::Parse)?;
57    let headers = pe_file.nt_headers();
58    let machine = headers.file_header().machine.get(LE);
59    if machine != pe::IMAGE_FILE_MACHINE_AMD64 {
60        return Err(Error::WrongMachine(machine));
61    }
62    let optional = headers.optional_header();
63    let section_alignment = optional.section_alignment();
64    if !section_alignment.is_power_of_two() || u64::from(section_alignment) < HV_PAGE_SIZE {
65        return Err(Error::BadSectionAlignment(section_alignment));
66    }
67
68    let size_of_image = optional.size_of_image() as usize;
69    let size_of_headers = optional.size_of_headers() as usize;
70    let headers = file
71        .get(..size_of_headers)
72        .filter(|_| size_of_headers <= size_of_image)
73        .ok_or(Error::BadHeaders)?;
74    let mut image = vec![0; size_of_image.next_multiple_of(HV_PAGE_SIZE as usize)];
75    image[..size_of_headers].copy_from_slice(headers);
76
77    let sections = pe_file.section_table();
78    for (index, section) in sections.iter().enumerate() {
79        // `pe_data` returns the part of the raw data within the virtual size,
80        // without file-alignment padding. The rest of the section is zero.
81        let data = section
82            .pe_data(file)
83            .map_err(|_| Error::BadSection(index))?;
84        let (start, virtual_size) = section.pe_address_range();
85        let start = start as usize;
86        if start
87            .checked_add((virtual_size as usize).max(data.len()))
88            .is_none_or(|end| end > size_of_image)
89        {
90            return Err(Error::BadSection(index));
91        }
92        image[start..start + data.len()].copy_from_slice(data);
93    }
94
95    let entry_offset = optional.address_of_entry_point() as usize;
96    if entry_offset == 0 || entry_offset >= size_of_image {
97        return Err(Error::BadEntryPoint);
98    }
99
100    // Padding entries have type IMAGE_REL_BASED_ABSOLUTE. Any other entry
101    // needs the image to be relocated.
102    if let Some(mut blocks) = pe_file
103        .data_directories()
104        .relocation_blocks(file, &sections)
105        .map_err(|_| Error::NeedsRelocation)?
106    {
107        while let Some(block) = blocks.next().map_err(|_| Error::NeedsRelocation)? {
108            if block
109                .into_iter()
110                .any(|relocation| relocation.typ != pe::IMAGE_REL_BASED_ABSOLUTE)
111            {
112                return Err(Error::NeedsRelocation);
113            }
114        }
115    }
116
117    Ok(PeImage {
118        image,
119        entry_offset: entry_offset as u64,
120        alignment: section_alignment.into(),
121    })
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use core::mem::offset_of;
128    use test_with_tracing::test;
129
130    const PE_OFFSET: usize = 0x40;
131    const OPTIONAL_OFFSET: usize = PE_OFFSET + 4 + size_of::<pe::ImageFileHeader>();
132    const DIRECTORY_COUNT: usize = pe::IMAGE_DIRECTORY_ENTRY_BASERELOC + 1;
133    const SECTIONS_OFFSET: usize = OPTIONAL_OFFSET
134        + size_of::<pe::ImageOptionalHeader64>()
135        + DIRECTORY_COUNT * size_of::<pe::ImageDataDirectory>();
136    const RELOCATION_DIRECTORY: usize = OPTIONAL_OFFSET
137        + size_of::<pe::ImageOptionalHeader64>()
138        + pe::IMAGE_DIRECTORY_ENTRY_BASERELOC * size_of::<pe::ImageDataDirectory>();
139
140    fn put(file: &mut [u8], offset: usize, bytes: &[u8]) {
141        file[offset..offset + bytes.len()].copy_from_slice(bytes);
142    }
143
144    /// Builds an image with a header page, a `.text` section whose raw data
145    /// is longer than its virtual size, and a `.data` section with a BSS tail.
146    fn test_image() -> Vec<u8> {
147        let mut file = vec![0; 0x3000];
148        put(&mut file, 0, &pe::IMAGE_DOS_SIGNATURE.to_le_bytes());
149        put(
150            &mut file,
151            offset_of!(pe::ImageDosHeader, e_lfanew),
152            &(PE_OFFSET as u32).to_le_bytes(),
153        );
154        put(&mut file, PE_OFFSET, &pe::IMAGE_NT_SIGNATURE.to_le_bytes());
155        let coff = PE_OFFSET + 4;
156        put(&mut file, coff, &pe::IMAGE_FILE_MACHINE_AMD64.to_le_bytes());
157        put(
158            &mut file,
159            coff + offset_of!(pe::ImageFileHeader, number_of_sections),
160            &2u16.to_le_bytes(),
161        );
162        let optional_size = (SECTIONS_OFFSET - OPTIONAL_OFFSET) as u16;
163        put(
164            &mut file,
165            coff + offset_of!(pe::ImageFileHeader, size_of_optional_header),
166            &optional_size.to_le_bytes(),
167        );
168        let o = OPTIONAL_OFFSET;
169        put(
170            &mut file,
171            o,
172            &pe::IMAGE_NT_OPTIONAL_HDR64_MAGIC.to_le_bytes(),
173        );
174        put(
175            &mut file,
176            o + offset_of!(pe::ImageOptionalHeader64, address_of_entry_point),
177            &0x1010u32.to_le_bytes(),
178        );
179        put(
180            &mut file,
181            o + offset_of!(pe::ImageOptionalHeader64, section_alignment),
182            &0x1000u32.to_le_bytes(),
183        );
184        put(
185            &mut file,
186            o + offset_of!(pe::ImageOptionalHeader64, file_alignment),
187            &0x200u32.to_le_bytes(),
188        );
189        put(
190            &mut file,
191            o + offset_of!(pe::ImageOptionalHeader64, size_of_image),
192            &0x4000u32.to_le_bytes(),
193        );
194        put(
195            &mut file,
196            o + offset_of!(pe::ImageOptionalHeader64, size_of_headers),
197            &0x1000u32.to_le_bytes(),
198        );
199        put(
200            &mut file,
201            o + offset_of!(pe::ImageOptionalHeader64, number_of_rva_and_sizes),
202            &(DIRECTORY_COUNT as u32).to_le_bytes(),
203        );
204
205        for (index, (va, virtual_size, raw_ptr, raw_size)) in [
206            (0x1000u32, 0x10u32, 0x1000u32, 0x200u32),
207            (0x2000, 0x1800, 0x2000, 0x1000),
208        ]
209        .into_iter()
210        .enumerate()
211        {
212            let s = SECTIONS_OFFSET + index * size_of::<pe::ImageSectionHeader>();
213            put(
214                &mut file,
215                s + offset_of!(pe::ImageSectionHeader, virtual_size),
216                &virtual_size.to_le_bytes(),
217            );
218            put(
219                &mut file,
220                s + offset_of!(pe::ImageSectionHeader, virtual_address),
221                &va.to_le_bytes(),
222            );
223            put(
224                &mut file,
225                s + offset_of!(pe::ImageSectionHeader, size_of_raw_data),
226                &raw_size.to_le_bytes(),
227            );
228            put(
229                &mut file,
230                s + offset_of!(pe::ImageSectionHeader, pointer_to_raw_data),
231                &raw_ptr.to_le_bytes(),
232            );
233        }
234        file[0x1000..0x1200].fill(0xaa);
235        file[0x2000..0x3000].fill(0xbb);
236        file
237    }
238
239    #[test]
240    fn lays_out_sections() {
241        let file = test_image();
242        assert!(is_pe(&file));
243        let pe = layout(&file).unwrap();
244        assert_eq!(pe.image.len(), 0x4000);
245        assert_eq!(pe.entry_offset, 0x1010);
246        assert_eq!(pe.alignment, 0x1000);
247        assert_eq!(pe.image[..0x1000], file[..0x1000]);
248        // Only the virtual size of `.text` is copied.
249        assert!(pe.image[0x1000..0x1010].iter().all(|&b| b == 0xaa));
250        assert!(pe.image[0x1010..0x2000].iter().all(|&b| b == 0));
251        // The `.data` BSS tail is zero.
252        assert!(pe.image[0x2000..0x3000].iter().all(|&b| b == 0xbb));
253        assert!(pe.image[0x3000..].iter().all(|&b| b == 0));
254    }
255
256    #[test]
257    fn rejects_non_pe_and_wrong_machine() {
258        assert!(!is_pe(&[0; 0x100]));
259        assert!(matches!(layout(&[0; 0x100]), Err(Error::Parse(_))));
260        let mut file = test_image();
261        put(
262            &mut file,
263            PE_OFFSET + 4,
264            &pe::IMAGE_FILE_MACHINE_I386.to_le_bytes(),
265        );
266        assert!(matches!(
267            layout(&file),
268            Err(Error::WrongMachine(pe::IMAGE_FILE_MACHINE_I386))
269        ));
270    }
271
272    #[test]
273    fn rejects_section_outside_image() {
274        let mut file = test_image();
275        put(
276            &mut file,
277            SECTIONS_OFFSET
278                + size_of::<pe::ImageSectionHeader>()
279                + offset_of!(pe::ImageSectionHeader, virtual_size),
280            &0x3000u32.to_le_bytes(),
281        );
282        assert!(matches!(layout(&file), Err(Error::BadSection(1))));
283    }
284
285    #[test]
286    fn accepts_padding_relocations_and_rejects_real_ones() {
287        let mut file = test_image();
288        put(&mut file, RELOCATION_DIRECTORY, &0x2100u32.to_le_bytes());
289        put(&mut file, RELOCATION_DIRECTORY + 4, &12u32.to_le_bytes());
290        // One block with two absolute (padding) entries.
291        put(&mut file, 0x2100, &0x1000u32.to_le_bytes());
292        put(&mut file, 0x2104, &12u32.to_le_bytes());
293        put(&mut file, 0x2108, &0x0008u16.to_le_bytes());
294        put(&mut file, 0x210a, &0u16.to_le_bytes());
295        layout(&file).unwrap();
296
297        // A DIR64 entry needs relocation.
298        put(&mut file, 0x2108, &0xa008u16.to_le_bytes());
299        assert!(matches!(layout(&file), Err(Error::NeedsRelocation)));
300    }
301}