image.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. use object::LittleEndian as LE;
  2. use object::Object;
  3. use object::pe::{self, ImageNtHeaders64};
  4. use object::read::pe::{
  5. ExportTarget, ImageNtHeaders, ImageOptionalHeader, Import, ImportTable, ImportThunkList,
  6. PeFile64,
  7. };
  8. use crate::layout::{self, dir};
  9. use crate::{MACHINE_AMD64, PeError};
  10. /// Everything we need to know about a PE32+ image, extracted in one pass.
  11. #[derive(Debug, Clone)]
  12. pub struct ImageInfo {
  13. pub machine: u16,
  14. /// `IMAGE_FILE_HEADER::Characteristics`.
  15. pub characteristics: u16,
  16. pub timestamp: u32,
  17. pub subsystem: u16,
  18. /// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics`.
  19. pub dll_characteristics: u16,
  20. pub image_base: u64,
  21. pub size_of_image: u32,
  22. pub entry_rva: u32,
  23. pub stack_reserve: u64,
  24. pub stack_commit: u64,
  25. pub sections: Vec<SectionInfo>,
  26. pub imports: Vec<ImportModule>,
  27. pub delay_imports: Vec<ImportModule>,
  28. pub exports: Vec<ExportInfo>,
  29. pub tls: Option<TlsInfo>,
  30. pub has_relocations: bool,
  31. pub has_exception_table: bool,
  32. pub has_load_config: bool,
  33. pub codeview: Option<CodeViewInfo>,
  34. }
  35. #[derive(Debug, Clone)]
  36. pub struct SectionInfo {
  37. pub name: String,
  38. pub rva: u32,
  39. pub virtual_size: u32,
  40. pub file_offset: u32,
  41. pub file_size: u32,
  42. pub characteristics: u32,
  43. }
  44. /// One imported DLL and the functions taken from it.
  45. #[derive(Debug, Clone)]
  46. pub struct ImportModule {
  47. /// DLL name exactly as written in the image (case preserved).
  48. pub dll: String,
  49. pub entries: Vec<ImportEntry>,
  50. }
  51. #[derive(Debug, Clone)]
  52. pub struct ImportEntry {
  53. pub symbol: ImportSymbol,
  54. /// RVA of the 8-byte IAT slot the loader must fill in.
  55. pub iat_slot_rva: u32,
  56. }
  57. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
  58. pub enum ImportSymbol {
  59. Name { hint: u16, name: String },
  60. Ordinal(u16),
  61. }
  62. impl std::fmt::Display for ImportSymbol {
  63. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  64. match self {
  65. ImportSymbol::Name { name, .. } => f.write_str(name),
  66. ImportSymbol::Ordinal(o) => write!(f, "#{o}"),
  67. }
  68. }
  69. }
  70. #[derive(Debug, Clone)]
  71. pub struct ExportInfo {
  72. pub name: Option<String>,
  73. pub ordinal: u16,
  74. /// `None` for forwarded exports.
  75. pub rva: Option<u32>,
  76. /// `"dll.name"` or `"dll.#ordinal"` for forwarded exports.
  77. pub forward: Option<String>,
  78. }
  79. #[derive(Debug, Clone)]
  80. pub struct TlsInfo {
  81. /// RVA of `IMAGE_TLS_DIRECTORY64`.
  82. pub directory_rva: u32,
  83. /// VA (at the preferred base) of the callback array, 0 if none.
  84. pub callbacks_va: u64,
  85. /// Callback RVAs, in call order.
  86. pub callback_rvas: Vec<u32>,
  87. }
  88. /// CodeView (RSDS) record: identifies the exact build that produced an image.
  89. #[derive(Debug, Clone)]
  90. pub struct CodeViewInfo {
  91. pub pdb_path: String,
  92. pub guid: [u8; 16],
  93. pub age: u32,
  94. }
  95. impl CodeViewInfo {
  96. /// The key symbol servers use: GUID (Windows byte order) + age.
  97. pub fn symbol_key(&self) -> String {
  98. let g = &self.guid;
  99. let d1 = u32::from_le_bytes([g[0], g[1], g[2], g[3]]);
  100. let d2 = u16::from_le_bytes([g[4], g[5]]);
  101. let d3 = u16::from_le_bytes([g[6], g[7]]);
  102. let mut s = format!("{d1:08X}{d2:04X}{d3:04X}");
  103. for b in &g[8..] {
  104. s.push_str(&format!("{b:02X}"));
  105. }
  106. s.push_str(&format!("{:X}", self.age));
  107. s
  108. }
  109. }
  110. /// Upper bound on TLS callbacks we are willing to walk (defends against garbage).
  111. const MAX_TLS_CALLBACKS: usize = 1024;
  112. impl ImageInfo {
  113. /// Parses a complete PE32+ x86-64 image from its file bytes.
  114. pub fn parse(data: &[u8]) -> Result<Self, PeError> {
  115. let kind = object::FileKind::parse(data)?;
  116. if kind != object::FileKind::Pe64 {
  117. return Err(PeError::Unsupported(format!(
  118. "expected PE32+, found {kind:?}"
  119. )));
  120. }
  121. let file = PeFile64::parse(data)?;
  122. let nt = file.nt_headers();
  123. let fh = nt.file_header();
  124. let opt = nt.optional_header();
  125. let machine = fh.machine.get(LE).0;
  126. if machine != MACHINE_AMD64 {
  127. return Err(PeError::Unsupported(format!(
  128. "machine 0x{machine:04x} is not AMD64"
  129. )));
  130. }
  131. let sections: Vec<SectionInfo> = file
  132. .section_table()
  133. .iter()
  134. .map(|s| SectionInfo {
  135. name: String::from_utf8_lossy(s.raw_name()).into_owned(),
  136. rva: s.virtual_address.get(LE),
  137. virtual_size: s.virtual_size.get(LE),
  138. file_offset: s.pointer_to_raw_data.get(LE),
  139. file_size: s.size_of_raw_data.get(LE),
  140. characteristics: s.characteristics.get(LE).0,
  141. })
  142. .collect();
  143. // Validate section raw-data boundaries before accepting
  144. // the PE image.
  145. for section in &sections {
  146. if section.file_size == 0 {
  147. continue;
  148. }
  149. let start = u64::from(section.file_offset);
  150. let size = u64::from(section.file_size);
  151. let Some(end) = start.checked_add(size) else {
  152. return Err(PeError::Malformed(format!(
  153. "section '{}' has invalid raw-data bounds",
  154. section.name
  155. )));
  156. };
  157. if end > data.len() as u64 {
  158. return Err(PeError::Malformed(format!(
  159. "section '{}' extends beyond file bounds",
  160. section.name
  161. )));
  162. }
  163. }
  164. let dir_present = |index: usize| {
  165. file.data_directory(index)
  166. .is_some_and(|d| d.virtual_address.get(LE) != 0 && d.size.get(LE) != 0)
  167. };
  168. let imports = match file.import_table()? {
  169. Some(table) => parse_imports(&table, opt.size_of_image())?,
  170. None => Vec::new(),
  171. };
  172. let delay_imports = parse_delay_imports(&file, opt.size_of_image())?;
  173. let exports = parse_exports(&file)?;
  174. let tls = parse_tls(&file, data, opt.image_base())?;
  175. let codeview = file.pdb_info()?.map(|cv| CodeViewInfo {
  176. pdb_path: String::from_utf8_lossy(cv.path()).into_owned(),
  177. guid: cv.guid(),
  178. age: cv.age(),
  179. });
  180. Ok(ImageInfo {
  181. machine,
  182. characteristics: fh.characteristics.get(LE).0,
  183. timestamp: fh.time_date_stamp.get(LE),
  184. subsystem: opt.subsystem().0,
  185. dll_characteristics: opt.dll_characteristics().0,
  186. image_base: opt.image_base(),
  187. size_of_image: opt.size_of_image(),
  188. entry_rva: opt.address_of_entry_point(),
  189. stack_reserve: opt.size_of_stack_reserve(),
  190. stack_commit: opt.size_of_stack_commit(),
  191. sections,
  192. imports,
  193. delay_imports,
  194. exports,
  195. tls,
  196. has_relocations: dir_present(dir::BASERELOC)
  197. && !has_flag(
  198. fh.characteristics.get(LE).0,
  199. layout::file_flags::RELOCS_STRIPPED,
  200. ),
  201. has_exception_table: dir_present(dir::EXCEPTION),
  202. has_load_config: dir_present(dir::LOAD_CONFIG),
  203. codeview,
  204. })
  205. }
  206. pub fn is_dll(&self) -> bool {
  207. has_flag(self.characteristics, layout::file_flags::DLL)
  208. }
  209. /// Maps an RVA to an offset in the file, if it is backed by file data.
  210. pub fn rva_to_file_offset(&self, rva: u32) -> Option<u32> {
  211. self.sections.iter().find_map(|s| {
  212. let delta = rva.checked_sub(s.rva)?;
  213. // Raw data may be padded past the virtual size; that padding is
  214. // not part of the section in memory.
  215. let backed = match s.virtual_size {
  216. 0 => s.file_size,
  217. vs => vs.min(s.file_size),
  218. };
  219. // Header values are untrusted: an offset near 4 GiB overflows.
  220. (delta < backed).then(|| s.file_offset.checked_add(delta))?
  221. })
  222. }
  223. pub fn import_count(&self) -> usize {
  224. self.imports.iter().map(|m| m.entries.len()).sum()
  225. }
  226. pub fn subsystem_name(&self) -> &'static str {
  227. use layout::subsystem::*;
  228. match self.subsystem {
  229. WINDOWS_GUI => "windows-gui",
  230. WINDOWS_CUI => "windows-cui",
  231. XBOX => "xbox",
  232. XBOX_CODE_CATALOG => "xbox-code-catalog",
  233. _ => "other",
  234. }
  235. }
  236. }
  237. fn has_flag(value: u16, flag: u16) -> bool {
  238. value & flag != 0
  239. }
  240. fn utf8(bytes: &[u8]) -> String {
  241. String::from_utf8_lossy(bytes).into_owned()
  242. }
  243. fn convert_import(import: Import<'_>) -> ImportSymbol {
  244. match import {
  245. Import::Ordinal(o) => ImportSymbol::Ordinal(o),
  246. Import::Name(hint, name) => ImportSymbol::Name {
  247. hint,
  248. name: utf8(name),
  249. },
  250. }
  251. }
  252. fn parse_imports(
  253. table: &ImportTable<'_>,
  254. size_of_image: u32,
  255. ) -> Result<Vec<ImportModule>, PeError> {
  256. let mut modules = Vec::new();
  257. let mut descriptors = table.descriptors()?;
  258. while let Some(desc) = descriptors.next()? {
  259. let iat_rva = desc.first_thunk.get(LE);
  260. // Prefer the unbound name table; fall back to the IAT for old linkers.
  261. let int_rva = match desc.original_first_thunk.get(LE) {
  262. 0 => iat_rva,
  263. rva => rva,
  264. };
  265. modules.push(ImportModule {
  266. dll: utf8(table.name(desc.name.get(LE))?),
  267. entries: entries(table.thunks(int_rva)?, iat_rva, size_of_image, |t| {
  268. table.import::<ImageNtHeaders64>(t)
  269. })?,
  270. });
  271. }
  272. Ok(modules)
  273. }
  274. fn parse_delay_imports(
  275. file: &PeFile64<'_>,
  276. size_of_image: u32,
  277. ) -> Result<Vec<ImportModule>, PeError> {
  278. let Some(table) = file.delay_load_import_table()? else {
  279. return Ok(Vec::new());
  280. };
  281. let mut modules = Vec::new();
  282. let mut descriptors = table.descriptors()?;
  283. while let Some(desc) = descriptors.next()? {
  284. modules.push(ImportModule {
  285. dll: utf8(table.name(desc.dll_name_rva.get(LE))?),
  286. entries: entries(
  287. table.thunks(desc.import_name_table_rva.get(LE))?,
  288. desc.import_address_table_rva.get(LE),
  289. size_of_image,
  290. |t| table.import::<ImageNtHeaders64>(t),
  291. )?,
  292. });
  293. }
  294. Ok(modules)
  295. }
  296. /// Pairs each name-table entry with its IAT slot. The IAT RVA is not checked
  297. /// by `object`, so every slot is checked to lie inside the image here.
  298. fn entries<'data>(
  299. mut thunks: ImportThunkList<'data>,
  300. iat_rva: u32,
  301. size_of_image: u32,
  302. import: impl Fn(pe::ImageThunkData64) -> object::read::Result<Import<'data>>,
  303. ) -> Result<Vec<ImportEntry>, PeError> {
  304. let mut entries = Vec::new();
  305. while let Some(thunk) = thunks.next::<ImageNtHeaders64>()? {
  306. let iat_slot_rva = u32::try_from(entries.len() * 8)
  307. .ok()
  308. .and_then(|offset| iat_rva.checked_add(offset))
  309. .filter(|&rva| rva.checked_add(8).is_some_and(|end| end <= size_of_image))
  310. .ok_or_else(|| {
  311. PeError::Malformed(format!("IAT at {iat_rva:#x} runs outside the image"))
  312. })?;
  313. entries.push(ImportEntry {
  314. symbol: convert_import(import(thunk)?),
  315. iat_slot_rva,
  316. });
  317. }
  318. Ok(entries)
  319. }
  320. fn parse_exports(file: &PeFile64<'_>) -> Result<Vec<ExportInfo>, PeError> {
  321. let Some(table) = file.export_table()? else {
  322. return Ok(Vec::new());
  323. };
  324. Ok(table
  325. .exports()?
  326. .into_iter()
  327. // An address of 0 marks an unused slot in the address table (a gap
  328. // in the ordinals), not an export at the image base.
  329. .filter(|e| !matches!(e.target, ExportTarget::Address(0)))
  330. .map(|e| {
  331. let (rva, forward) = match e.target {
  332. ExportTarget::Address(rva) => (Some(rva), None),
  333. ExportTarget::ForwardByName(d, n) => {
  334. (None, Some(format!("{}.{}", utf8(d), utf8(n))))
  335. }
  336. ExportTarget::ForwardByOrdinal(d, o) => {
  337. (None, Some(format!("{}.#{}", utf8(d), o.0)))
  338. }
  339. };
  340. ExportInfo {
  341. name: e.name.map(utf8),
  342. ordinal: e.ordinal.0,
  343. rva,
  344. forward,
  345. }
  346. })
  347. .collect())
  348. }
  349. fn parse_tls(
  350. file: &PeFile64<'_>,
  351. data: &[u8],
  352. image_base: u64,
  353. ) -> Result<Option<TlsInfo>, PeError> {
  354. let Some(dd) = file.data_directory(pe::IMAGE_DIRECTORY_ENTRY_TLS) else {
  355. return Ok(None);
  356. };
  357. let directory_rva = dd.virtual_address.get(LE);
  358. if directory_rva == 0 {
  359. return Ok(None);
  360. }
  361. let sections = file.section_table();
  362. let tls = sections
  363. .pe_data_at(data, directory_rva)
  364. .ok_or_else(|| PeError::Malformed("TLS directory outside of sections".into()))?;
  365. let callbacks_va = layout::read_u64(tls, layout::TLS64_ADDRESS_OF_CALLBACKS)
  366. .ok_or_else(|| PeError::Malformed("truncated TLS directory".into()))?;
  367. let mut callback_rvas = Vec::new();
  368. if callbacks_va != 0 {
  369. let array_rva = va_to_rva(callbacks_va, image_base)?;
  370. let array = sections
  371. .pe_data_at(data, array_rva)
  372. .ok_or_else(|| PeError::Malformed("TLS callback array outside of sections".into()))?;
  373. for slot in array.as_chunks::<8>().0.iter().take(MAX_TLS_CALLBACKS) {
  374. let va = u64::from_le_bytes(*slot);
  375. if va == 0 {
  376. break;
  377. }
  378. callback_rvas.push(va_to_rva(va, image_base)?);
  379. }
  380. }
  381. Ok(Some(TlsInfo {
  382. directory_rva,
  383. callbacks_va,
  384. callback_rvas,
  385. }))
  386. }
  387. fn va_to_rva(va: u64, image_base: u64) -> Result<u32, PeError> {
  388. va.checked_sub(image_base)
  389. .and_then(|rva| u32::try_from(rva).ok())
  390. .ok_or_else(|| PeError::Malformed(format!("VA 0x{va:x} is outside the image")))
  391. }
  392. #[cfg(test)]
  393. mod tests {
  394. use super::*;
  395. /// The test binary itself is a real MSVC-linked PE32+ image.
  396. fn own_image() -> Vec<u8> {
  397. std::fs::read(std::env::current_exe().unwrap()).unwrap()
  398. }
  399. #[test]
  400. fn parses_own_test_binary() {
  401. let info = ImageInfo::parse(&own_image()).unwrap();
  402. assert_eq!(info.machine, MACHINE_AMD64);
  403. assert!(!info.is_dll());
  404. assert!(info.entry_rva != 0);
  405. assert!(info.has_exception_table, "x64 images always carry .pdata");
  406. assert!(info.sections.iter().any(|s| s.name.starts_with(".text")));
  407. let kernel32 = info
  408. .imports
  409. .iter()
  410. .find(|m| m.dll.eq_ignore_ascii_case("kernel32.dll"))
  411. .expect("Rust std imports kernel32");
  412. assert!(kernel32.entries.iter().all(|e| e.iat_slot_rva != 0));
  413. // Rust std uses static TLS, so a TLS directory must be present (its
  414. // callback array may legitimately be empty).
  415. assert!(info.tls.is_some());
  416. }
  417. #[test]
  418. fn rva_to_file_offset_maps_entry_point() {
  419. let data = own_image();
  420. let info = ImageInfo::parse(&data).unwrap();
  421. let off = info.rva_to_file_offset(info.entry_rva).unwrap() as usize;
  422. assert!(off < data.len());
  423. }
  424. #[test]
  425. fn rva_to_file_offset_rejects_offsets_past_4_gib() {
  426. let mut info = ImageInfo::parse(&own_image()).unwrap();
  427. let rva = info.sections[0].rva + 0x20;
  428. assert!(info.rva_to_file_offset(rva).is_some());
  429. // Used to overflow (a panic in debug builds, a wrong offset in
  430. // release ones).
  431. info.sections[0].file_offset = u32::MAX - 0x10;
  432. assert_eq!(info.rva_to_file_offset(rva), None);
  433. }
  434. #[test]
  435. fn rejects_garbage_without_panicking() {
  436. assert!(ImageInfo::parse(b"").is_err());
  437. assert!(ImageInfo::parse(b"MZ not really").is_err());
  438. let mut truncated = own_image();
  439. truncated.truncate(0x200);
  440. assert!(ImageInfo::parse(&truncated).is_err());
  441. }
  442. #[test]
  443. fn rejects_iat_outside_image() {
  444. let mut data = own_image();
  445. let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap();
  446. let import_rva = layout::read_u32(&data, dd).unwrap();
  447. let desc = ImageInfo::parse(&data)
  448. .unwrap()
  449. .rva_to_file_offset(import_rva)
  450. .unwrap() as usize;
  451. // First descriptor's FirstThunk, at the 4 GiB limit: used to overflow.
  452. data[desc + 16..desc + 20].copy_from_slice(&0xFFFF_FFF8u32.to_le_bytes());
  453. assert!(matches!(
  454. ImageInfo::parse(&data),
  455. Err(PeError::Malformed(_))
  456. ));
  457. }
  458. /// A minimal PE32+ image: one section at RVA 0x1000 holding `body`, with
  459. /// the export directory (RVA 0x1000, 0x80 bytes) pointing at it.
  460. fn synthetic_image(body: &[u8]) -> Vec<u8> {
  461. let mut d = vec![0u8; 0x200];
  462. d[0..2].copy_from_slice(b"MZ");
  463. d[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
  464. d[0x40..0x44].copy_from_slice(b"PE\0\0");
  465. d[0x44..0x46].copy_from_slice(&MACHINE_AMD64.to_le_bytes());
  466. d[0x46..0x48].copy_from_slice(&1u16.to_le_bytes()); // sections
  467. d[0x54..0x56].copy_from_slice(&240u16.to_le_bytes()); // optional header size
  468. d[0x56..0x58].copy_from_slice(&0x2022u16.to_le_bytes()); // DLL, large address aware
  469. let opt = 0x58;
  470. d[opt..opt + 2].copy_from_slice(&0x20Bu16.to_le_bytes());
  471. d[opt + 24..opt + 32].copy_from_slice(&0x1_8000_0000u64.to_le_bytes());
  472. d[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
  473. d[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
  474. d[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes());
  475. d[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
  476. d[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes());
  477. d[opt + 112..opt + 116].copy_from_slice(&0x1000u32.to_le_bytes());
  478. d[opt + 116..opt + 120].copy_from_slice(&0x80u32.to_le_bytes());
  479. let sec = opt + 240;
  480. d[sec..sec + 6].copy_from_slice(b".edata");
  481. d[sec + 8..sec + 12].copy_from_slice(&0x200u32.to_le_bytes()); // virtual size
  482. d[sec + 12..sec + 16].copy_from_slice(&0x1000u32.to_le_bytes());
  483. d[sec + 16..sec + 20].copy_from_slice(&0x200u32.to_le_bytes()); // raw size
  484. d[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // raw offset
  485. d.extend_from_slice(body);
  486. d.resize(0x400, 0);
  487. d
  488. }
  489. #[test]
  490. fn rejects_section_extending_beyond_file() {
  491. // Create a synthetic PE image.
  492. let mut data = synthetic_image(&vec![0u8; 0x200]);
  493. // Remove the export directory to isolate section validation.
  494. let opt = 0x58;
  495. data[opt + 112..opt + 120].fill(0);
  496. // Verify the baseline PE is accepted.
  497. assert!(
  498. ImageInfo::parse(&data).is_ok(),
  499. "baseline synthetic image must be valid"
  500. );
  501. // The section header starts after the 240-byte optional header.
  502. let sec = opt + 240;
  503. // Declare 4096 bytes of raw section data.
  504. // The actual file contains only 1024 bytes.
  505. data[sec + 16..sec + 20].copy_from_slice(&0x1000u32.to_le_bytes());
  506. // Investigate whether the parser rejects this malformed image.
  507. assert!(
  508. ImageInfo::parse(&data).is_err(),
  509. "section extends beyond physical file bounds"
  510. );
  511. }
  512. #[test]
  513. fn accepts_section_ending_at_file_boundary() {
  514. let mut data = synthetic_image(&vec![0u8; 0x200]);
  515. // Disable the export directory to isolate section validation.
  516. let opt = 0x58;
  517. data[opt + 112..opt + 120].fill(0);
  518. // Raw section: offset 0x200 + size 0x200 = file length 0x400.
  519. let info = ImageInfo::parse(&data);
  520. assert!(
  521. info.is_ok(),
  522. "section ending exactly at EOF should be accepted"
  523. );
  524. }
  525. #[test]
  526. fn accepts_section_with_zero_raw_size() {
  527. let mut data = synthetic_image(&vec![0u8; 0x200]);
  528. // Disable the export directory.
  529. let opt = 0x58;
  530. data[opt + 112..opt + 120].fill(0);
  531. // Section header begins after the optional header.
  532. let sec = opt + 240;
  533. // A section may occupy virtual memory without having raw data.
  534. data[sec + 16..sec + 20].copy_from_slice(&0u32.to_le_bytes());
  535. let info = ImageInfo::parse(&data);
  536. assert!(
  537. info.is_ok(),
  538. "section with zero raw size should be accepted"
  539. );
  540. }
  541. #[test]
  542. fn unused_export_slots_are_not_exports() {
  543. // Ordinal base 1; three address slots: "alpha", an unused hole (0),
  544. // and "gamma". The Windows loader treats address 0 as "not exported".
  545. let mut body = vec![0u8; 0x100];
  546. let put32 =
  547. |b: &mut Vec<u8>, at: usize, v: u32| b[at..at + 4].copy_from_slice(&v.to_le_bytes());
  548. put32(&mut body, 12, 0x1040); // name of the DLL
  549. put32(&mut body, 16, 1); // ordinal base
  550. put32(&mut body, 20, 3); // number of functions
  551. put32(&mut body, 24, 2); // number of names
  552. put32(&mut body, 28, 0x1028); // address table
  553. put32(&mut body, 32, 0x1034); // name pointer table
  554. put32(&mut body, 36, 0x103C); // name ordinal table
  555. put32(&mut body, 0x28, 0x1200);
  556. put32(&mut body, 0x2C, 0);
  557. put32(&mut body, 0x30, 0x1204);
  558. put32(&mut body, 0x34, 0x1044);
  559. put32(&mut body, 0x38, 0x104A);
  560. body[0x3C..0x3E].copy_from_slice(&0u16.to_le_bytes());
  561. body[0x3E..0x40].copy_from_slice(&2u16.to_le_bytes());
  562. body[0x40..0x44].copy_from_slice(b"t.dl");
  563. body[0x44..0x4A].copy_from_slice(b"alpha\0");
  564. body[0x4A..0x50].copy_from_slice(b"gamma\0");
  565. let info = ImageInfo::parse(&synthetic_image(&body)).unwrap();
  566. let exports: Vec<_> = info
  567. .exports
  568. .iter()
  569. .map(|e| (e.name.as_deref(), e.ordinal, e.rva))
  570. .collect();
  571. assert_eq!(
  572. exports,
  573. [
  574. (Some("alpha"), 1, Some(0x1200)),
  575. (Some("gamma"), 3, Some(0x1204))
  576. ]
  577. );
  578. }
  579. }