Pārlūkot izejas kodu

Keep an empty import descriptor so Windows assigns static TLS

Use the descriptor count already validated by the PE parser, so the directory size need not include the null terminator. Check the OS-assigned static TLS index on a mapped test DLL.
ifBars 3 dienas atpakaļ
vecāks
revīzija
25a3e9596f
1 mainītis faili ar 69 papildinājumiem un 17 dzēšanām
  1. 69 17
      crates/victory-loader/src/prepare.rs

+ 69 - 17
crates/victory-loader/src/prepare.rs

@@ -35,8 +35,8 @@ impl PreparedImage {
 ///
 ///
 /// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL
 /// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL
 ///   and calls nothing;
 ///   and calls nothing;
-/// * import, bound-import and IAT directories cleared: we bind the original
-///   IAT slots ourselves, using `info.imports`;
+/// * import directory points to its empty terminator and the bound-import
+///   directory is cleared: we bind the original slots using `info.imports`;
 /// * TLS callback pointer cleared: the OS still allocates static TLS for
 /// * TLS callback pointer cleared: the OS still allocates static TLS for
 ///   the image, but callbacks only run when we call them (after binding);
 ///   the image, but callbacks only run when we call them (after binding);
 ///   its base relocation is made a no-op so the 0 survives a rebase;
 ///   its base relocation is made a no-op so the 0 survives a rebase;
@@ -64,13 +64,24 @@ pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> {
         dll_characteristics,
         dll_characteristics,
     )?;
     )?;
 
 
-    // Clear the IAT directory along with the import directory for Windows 10.
-    // The slots themselves stay in the image for our binder.
-    for index in [dir::IMPORT, dir::BOUND_IMPORT, dir::IAT] {
-        if let Some(at) = layout::data_directory_offset(&bytes, index) {
-            write(&mut bytes, at, &[0; layout::DATA_DIRECTORY_SIZE])?;
+    // Windows 10 assigns static TLS to the prepared DLL when its empty
+    // import table is present. The parser has already walked one descriptor
+    // per module up to the null terminator, regardless of the recorded Size.
+    if let Some(at) = layout::data_directory_offset(&bytes, dir::IMPORT) {
+        let rva = layout::read_u32(&bytes, at).ok_or(PrepareError::Patch("no import RVA"))?;
+        if rva != 0 {
+            let terminator = u32::try_from(info.imports.len())
+                .ok()
+                .and_then(|count| count.checked_mul(IMPORT_DESCRIPTOR_SIZE))
+                .and_then(|offset| rva.checked_add(offset))
+                .ok_or(PrepareError::Patch("import terminator RVA overflow"))?;
+            write_u32(&mut bytes, at, terminator)?;
+            write_u32(&mut bytes, at + 4, IMPORT_DESCRIPTOR_SIZE)?;
         }
         }
     }
     }
+    if let Some(at) = layout::data_directory_offset(&bytes, dir::BOUND_IMPORT) {
+        write(&mut bytes, at, &[0; layout::DATA_DIRECTORY_SIZE])?;
+    }
 
 
     if let Some(tls) = &info.tls
     if let Some(tls) = &info.tls
         && tls.callbacks_va != 0
         && tls.callbacks_va != 0
@@ -102,6 +113,9 @@ pub fn prepare(original: &[u8]) -> Result<PreparedImage, PrepareError> {
     })
     })
 }
 }
 
 
