image.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 = 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. let dir_present = |index: usize| {
  144. file.data_directory(index)
  145. .is_some_and(|d| d.virtual_address.get(LE) != 0 && d.size.get(LE) != 0)
  146. };
  147. let imports = match file.import_table()? {
  148. Some(table) => parse_imports(&table, opt.size_of_image())?,
  149. None => Vec::new(),
  150. };
  151. let delay_imports = parse_delay_imports(&file, opt.size_of_image())?;
  152. let exports = parse_exports(&file)?;
  153. let tls = parse_tls(&file, data, opt.image_base())?;
  154. let codeview = file.pdb_info()?.map(|cv| CodeViewInfo {
  155. pdb_path: String::from_utf8_lossy(cv.path()).into_owned(),
  156. guid: cv.guid(),
  157. age: cv.age(),
  158. });
  159. Ok(ImageInfo {
  160. machine,
  161. characteristics: fh.characteristics.get(LE).0,
  162. timestamp: fh.time_date_stamp.get(LE),
  163. subsystem: opt.subsystem().0,
  164. dll_characteristics: opt.dll_characteristics().0,
  165. image_base: opt.image_base(),
  166. size_of_image: opt.size_of_image(),
  167. entry_rva: opt.address_of_entry_point(),
  168. stack_reserve: opt.size_of_stack_reserve(),
  169. stack_commit: opt.size_of_stack_commit(),
  170. sections,
  171. imports,
  172. delay_imports,
  173. exports,
  174. tls,
  175. has_relocations: dir_present(dir::BASERELOC)
  176. && !has_flag(
  177. fh.characteristics.get(LE).0,
  178. layout::file_flags::RELOCS_STRIPPED,
  179. ),
  180. has_exception_table: dir_present(dir::EXCEPTION),
  181. has_load_config: dir_present(dir::LOAD_CONFIG),
  182. codeview,
  183. })
  184. }
  185. pub fn is_dll(&self) -> bool {
  186. has_flag(self.characteristics, layout::file_flags::DLL)
  187. }
  188. /// Maps an RVA to an offset in the file, if it is backed by file data.
  189. pub fn rva_to_file_offset(&self, rva: u32) -> Option<u32> {
  190. self.sections.iter().find_map(|s| {
  191. let delta = rva.checked_sub(s.rva)?;
  192. // Raw data may be padded past the virtual size; that padding is
  193. // not part of the section in memory.
  194. let backed = match s.virtual_size {
  195. 0 => s.file_size,
  196. vs => vs.min(s.file_size),
  197. };
  198. // Header values are untrusted: an offset near 4 GiB overflows.
  199. (delta < backed).then(|| s.file_offset.checked_add(delta))?
  200. })
  201. }
  202. pub fn import_count(&self) -> usize {
  203. self.imports.iter().map(|m| m.entries.len()).sum()
  204. }
  205. pub fn subsystem_name(&self) -> &'static str {
  206. use layout::subsystem::*;
  207. match self.subsystem {
  208. WINDOWS_GUI => "windows-gui",
  209. WINDOWS_CUI => "windows-cui",
  210. XBOX => "xbox",
  211. XBOX_CODE_CATALOG => "xbox-code-catalog",
  212. _ => "other",
  213. }
  214. }
  215. }
  216. fn has_flag(value: u16, flag: u16) -> bool {
  217. value & flag != 0
  218. }
  219. fn utf8(bytes: &[u8]) -> String {
  220. String::from_utf8_lossy(bytes).into_owned()
  221. }
  222. fn convert_import(import: Import<'_>) -> ImportSymbol {
  223. match import {
  224. Import::Ordinal(o) => ImportSymbol::Ordinal(o),
  225. Import::Name(hint, name) => ImportSymbol::Name {
  226. hint,
  227. name: utf8(name),
  228. },
  229. }
  230. }
  231. fn parse_imports(
  232. table: &ImportTable<'_>,
  233. size_of_image: u32,
  234. ) -> Result<Vec<ImportModule>, PeError> {
  235. let mut modules = Vec::new();
  236. let mut descriptors = table.descriptors()?;
  237. while let Some(desc) = descriptors.next()? {
  238. let iat_rva = desc.first_thunk.get(LE);
  239. // Prefer the unbound name table; fall back to the IAT for old linkers.
  240. let int_rva = match desc.original_first_thunk.get(LE) {
  241. 0 => iat_rva,
  242. rva => rva,
  243. };
  244. modules.push(ImportModule {
  245. dll: utf8(table.name(desc.name.get(LE))?),
  246. entries: entries(table.thunks(int_rva)?, iat_rva, size_of_image, |t| {
  247. table.import::<ImageNtHeaders64>(t)
  248. })?,
  249. });
  250. }
  251. Ok(modules)
  252. }
  253. fn parse_delay_imports(
  254. file: &PeFile64<'_>,
  255. size_of_image: u32,
  256. ) -> Result<Vec<ImportModule>, PeError> {
  257. let Some(table) = file.delay_load_import_table()? else {
  258. return Ok(Vec::new());
  259. };
  260. let mut modules = Vec::new();
  261. let mut descriptors = table.descriptors()?;
  262. while let Some(desc) = descriptors.next()? {
  263. modules.push(ImportModule {
  264. dll: utf8(table.name(desc.dll_name_rva.get(LE))?),
  265. entries: entries(
  266. table.thunks(desc.import_name_table_rva.get(LE))?,
  267. desc.import_address_table_rva.get(LE),
  268. size_of_image,
  269. |t| table.import::<ImageNtHeaders64>(t),
  270. )?,
  271. });
  272. }
  273. Ok(modules)
  274. }
  275. /// Pairs each name-table entry with its IAT slot. The IAT RVA is not checked
  276. /// by `object`, so every slot is checked to lie inside the image here.
  277. fn entries<'data>(
  278. mut thunks: ImportThunkList<'data>,
  279. iat_rva: u32,
  280. size_of_image: u32,
  281. import: impl Fn(pe::ImageThunkData64) -> object::read::Result<Import<'data>>,
  282. ) -> Result<Vec<ImportEntry>, PeError> {
  283. let mut entries = Vec::new();
  284. while let Some(thunk) = thunks.next::<ImageNtHeaders64>()? {
  285. let iat_slot_rva = u32::try_from(entries.len() * 8)
  286. .ok()
  287. .and_then(|offset| iat_rva.checked_add(offset))
  288. .filter(|&rva| rva.checked_add(8).is_some_and(|end| end <= size_of_image))
  289. .ok_or_else(|| {
  290. PeError::Malformed(format!("IAT at {iat_rva:#x} runs outside the image"))
  291. })?;
  292. entries.push(ImportEntry {
  293. symbol: convert_import(import(thunk)?),
  294. iat_slot_rva,
  295. });
  296. }
  297. Ok(entries)
  298. }
  299. fn parse_exports(file: &PeFile64<'_>) -> Result<Vec<ExportInfo>, PeError> {
  300. let Some(table) = file.export_table()? else {
  301. return Ok(Vec::new());
  302. };
  303. Ok(table
  304. .exports()?
  305. .into_iter()
  306. // An address of 0 marks an unused slot in the address table (a gap
  307. // in the ordinals), not an export at the image base.
  308. .filter(|e| !matches!(e.target, ExportTarget::Address(0)))
  309. .map(|e| {
  310. let (rva, forward) = match e.target {
  311. ExportTarget::Address(rva) => (Some(rva), None),
  312. ExportTarget::ForwardByName(d, n) => {
  313. (None, Some(format!("{}.{}", utf8(d), utf8(n))))
  314. }
  315. ExportTarget::ForwardByOrdinal(d, o) => {
  316. (None, Some(format!("{}.#{}", utf8(d), o.0)))
  317. }
  318. };
  319. ExportInfo {
  320. name: e.name.map(utf8),
  321. ordinal: e.ordinal.0,
  322. rva,
  323. forward,
  324. }
  325. })
  326. .collect())
  327. }
  328. fn parse_tls(
  329. file: &PeFile64<'_>,
  330. data: &[u8],
  331. image_base: u64,
  332. ) -> Result<Option<TlsInfo>, PeError> {
  333. let Some(dd) = file.data_directory(pe::IMAGE_DIRECTORY_ENTRY_TLS) else {
  334. return Ok(None);
  335. };
  336. let directory_rva = dd.virtual_address.get(LE);
  337. if directory_rva == 0 {
  338. return Ok(None);
  339. }
  340. let sections = file.section_table();
  341. let tls = sections
  342. .pe_data_at(data, directory_rva)
  343. .ok_or_else(|| PeError::Malformed("TLS directory outside of sections".into()))?;
  344. let callbacks_va = layout::read_u64(tls, layout::TLS64_ADDRESS_OF_CALLBACKS)
  345. .ok_or_else(|| PeError::Malformed("truncated TLS directory".into()))?;
  346. let mut callback_rvas = Vec::new();
  347. if callbacks_va != 0 {
  348. let array_rva = va_to_rva(callbacks_va, image_base)?;
  349. let array = sections
  350. .pe_data_at(data, array_rva)
  351. .ok_or_else(|| PeError::Malformed("TLS callback array outside of sections".into()))?;
  352. for slot in array.as_chunks::<8>().0.iter().take(MAX_TLS_CALLBACKS) {
  353. let va = u64::from_le_bytes(*slot);
  354. if va == 0 {
  355. break;
  356. }
  357. callback_rvas.push(va_to_rva(va, image_base)?);
  358. }
  359. }
  360. Ok(Some(TlsInfo {
  361. directory_rva,
  362. callbacks_va,
  363. callback_rvas,
  364. }))
  365. }
  366. fn va_to_rva(va: u64, image_base: u64) -> Result<u32, PeError> {
  367. va.checked_sub(image_base)
  368. .and_then(|rva| u32::try_from(rva).ok())
  369. .ok_or_else(|| PeError::Malformed(format!("VA 0x{va:x} is outside the image")))
  370. }
  371. #[cfg(test)]
  372. mod tests {
  373. use super::*;
  374. /// The test binary itself is a real MSVC-linked PE32+ image.
  375. fn own_image() -> Vec<u8> {
  376. std::fs::read(std::env::current_exe().unwrap()).unwrap()
  377. }
  378. #[test]
  379. fn parses_own_test_binary() {
  380. let info = ImageInfo::parse(&own_image()).unwrap();
  381. assert_eq!(info.machine, MACHINE_AMD64);
  382. assert!(!info.is_dll());
  383. assert!(info.entry_rva != 0);
  384. assert!(info.has_exception_table, "x64 images always carry .pdata");
  385. assert!(info.sections.iter().any(|s| s.name.starts_with(".text")));
  386. let kernel32 = info
  387. .imports
  388. .iter()
  389. .find(|m| m.dll.eq_ignore_ascii_case("kernel32.dll"))
  390. .expect("Rust std imports kernel32");
  391. assert!(kernel32.entries.iter().all(|e| e.iat_slot_rva != 0));
  392. // Rust std uses static TLS, so a TLS directory must be present (its
  393. // callback array may legitimately be empty).
  394. assert!(info.tls.is_some());
  395. }
  396. #[test]
  397. fn rva_to_file_offset_maps_entry_point() {
  398. let data = own_image();
  399. let info = ImageInfo::parse(&data).unwrap();
  400. let off = info.rva_to_file_offset(info.entry_rva).unwrap() as usize;
  401. assert!(off < data.len());
  402. }
  403. #[test]
  404. fn rva_to_file_offset_rejects_offsets_past_4_gib() {
  405. let mut info = ImageInfo::parse(&own_image()).unwrap();
  406. let rva = info.sections[0].rva + 0x20;
  407. assert!(info.rva_to_file_offset(rva).is_some());
  408. // Used to overflow (a panic in debug builds, a wrong offset in
  409. // release ones).
  410. info.sections[0].file_offset = u32::MAX - 0x10;
  411. assert_eq!(info.rva_to_file_offset(rva), None);
  412. }
  413. #[test]
  414. fn rejects_garbage_without_panicking() {
  415. assert!(ImageInfo::parse(b"").is_err());
  416. assert!(ImageInfo::parse(b"MZ not really").is_err());
  417. let mut truncated = own_image();
  418. truncated.truncate(0x200);
  419. assert!(ImageInfo::parse(&truncated).is_err());
  420. }
  421. #[test]
  422. fn rejects_iat_outside_image() {
  423. let mut data = own_image();
  424. let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap();
  425. let import_rva = layout::read_u32(&data, dd).unwrap();
  426. let desc = ImageInfo::parse(&data)
  427. .unwrap()
  428. .rva_to_file_offset(import_rva)
  429. .unwrap() as usize;
  430. // First descriptor's FirstThunk, at the 4 GiB limit: used to overflow.
  431. data[desc + 16..desc + 20].copy_from_slice(&0xFFFF_FFF8u32.to_le_bytes());
  432. assert!(matches!(
  433. ImageInfo::parse(&data),
  434. Err(PeError::Malformed(_))
  435. ));
  436. }
  437. /// A minimal PE32+ image: one section at RVA 0x1000 holding `body`, with
  438. /// the export directory (RVA 0x1000, 0x80 bytes) pointing at it.
  439. fn synthetic_image(body: &[u8]) -> Vec<u8> {
  440. let mut d = vec![0u8; 0x200];
  441. d[0..2].copy_from_slice(b"MZ");
  442. d[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
  443. d[0x40..0x44].copy_from_slice(b"PE\0\0");
  444. d[0x44..0x46].copy_from_slice(&MACHINE_AMD64.to_le_bytes());
  445. d[0x46..0x48].copy_from_slice(&1u16.to_le_bytes()); // sections
  446. d[0x54..0x56].copy_from_slice(&240u16.to_le_bytes()); // optional header size
  447. d[0x56..0x58].copy_from_slice(&0x2022u16.to_le_bytes()); // DLL, large address aware
  448. let opt = 0x58;
  449. d[opt..opt + 2].copy_from_slice(&0x20Bu16.to_le_bytes());
  450. d[opt + 24..opt + 32].copy_from_slice(&0x1_8000_0000u64.to_le_bytes());
  451. d[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
  452. d[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
  453. d[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes());
  454. d[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
  455. d[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes());
  456. d[opt + 112..opt + 116].copy_from_slice(&0x1000u32.to_le_bytes());
  457. d[opt + 116..opt + 120].copy_from_slice(&0x80u32.to_le_bytes());
  458. let sec = opt + 240;
  459. d[sec..sec + 6].copy_from_slice(b".edata");
  460. d[sec + 8..sec + 12].copy_from_slice(&0x200u32.to_le_bytes()); // virtual size
  461. d[sec + 12..sec + 16].copy_from_slice(&0x1000u32.to_le_bytes());
  462. d[sec + 16..sec + 20].copy_from_slice(&0x200u32.to_le_bytes()); // raw size
  463. d[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // raw offset
  464. d.extend_from_slice(body);
  465. d.resize(0x400, 0);
  466. d
  467. }
  468. #[test]
  469. fn unused_export_slots_are_not_exports() {
  470. // Ordinal base 1; three address slots: "alpha", an unused hole (0),
  471. // and "gamma". The Windows loader treats address 0 as "not exported".
  472. let mut body = vec![0u8; 0x100];
  473. let put32 =
  474. |b: &mut Vec<u8>, at: usize, v: u32| b[at..at + 4].copy_from_slice(&v.to_le_bytes());
  475. put32(&mut body, 12, 0x1040); // name of the DLL
  476. put32(&mut body, 16, 1); // ordinal base
  477. put32(&mut body, 20, 3); // number of functions
  478. put32(&mut body, 24, 2); // number of names
  479. put32(&mut body, 28, 0x1028); // address table
  480. put32(&mut body, 32, 0x1034); // name pointer table
  481. put32(&mut body, 36, 0x103C); // name ordinal table
  482. put32(&mut body, 0x28, 0x1200);
  483. put32(&mut body, 0x2C, 0);
  484. put32(&mut body, 0x30, 0x1204);
  485. put32(&mut body, 0x34, 0x1044);
  486. put32(&mut body, 0x38, 0x104A);
  487. body[0x3C..0x3E].copy_from_slice(&0u16.to_le_bytes());
  488. body[0x3E..0x40].copy_from_slice(&2u16.to_le_bytes());
  489. body[0x40..0x44].copy_from_slice(b"t.dl");
  490. body[0x44..0x4A].copy_from_slice(b"alpha\0");
  491. body[0x4A..0x50].copy_from_slice(b"gamma\0");
  492. let info = ImageInfo::parse(&synthetic_image(&body)).unwrap();
  493. let exports: Vec<_> = info
  494. .exports
  495. .iter()
  496. .map(|e| (e.name.as_deref(), e.ordinal, e.rva))
  497. .collect();
  498. assert_eq!(
  499. exports,
  500. [
  501. (Some("alpha"), 1, Some(0x1200)),
  502. (Some("gamma"), 3, Some(0x1204))
  503. ]
  504. );
  505. }
  506. }