thunks.rs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. //! Stubs for imports nobody implements yet.
  2. //!
  3. //! Each unresolved import gets 32 bytes of generated code:
  4. //!
  5. //! ```text
  6. //! mov rcx, <&'static ImportSite> ; 48 B9 imm64
  7. //! mov rax, <unimplemented_import> ; 48 B8 imm64
  8. //! jmp rax ; FF E0
  9. //! ```
  10. //!
  11. //! The jump keeps the title's return address on the stack, so the handler
  12. //! returns straight to the caller. Bring-up then shows exactly which API to
  13. //! implement next, rather than failing at load time.
  14. use std::sync::atomic::{AtomicU64, Ordering};
  15. use anyhow::{Result, bail};
  16. use windows_sys::Win32::System::Diagnostics::Debug::{
  17. DebugBreak, FlushInstructionCache, IsDebuggerPresent,
  18. };
  19. use windows_sys::Win32::System::Memory::{
  20. MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc, VirtualProtect,
  21. };
  22. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  23. /// What an unimplemented import does when called.
  24. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
  25. pub enum UnimplementedPolicy {
  26. /// Log, break into an attached debugger, then abort. The default:
  27. /// silently continuing usually crashes later and further from the cause.
  28. #[default]
  29. Trap,
  30. /// Log once per import and return 0. Useful to push through bring-up.
  31. ReturnZero,
  32. }
  33. /// Identifies one unresolved import. Leaked: lives as long as the process.
  34. #[derive(Debug)]
  35. pub struct ImportSite {
  36. pub dll: String,
  37. pub symbol: String,
  38. pub policy: UnimplementedPolicy,
  39. pub calls: AtomicU64,
  40. }
  41. static UNIMPLEMENTED_CALLS: AtomicU64 = AtomicU64::new(0);
  42. /// Total number of calls that reached an unimplemented-import stub.
  43. pub fn unimplemented_call_count() -> u64 {
  44. UNIMPLEMENTED_CALLS.load(Ordering::Relaxed)
  45. }
  46. extern "system" fn unimplemented_import(site: &'static ImportSite) -> u64 {
  47. UNIMPLEMENTED_CALLS.fetch_add(1, Ordering::Relaxed);
  48. let previous = site.calls.fetch_add(1, Ordering::Relaxed);
  49. match site.policy {
  50. UnimplementedPolicy::ReturnZero => {
  51. if previous == 0 {
  52. tracing::warn!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called, returning 0");
  53. }
  54. 0
  55. }
  56. UnimplementedPolicy::Trap => {
  57. tracing::error!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called");
  58. // Into the crash log too: `abort` ends the process without
  59. // running the handlers that write it.
  60. let (dll, symbol) = (&site.dll, &site.symbol);
  61. let text = format!("VIctory: unimplemented import {dll}!{symbol} called");
  62. crate::log_crash(&text);
  63. // SAFETY: plain Win32 calls without preconditions.
  64. unsafe {
  65. if IsDebuggerPresent() != 0 {
  66. DebugBreak();
  67. }
  68. }
  69. std::process::abort();
  70. }
  71. }
  72. }
  73. const THUNK_SIZE: usize = 32;
  74. /// Executable memory holding one stub per unresolved import.
  75. pub(crate) struct ThunkBlock {
  76. base: *mut u8,
  77. len: usize,
  78. used: usize,
  79. }
  80. impl ThunkBlock {
  81. /// Reserves room for `count` stubs (writable until [`Self::seal`]).
  82. pub(crate) fn new(count: usize) -> Result<Self> {
  83. let len = (count.max(1) * THUNK_SIZE).next_multiple_of(4096);
  84. // SAFETY: fresh anonymous allocation; no existing memory is touched.
  85. let base = unsafe {
  86. VirtualAlloc(
  87. std::ptr::null(),
  88. len,
  89. MEM_COMMIT | MEM_RESERVE,
  90. PAGE_READWRITE,
  91. )
  92. } as *mut u8;
  93. if base.is_null() {
  94. bail!(
  95. "VirtualAlloc for import stubs failed: {}",
  96. std::io::Error::last_os_error()
  97. );
  98. }
  99. Ok(ThunkBlock { base, len, used: 0 })
  100. }
  101. /// Emits a stub for `site` and returns its address.
  102. pub(crate) fn emit(&mut self, site: &'static ImportSite) -> Result<usize> {
  103. if self.used + THUNK_SIZE > self.len {
  104. bail!("import stub block is full");
  105. }
  106. let mut code = [0xCC_u8; THUNK_SIZE]; // int3 padding
  107. code[0..2].copy_from_slice(&[0x48, 0xB9]);
  108. code[2..10].copy_from_slice(&(site as *const ImportSite as u64).to_le_bytes());
  109. code[10..12].copy_from_slice(&[0x48, 0xB8]);
  110. let handler = unimplemented_import as extern "system" fn(&'static ImportSite) -> u64;
  111. code[12..20].copy_from_slice(&(handler as *const () as u64).to_le_bytes());
  112. code[20..22].copy_from_slice(&[0xFF, 0xE0]);
  113. // SAFETY: `used + THUNK_SIZE <= len`, and the block is still writable.
  114. let at = unsafe {
  115. let at = self.base.add(self.used);
  116. std::ptr::copy_nonoverlapping(code.as_ptr(), at, THUNK_SIZE);
  117. at
  118. };
  119. self.used += THUNK_SIZE;
  120. Ok(at as usize)
  121. }
  122. /// Makes the block read+execute. The block is intentionally leaked:
  123. /// title code may hold these addresses for the life of the process.
  124. pub(crate) fn seal(self) -> Result<()> {
  125. let mut old = 0;
  126. // SAFETY: `base..base+len` is the allocation made in `new`.
  127. let ok = unsafe { VirtualProtect(self.base as _, self.len, PAGE_EXECUTE_READ, &mut old) };
  128. if ok == 0 {
  129. bail!(
  130. "VirtualProtect for import stubs failed: {}",
  131. std::io::Error::last_os_error()
  132. );
  133. }
  134. // SAFETY: flushing our own process's instruction cache for our own block.
  135. unsafe { FlushInstructionCache(GetCurrentProcess(), self.base as _, self.len) };
  136. Ok(())
  137. }
  138. }
  139. #[cfg(test)]
  140. mod tests {
  141. use super::*;
  142. /// In a child process of the next test: calls an unimplemented import
  143. /// that traps, with the crash log where `VICTORY_TRAP_LOG` says.
  144. #[test]
  145. fn trap_child() {
  146. let Some(log) = std::env::var_os("VICTORY_TRAP_LOG") else {
  147. return;
  148. };
  149. crate::log_crashes_to(log.into());
  150. let site = Box::leak(Box::new(ImportSite {
  151. dll: "probe.dll".into(),
  152. symbol: "Missing".into(),
  153. policy: UnimplementedPolicy::Trap,
  154. calls: AtomicU64::new(0),
  155. }));
  156. unimplemented_import(site);
  157. }
  158. #[test]
  159. fn a_trapped_import_is_in_the_crash_log() {
  160. let dir = tempfile::tempdir().unwrap();
  161. let log = dir.path().join("crashes.log");
  162. let out = std::process::Command::new(std::env::current_exe().unwrap())
  163. .args(["--exact", "thunks::tests::trap_child", "--nocapture"])
  164. .env("VICTORY_TRAP_LOG", &log)
  165. .output()
  166. .unwrap();
  167. assert!(!out.status.success(), "the trap ends the process");
  168. let text = std::fs::read_to_string(&log).unwrap_or_default();
  169. let named = text.contains("VIctory: unimplemented import probe.dll!Missing called");
  170. assert!(named, "crash log: {text:?}");
  171. }
  172. }