+/// Size of an IMAGE_IMPORT_DESCRIPTOR in the PE file.
+const IMPORT_DESCRIPTOR_SIZE: u32 = 20;
+
 /// Every `IMAGE_REL_BASED_DIR64` base relocation: (file offset of its entry,
 /// Every `IMAGE_REL_BASED_DIR64` base relocation: (file offset of its entry,
 /// RVA it patches). Empty if the image has no readable relocation table.
 /// RVA it patches). Empty if the image has no readable relocation table.
 fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> {
 fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> {
@@ -174,13 +188,6 @@ mod tests {
         assert!(patched.is_dll());
         assert!(patched.is_dll());
         assert_eq!(patched.entry_rva, 0);
         assert_eq!(patched.entry_rva, 0);
         assert!(patched.imports.is_empty());
         assert!(patched.imports.is_empty());
-        for index in [dir::IMPORT, dir::BOUND_IMPORT, dir::IAT] {
-            let at = layout::data_directory_offset(&original, index).unwrap();
-            assert_eq!(
-                &prepared.bytes[at..at + layout::DATA_DIRECTORY_SIZE],
-                &[0; 8]
-            );
-        }
         assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0);
         assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0);
         if let Some(tls) = &patched.tls {
         if let Some(tls) = &patched.tls {
             assert_eq!(tls.callbacks_va, 0);
             assert_eq!(tls.callbacks_va, 0);
@@ -203,14 +210,27 @@ mod tests {
         let info = ImageInfo::parse(&original).unwrap();
         let info = ImageInfo::parse(&original).unwrap();
         let directory = layout::data_directory_offset(&original, dir::IMPORT).unwrap();
         let directory = layout::data_directory_offset(&original, dir::IMPORT).unwrap();
         // This linker layout counts the descriptors for real modules only.
         // This linker layout counts the descriptors for real modules only.
-        let descriptor_bytes = u32::try_from(info.imports.len() * 20).unwrap();
+        let descriptor_bytes = u32::try_from(info.imports.len()).unwrap() * IMPORT_DESCRIPTOR_SIZE;
         write_u32(&mut original, directory + 4, descriptor_bytes).unwrap();
         write_u32(&mut original, directory + 4, descriptor_bytes).unwrap();
         let prepared = prepare(&original).unwrap();
         let prepared = prepare(&original).unwrap();
+        let empty = layout::read_u32(&prepared.bytes, directory).unwrap();
+        assert_eq!(
+            empty,
+            layout::read_u32(&original, directory).unwrap() + descriptor_bytes
+        );
+        assert_eq!(
+            layout::read_u32(&prepared.bytes, directory + 4),
+            Some(IMPORT_DESCRIPTOR_SIZE)
+        );
+        let at = info.rva_to_file_offset(empty).unwrap() as usize;
+        assert_eq!(
+            &prepared.bytes[at..at + IMPORT_DESCRIPTOR_SIZE as usize],
+            &[0; 20]
+        );
         let iat = layout::data_directory_offset(&original, dir::IAT).unwrap();
         let iat = layout::data_directory_offset(&original, dir::IAT).unwrap();
-        assert_ne!(layout::read_u32(&original, iat), Some(0));
         assert_eq!(
         assert_eq!(
             &prepared.bytes[iat..iat + layout::DATA_DIRECTORY_SIZE],
             &prepared.bytes[iat..iat + layout::DATA_DIRECTORY_SIZE],
-            &[0; 8]
+            &original[iat..iat + layout::DATA_DIRECTORY_SIZE]
         );
         );
         assert_eq!(prepared.info.import_count(), info.import_count());
         assert_eq!(prepared.info.import_count(), info.import_count());
         for module in &prepared.info.imports {
         for module in &prepared.info.imports {
@@ -221,6 +241,38 @@ mod tests {
         }
         }
     }
     }
 
 
+    #[cfg(windows)]
+    #[test]
+    fn windows_assigns_static_tls_to_a_prepared_dll() {
+        // Model a title DLL using our own linked image. Loading a DLL leaves
+        // its assigned index intact; the executable-specific redirect resets it.
+        let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap();
+        let flags =
+            layout::file_header_offset(&original).unwrap() + layout::FILE_HEADER_CHARACTERISTICS;
+        let characteristics =
+            ImageInfo::parse(&original).unwrap().characteristics | file_flags::DLL;
+        write_u16(&mut original, flags, characteristics).unwrap();
+        let prepared = prepare(&original).unwrap();
+        let info = &prepared.info;
+        let tls = info.tls.as_ref().expect("the test binary uses static TLS");
+        let directory = info.rva_to_file_offset(tls.directory_rva).unwrap() as usize;
+        let index_va = layout::read_u64(&original, directory + 16).unwrap();
+        let index_rva = index_va.checked_sub(info.image_base).unwrap();
+        assert!(index_rva + 4 <= u64::from(info.size_of_image));
+
+        let folder = tempfile::tempdir().unwrap();
+        let image = crate::load(&prepared, folder.path()).unwrap();
+        // SAFETY: the mapped test image contains the checked DWORD above.
+        let assigned =
+            unsafe { ((image.base() + index_rva as usize) as *const u32).read_unaligned() };
+        // SAFETY: the prepared DLL has never been attached or given to a caller.
+        unsafe { image.unload() };
+        assert_ne!(
+            assigned, 0,
+            "the process executable already owns TLS slot zero"
+        );
+    }
+
     #[test]
     #[test]
     fn file_name_is_stable_per_build() {
     fn file_name_is_stable_per_build() {
         let original = std::fs::read(std::env::current_exe().unwrap()).unwrap();
         let original = std::fs::read(std::env::current_exe().unwrap()).unwrap();