image.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. (delta < backed).then(|| s.file_offset + delta)
  199. })
  200. }
  201. pub fn import_count(&self) -> usize {
  202. self.imports.iter().map(|m| m.entries.len()).sum()
  203. }
  204. pub fn subsystem_name(&self) -> &'static str {
  205. use layout::subsystem::*;
  206. match self.subsystem {
  207. WINDOWS_GUI => "windows-gui",
  208. WINDOWS_CUI => "windows-cui",
  209. XBOX => "xbox",
  210. XBOX_CODE_CATALOG => "xbox-code-catalog",
  211. _ => "other",
  212. }
  213. }
  214. }
  215. fn has_flag(value: u16, flag: u16) -> bool {
  216. value & flag != 0
  217. }
  218. fn utf8(bytes: &[u8]) -> String {
  219. String::from_utf8_lossy(bytes).into_owned()
  220. }
  221. fn convert_import(import: Import<'_>) -> ImportSymbol {
  222. match import {
  223. Import::Ordinal(o) => ImportSymbol::Ordinal(o),
  224. Import::Name(hint, name) => ImportSymbol::Name {
  225. hint,
  226. name: utf8(name),
  227. },
  228. }
  229. }
  230. fn parse_imports(
  231. table: &ImportTable<'_>,
  232. size_of_image: u32,
  233. ) -> Result<Vec<ImportModule>, PeError> {
  234. let mut modules = Vec::new();
  235. let mut descriptors = table.descriptors()?;
  236. while let Some(desc) = descriptors.next()? {
  237. let iat_rva = desc.first_thunk.get(LE);
  238. // Prefer the unbound name table; fall back to the IAT for old linkers.
  239. let int_rva = match desc.original_first_thunk.get(LE) {
  240. 0 => iat_rva,
  241. rva => rva,
  242. };
  243. modules.push(ImportModule {
  244. dll: utf8(table.name(desc.name.get(LE))?),
  245. entries: entries(table.thunks(int_rva)?, iat_rva, size_of_image, |t| {
  246. table.import::<ImageNtHeaders64>(t)
  247. })?,
  248. });
  249. }
  250. Ok(modules)
  251. }
  252. fn parse_delay_imports(
  253. file: &PeFile64<'_>,
  254. size_of_image: u32,
  255. ) -> Result<Vec<ImportModule>, PeError> {
  256. let Some(table) = file.delay_load_import_table()? else {
  257. return Ok(Vec::new());
  258. };
  259. let mut modules = Vec::new();
  260. let mut descriptors = table.descriptors()?;
  261. while let Some(desc) = descriptors.next()? {
  262. modules.push(ImportModule {
  263. dll: utf8(table.name(desc.dll_name_rva.get(LE))?),
  264. entries: entries(
  265. table.thunks(desc.import_name_table_rva.get(LE))?,
  266. desc.import_address_table_rva.get(LE),
  267. size_of_image,
  268. |t| table.import::<ImageNtHeaders64>(t),
  269. )?,
  270. });
  271. }
  272. Ok(modules)
  273. }
  274. /// Pairs each name-table entry with its IAT slot. The IAT RVA is not checked
  275. /// by `object`, so every slot is checked to lie inside the image here.
  276. fn entries<'data>(
  277. mut thunks: ImportThunkList<'data>,
  278. iat_rva: u32,
  279. size_of_image: u32,
  280. import: impl Fn(pe::ImageThunkData64) -> object::read::Result<Import<'data>>,
  281. ) -> Result<Vec<ImportEntry>, PeError> {
  282. let mut entries = Vec::new();
  283. while let Some(thunk) = thunks.next::<ImageNtHeaders64>()? {
  284. let iat_slot_rva = u32::try_from(entries.len() * 8)
  285. .ok()
  286. .and_then(|offset| iat_rva.checked_add(offset))
  287. .filter(|&rva| rva.checked_add(8).is_some_and(|end| end <= size_of_image))
  288. .ok_or_else(|| {
  289. PeError::Malformed(format!("IAT at {iat_rva:#x} runs outside the image"))
  290. })?;
  291. entries.push(ImportEntry {
  292. symbol: convert_import(import(thunk)?),
  293. iat_slot_rva,
  294. });
  295. }
  296. Ok(entries)
  297. }
  298. fn parse_exports(file: &PeFile64<'_>) -> Result<Vec<ExportInfo>, PeError> {
  299. let Some(table) = file.export_table()? else {
  300. return Ok(Vec::new());
  301. };
  302. Ok(table
  303. .exports()?
  304. .into_iter()
  305. .map(|e| {
  306. let (rva, forward) = match e.target {
  307. ExportTarget::Address(rva) => (Some(rva), None),
  308. ExportTarget::ForwardByName(d, n) => {
  309. (None, Some(format!("{}.{}", utf8(d), utf8(n))))
  310. }
  311. ExportTarget::ForwardByOrdinal(d, o) => {
  312. (None, Some(format!("{}.#{}", utf8(d), o.0)))
  313. }
  314. };
  315. ExportInfo {
  316. name: e.name.map(utf8),
  317. ordinal: e.ordinal.0,
  318. rva,
  319. forward,
  320. }
  321. })
  322. .collect())
  323. }
  324. fn parse_tls(
  325. file: &PeFile64<'_>,
  326. data: &[u8],
  327. image_base: u64,
  328. ) -> Result<Option<TlsInfo>, PeError> {
  329. let Some(dd) = file.data_directory(pe::IMAGE_DIRECTORY_ENTRY_TLS) else {
  330. return Ok(None);
  331. };
  332. let directory_rva = dd.virtual_address.get(LE);
  333. if directory_rva == 0 {
  334. return Ok(None);
  335. }
  336. let sections = file.section_table();
  337. let tls = sections
  338. .pe_data_at(data, directory_rva)
  339. .ok_or_else(|| PeError::Malformed("TLS directory outside of sections".into()))?;
  340. let callbacks_va = layout::read_u64(tls, layout::TLS64_ADDRESS_OF_CALLBACKS)
  341. .ok_or_else(|| PeError::Malformed("truncated TLS directory".into()))?;
  342. let mut callback_rvas = Vec::new();
  343. if callbacks_va != 0 {
  344. let array_rva = va_to_rva(callbacks_va, image_base)?;
  345. let array = sections
  346. .pe_data_at(data, array_rva)
  347. .ok_or_else(|| PeError::Malformed("TLS callback array outside of sections".into()))?;
  348. for slot in array.as_chunks::<8>().0.iter().take(MAX_TLS_CALLBACKS) {
  349. let va = u64::from_le_bytes(*slot);
  350. if va == 0 {
  351. break;
  352. }
  353. callback_rvas.push(va_to_rva(va, image_base)?);
  354. }
  355. }
  356. Ok(Some(TlsInfo {
  357. directory_rva,
  358. callbacks_va,
  359. callback_rvas,
  360. }))
  361. }
  362. fn va_to_rva(va: u64, image_base: u64) -> Result<u32, PeError> {
  363. va.checked_sub(image_base)
  364. .and_then(|rva| u32::try_from(rva).ok())
  365. .ok_or_else(|| PeError::Malformed(format!("VA 0x{va:x} is outside the image")))
  366. }
  367. #[cfg(test)]
  368. mod tests {
  369. use super::*;
  370. /// The test binary itself is a real MSVC-linked PE32+ image.
  371. fn own_image() -> Vec<u8> {
  372. std::fs::read(std::env::current_exe().unwrap()).unwrap()
  373. }
  374. #[test]
  375. fn parses_own_test_binary() {
  376. let info = ImageInfo::parse(&own_image()).unwrap();
  377. assert_eq!(info.machine, MACHINE_AMD64);
  378. assert!(!info.is_dll());
  379. assert!(info.entry_rva != 0);
  380. assert!(info.has_exception_table, "x64 images always carry .pdata");
  381. assert!(info.sections.iter().any(|s| s.name.starts_with(".text")));
  382. let kernel32 = info
  383. .imports
  384. .iter()
  385. .find(|m| m.dll.eq_ignore_ascii_case("kernel32.dll"))
  386. .expect("Rust std imports kernel32");
  387. assert!(kernel32.entries.iter().all(|e| e.iat_slot_rva != 0));
  388. // Rust std uses static TLS, so a TLS directory must be present (its
  389. // callback array may legitimately be empty).
  390. assert!(info.tls.is_some());
  391. }
  392. #[test]
  393. fn rva_to_file_offset_maps_entry_point() {
  394. let data = own_image();
  395. let info = ImageInfo::parse(&data).unwrap();
  396. let off = info.rva_to_file_offset(info.entry_rva).unwrap() as usize;
  397. assert!(off < data.len());
  398. }
  399. #[test]
  400. fn rejects_garbage_without_panicking() {
  401. assert!(ImageInfo::parse(b"").is_err());
  402. assert!(ImageInfo::parse(b"MZ not really").is_err());
  403. let mut truncated = own_image();
  404. truncated.truncate(0x200);
  405. assert!(ImageInfo::parse(&truncated).is_err());
  406. }
  407. #[test]
  408. fn rejects_iat_outside_image() {
  409. let mut data = own_image();
  410. let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap();
  411. let import_rva = layout::read_u32(&data, dd).unwrap();
  412. let desc = ImageInfo::parse(&data)
  413. .unwrap()
  414. .rva_to_file_offset(import_rva)
  415. .unwrap() as usize;
  416. // First descriptor's FirstThunk, at the 4 GiB limit: used to overflow.
  417. data[desc + 16..desc + 20].copy_from_slice(&0xFFFF_FFF8u32.to_le_bytes());
  418. assert!(matches!(
  419. ImageInfo::parse(&data),
  420. Err(PeError::Malformed(_))
  421. ));
  422. }
  423. }
  424. #[cfg(test)]
  425. mod dbg_tls {
  426. #[test]
  427. fn dump_tls() {
  428. let data = std::fs::read(std::env::current_exe().unwrap()).unwrap();
  429. let info = super::ImageInfo::parse(&data).unwrap();
  430. eprintln!("TLS = {:?}", info.tls);
  431. eprintln!("image_base = {:x}", info.image_base);
  432. }
  433. }