Parse the section table out of a PE image. Returns an empty vec on any malformed/short input (mirrors the C# which returns Array.Empty).
(pe: &[u8])
| 21 | /// Parse the section table out of a PE image. Returns an empty vec on any |
| 22 | /// malformed/short input (mirrors the C# which returns Array.Empty). |
| 23 | pub fn parse(pe: &[u8]) -> Vec<PeSection> { |
| 24 | if pe.len() < 64 { |
| 25 | return Vec::new(); |
| 26 | } |
| 27 | let pe_off = read_i32(pe, 0x3C); |
| 28 | if pe_off < 0 || pe_off as usize + 24 > pe.len() { |
| 29 | return Vec::new(); |
| 30 | } |
| 31 | let pe_off = pe_off as usize; |
| 32 | if pe[pe_off] != b'P' || pe[pe_off + 1] != b'E' { |
| 33 | return Vec::new(); |
| 34 | } |
| 35 | |
| 36 | let num_sections = read_u16(pe, pe_off + 6) as usize; |
| 37 | if num_sections > 96 { |
| 38 | return Vec::new(); |
| 39 | } |
| 40 | let opt_size = read_u16(pe, pe_off + 20) as usize; |
| 41 | let first_section = pe_off + 24 + opt_size; |
| 42 | if first_section > pe.len() { |
| 43 | return Vec::new(); |
| 44 | } |
| 45 | |
| 46 | let mut result = Vec::with_capacity(num_sections); |
| 47 | for i in 0..num_sections { |
| 48 | let off = first_section + i * 40; |
| 49 | if off + 40 > pe.len() { |
| 50 | break; |
| 51 | } |
| 52 | // Section name: up to 8 bytes, NUL-terminated, ASCII. |
| 53 | let mut name_end = 0usize; |
| 54 | for j in 0..8 { |
| 55 | if pe[off + j] == 0 { |
| 56 | break; |
| 57 | } |
| 58 | name_end = j + 1; |
| 59 | } |
| 60 | let name = String::from_utf8_lossy(&pe[off..off + name_end]).into_owned(); |
| 61 | |
| 62 | result.push(PeSection { |
| 63 | name, |
| 64 | virtual_size: read_u32(pe, off + 8), |
| 65 | virtual_address: read_u32(pe, off + 12), |
| 66 | raw_size: read_u32(pe, off + 16), |
| 67 | raw_offset: read_u32(pe, off + 20), |
| 68 | characteristics: read_u32(pe, off + 36), |
| 69 | }); |
| 70 | } |
| 71 | result |
| 72 | } |
| 73 | |
| 74 | pub fn find<'a>(sections: &'a [PeSection], name: &str) -> Option<&'a PeSection> { |
| 75 | sections.iter().find(|s| s.name == name) |