prepare.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //! Turns a title's image into something the Windows loader maps but does
  2. //! not run. Pure byte manipulation, so it is testable on any host.
  3. use victory_pe::layout::{self, dir, dll_flags, file_flags};
  4. use victory_pe::{ImageInfo, PeError};
  5. #[derive(Debug, thiserror::Error)]
  6. pub enum PrepareError {
  7. #[error(transparent)]
  8. Pe(#[from] PeError),
  9. #[error("cannot patch image: {0}")]
  10. Patch(&'static str),
  11. }
  12. /// A patched copy of an image plus everything we need from the original.
  13. #[derive(Debug, Clone)]
  14. pub struct PreparedImage {
  15. /// Parsed from the *original* bytes: imports, TLS callbacks and entry
  16. /// point as the title expects them.
  17. pub info: ImageInfo,
  18. /// The patched bytes to hand to the Windows loader.
  19. pub bytes: Vec<u8>,
  20. /// BLAKE3 of the original bytes: identifies the exact build.
  21. pub original_hash: blake3::Hash,
  22. }
  23. impl PreparedImage {
  24. /// File name for the patched copy, unique per original build.
  25. pub fn file_name(&self) -> String {
  26. format!("victory-image-{}.dll", &self.original_hash.to_hex()[..16])
  27. }
  28. }
  29. /// Produces the patched copy. The changes are:
  30. ///
  31. /// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL
  32. /// and calls nothing;
  33. /// * import directory points to its empty terminator and the bound-import
  34. /// directory is cleared: we bind the original slots using `info.imports`;
  35. /// * TLS callback pointer cleared: the OS still allocates static TLS for
  36. /// the image, but callbacks only run when we call them (after binding);
  37. /// its base relocation is made a no-op so the 0 survives a rebase;
  38. /// * `FORCE_INTEGRITY` cleared, checksum zeroed: the copy is unsigned.
  39. pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> {
  40. let info = ImageInfo::parse(original)?;
  41. let mut bytes = original.to_vec();
  42. let fh = layout::file_header_offset(&bytes).ok_or(PrepareError::Patch("no file header"))?;
  43. let opt =
  44. layout::optional_header_offset(&bytes).ok_or(PrepareError::Patch("no optional header"))?;
  45. let characteristics = info.characteristics | file_flags::DLL;
  46. write_u16(
  47. &mut bytes,
  48. fh + layout::FILE_HEADER_CHARACTERISTICS,
  49. characteristics,
  50. )?;
  51. write_u32(&mut bytes, opt + layout::OPT_ADDRESS_OF_ENTRY_POINT, 0)?;
  52. write_u32(&mut bytes, opt + layout::OPT_CHECKSUM, 0)?;
  53. let dll_characteristics = info.dll_characteristics & !dll_flags::FORCE_INTEGRITY;
  54. write_u16(
  55. &mut bytes,
  56. opt + layout::OPT_DLL_CHARACTERISTICS,
  57. dll_characteristics,
  58. )?;
  59. // Windows 10 assigns static TLS to the prepared DLL when its empty
  60. // import table is present. The parser has already walked one descriptor
  61. // per module up to the null terminator, regardless of the recorded Size.
  62. if let Some(at) = layout::data_directory_offset(&bytes, dir::IMPORT) {
  63. let rva = layout::read_u32(&bytes, at).ok_or(PrepareError::Patch("no import RVA"))?;
  64. if rva != 0 {
  65. let terminator = u32::try_from(info.imports.len())
  66. .ok()
  67. .and_then(|count| count.checked_mul(IMPORT_DESCRIPTOR_SIZE))
  68. .and_then(|offset| rva.checked_add(offset))
  69. .ok_or(PrepareError::Patch("import terminator RVA overflow"))?;
  70. write_u32(&mut bytes, at, terminator)?;
  71. write_u32(&mut bytes, at + 4, IMPORT_DESCRIPTOR_SIZE)?;
  72. }
  73. }
  74. if let Some(at) = layout::data_directory_offset(&bytes, dir::BOUND_IMPORT) {
  75. write(&mut bytes, at, &[0; layout::DATA_DIRECTORY_SIZE])?;
  76. }
  77. if let Some(tls) = &info.tls
  78. && tls.callbacks_va != 0
  79. {
  80. let at = info
  81. .rva_to_file_offset(tls.directory_rva)
  82. .ok_or(PrepareError::Patch("TLS directory is not file-backed"))?;
  83. write_u64(
  84. &mut bytes,
  85. at as usize + layout::TLS64_ADDRESS_OF_CALLBACKS,
  86. 0,
  87. )?;
  88. // The field's base relocation would turn the 0 into `delta` whenever
  89. // the loader maps the copy away from its preferred base (Wine always
  90. // does for DYNAMIC_BASE images), and the loader then reads callbacks
  91. // from there. Make that entry a no-op.
  92. let field_rva = tls.directory_rva + layout::TLS64_ADDRESS_OF_CALLBACKS as u32;
  93. for (entry, target) in dir64_relocations(&bytes, &info) {
  94. if target == field_rva {
  95. write_u16(&mut bytes, entry, 0)?; // IMAGE_REL_BASED_ABSOLUTE
  96. }
  97. }
  98. }
  99. Ok(PreparedImage {
  100. info,
  101. bytes,
  102. original_hash: blake3::hash(original),
  103. })
  104. }
  105. /// Size of an IMAGE_IMPORT_DESCRIPTOR in the PE file.
  106. const IMPORT_DESCRIPTOR_SIZE: u32 = 20;
  107. /// Every `IMAGE_REL_BASED_DIR64` base relocation: (file offset of its entry,
  108. /// RVA it patches). Empty if the image has no readable relocation table.
  109. fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> {
  110. const DIR64: u16 = 10;
  111. let mut out = Vec::new();
  112. let Some(d) = layout::data_directory_offset(bytes, dir::BASERELOC) else {
  113. return out;
  114. };
  115. let (Some(rva), Some(size)) = (layout::read_u32(bytes, d), layout::read_u32(bytes, d + 4))
  116. else {
  117. return out;
  118. };
  119. let Some(start) = info.rva_to_file_offset(rva).filter(|_| size != 0) else {
  120. return out;
  121. };
  122. let (mut at, end) = (start as usize, start as usize + size as usize);
  123. while at + 8 <= end {
  124. let (Some(page), Some(block)) =
  125. (layout::read_u32(bytes, at), layout::read_u32(bytes, at + 4))
  126. else {
  127. break;
  128. };
  129. let block = block as usize;
  130. if block < 8 || at + block > end {
  131. break;
  132. }
  133. for entry in (at + 8..at + block).step_by(2) {
  134. let Some(e) = bytes.get(entry..entry + 2) else {
  135. break;
  136. };
  137. let e = u16::from_le_bytes([e[0], e[1]]);
  138. if e >> 12 == DIR64 {
  139. out.push((entry, page + u32::from(e & 0xFFF)));
  140. }
  141. }
  142. at += block;
  143. }
  144. out
  145. }
  146. fn write_u16(bytes: &mut [u8], at: usize, v: u16) -> Result<(), PrepareError> {
  147. write(bytes, at, &v.to_le_bytes())
  148. }
  149. fn write_u32(bytes: &mut [u8], at: usize, v: u32) -> Result<(), PrepareError> {
  150. write(bytes, at, &v.to_le_bytes())
  151. }
  152. fn write_u64(bytes: &mut [u8], at: usize, v: u64) -> Result<(), PrepareError> {
  153. write(bytes, at, &v.to_le_bytes())
  154. }
  155. fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> {
  156. bytes
  157. .get_mut(at..at + v.len())
  158. .ok_or(PrepareError::Patch("header field outside of file"))?
  159. .copy_from_slice(v);
  160. Ok(())
  161. }
  162. #[cfg(test)]
  163. mod tests {
  164. use super::*;
  165. #[test]
  166. fn patches_own_test_binary() {
  167. let original = std::fs::read(std::env::current_exe().unwrap()).unwrap();
  168. let prepared = prepare(&original).unwrap();
  169. assert!(!prepared.info.is_dll(), "info describes the original");
  170. assert!(prepared.info.import_count() > 0);
  171. let patched = ImageInfo::parse(&prepared.bytes).unwrap();
  172. assert!(patched.is_dll());
  173. assert_eq!(patched.entry_rva, 0);
  174. assert!(patched.imports.is_empty());
  175. assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0);
  176. if let Some(tls) = &patched.tls {
  177. assert_eq!(tls.callbacks_va, 0);
  178. let field = tls.directory_rva + layout::TLS64_ADDRESS_OF_CALLBACKS as u32;
  179. assert!(
  180. dir64_relocations(&prepared.bytes, &patched)
  181. .iter()
  182. .all(|&(_, target)| target != field),
  183. "the cleared callback pointer must not be relocated"
  184. );
  185. }
  186. // Nothing else moved: same sections, same size.
  187. assert_eq!(patched.sections.len(), prepared.info.sections.len());
  188. assert_eq!(prepared.bytes.len(), original.len());
  189. }
  190. #[test]
  191. fn keeps_iat_slots_when_import_size_excludes_the_terminator() {
  192. let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap();
  193. let info = ImageInfo::parse(&original).unwrap();
  194. let directory = layout::data_directory_offset(&original, dir::IMPORT).unwrap();
  195. // This linker layout counts the descriptors for real modules only.
  196. let descriptor_bytes = u32::try_from(info.imports.len()).unwrap() * IMPORT_DESCRIPTOR_SIZE;
  197. write_u32(&mut original, directory + 4, descriptor_bytes).unwrap();
  198. let prepared = prepare(&original).unwrap();
  199. let empty = layout::read_u32(&prepared.bytes, directory).unwrap();
  200. assert_eq!(
  201. empty,
  202. layout::read_u32(&original, directory).unwrap() + descriptor_bytes
  203. );
  204. assert_eq!(
  205. layout::read_u32(&prepared.bytes, directory + 4),
  206. Some(IMPORT_DESCRIPTOR_SIZE)
  207. );
  208. let at = info.rva_to_file_offset(empty).unwrap() as usize;
  209. assert_eq!(
  210. &prepared.bytes[at..at + IMPORT_DESCRIPTOR_SIZE as usize],
  211. &[0; 20]
  212. );
  213. let iat = layout::data_directory_offset(&original, dir::IAT).unwrap();
  214. assert_eq!(
  215. &prepared.bytes[iat..iat + layout::DATA_DIRECTORY_SIZE],
  216. &original[iat..iat + layout::DATA_DIRECTORY_SIZE]
  217. );
  218. assert_eq!(prepared.info.import_count(), info.import_count());
  219. for module in &prepared.info.imports {
  220. for entry in &module.entries {
  221. let at = info.rva_to_file_offset(entry.iat_slot_rva).unwrap() as usize;
  222. assert_eq!(&prepared.bytes[at..at + 8], &original[at..at + 8]);
  223. }
  224. }
  225. }
  226. #[cfg(windows)]
  227. #[test]
  228. fn windows_assigns_static_tls_to_a_prepared_dll() {
  229. // Model a title DLL using our own linked image. Loading a DLL leaves
  230. // its assigned index intact; the executable-specific redirect resets it.
  231. let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap();
  232. let flags =
  233. layout::file_header_offset(&original).unwrap() + layout::FILE_HEADER_CHARACTERISTICS;
  234. let characteristics =
  235. ImageInfo::parse(&original).unwrap().characteristics | file_flags::DLL;
  236. write_u16(&mut original, flags, characteristics).unwrap();
  237. let prepared = prepare(&original).unwrap();
  238. let info = &prepared.info;
  239. let tls = info.tls.as_ref().expect("the test binary uses static TLS");
  240. let directory = info.rva_to_file_offset(tls.directory_rva).unwrap() as usize;
  241. let index_va = layout::read_u64(&original, directory + 16).unwrap();
  242. let index_rva = index_va.checked_sub(info.image_base).unwrap();
  243. assert!(index_rva + 4 <= u64::from(info.size_of_image));
  244. let folder = tempfile::tempdir().unwrap();
  245. let image = crate::load(&prepared, folder.path()).unwrap();
  246. // SAFETY: the mapped test image contains the checked DWORD above.
  247. let assigned =
  248. unsafe { ((image.base() + index_rva as usize) as *const u32).read_unaligned() };
  249. // SAFETY: the prepared DLL has never been attached or given to a caller.
  250. unsafe { image.unload() };
  251. assert_ne!(
  252. assigned, 0,
  253. "the process executable already owns TLS slot zero"
  254. );
  255. }
  256. #[test]
  257. fn file_name_is_stable_per_build() {
  258. let original = std::fs::read(std::env::current_exe().unwrap()).unwrap();
  259. let a = prepare(&original).unwrap();
  260. let b = prepare(&original).unwrap();
  261. assert_eq!(a.file_name(), b.file_name());
  262. }
  263. }