thunks.rs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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. eprintln!(
  59. "VIctory: unimplemented import {}!{} called",
  60. site.dll, site.symbol
  61. );
  62. // SAFETY: plain Win32 calls without preconditions.
  63. unsafe {
  64. if IsDebuggerPresent() != 0 {
  65. DebugBreak();
  66. }
  67. }
  68. std::process::abort();
  69. }
  70. }
  71. }
  72. const THUNK_SIZE: usize = 32;
  73. /// Executable memory holding one stub per unresolved import.
  74. pub(crate) struct ThunkBlock {
  75. base: *mut u8,
  76. len: usize,
  77. used: usize,
  78. }
  79. impl ThunkBlock {
  80. /// Reserves room for `count` stubs (writable until [`Self::seal`]).
  81. pub(crate) fn new(count: usize) -> Result<Self> {
  82. let len = (count.max(1) * THUNK_SIZE).next_multiple_of(4096);
  83. // SAFETY: fresh anonymous allocation; no existing memory is touched.
  84. let base = unsafe {
  85. VirtualAlloc(
  86. std::ptr::null(),
  87. len,
  88. MEM_COMMIT | MEM_RESERVE,
  89. PAGE_READWRITE,
  90. )
  91. } as *mut u8;
  92. if base.is_null() {
  93. bail!(
  94. "VirtualAlloc for import stubs failed: {}",
  95. std::io::Error::last_os_error()
  96. );
  97. }
  98. Ok(ThunkBlock { base, len, used: 0 })
  99. }
  100. /// Emits a stub for `site` and returns its address.
  101. pub(crate) fn emit(&mut self, site: &'static ImportSite) -> Result<usize> {
  102. if self.used + THUNK_SIZE > self.len {
  103. bail!("import stub block is full");
  104. }
  105. let mut code = [0xCC_u8; THUNK_SIZE]; // int3 padding
  106. code[0..2].copy_from_slice(&[0x48, 0xB9]);
  107. code[2..10].copy_from_slice(&(site as *const ImportSite as u64).to_le_bytes());
  108. code[10..12].copy_from_slice(&[0x48, 0xB8]);
  109. let handler = unimplemented_import as extern "system" fn(&'static ImportSite) -> u64;
  110. code[12..20].copy_from_slice(&(handler as *const () as u64).to_le_bytes());
  111. code[20..22].copy_from_slice(&[0xFF, 0xE0]);
  112. // SAFETY: `used + THUNK_SIZE <= len`, and the block is still writable.
  113. let at = unsafe {
  114. let at = self.base.add(self.used);
  115. std::ptr::copy_nonoverlapping(code.as_ptr(), at, THUNK_SIZE);
  116. at
  117. };
  118. self.used += THUNK_SIZE;
  119. Ok(at as usize)
  120. }
  121. /// Makes the block read+execute. The block is intentionally leaked:
  122. /// title code may hold these addresses for the life of the process.
  123. pub(crate) fn seal(self) -> Result<()> {
  124. let mut old = 0;
  125. // SAFETY: `base..base+len` is the allocation made in `new`.
  126. let ok = unsafe { VirtualProtect(self.base as _, self.len, PAGE_EXECUTE_READ, &mut old) };
  127. if ok == 0 {
  128. bail!(
  129. "VirtualProtect for import stubs failed: {}",
  130. std::io::Error::last_os_error()
  131. );
  132. }
  133. // SAFETY: flushing our own process's instruction cache for our own block.
  134. unsafe { FlushInstructionCache(GetCurrentProcess(), self.base as _, self.len) };
  135. Ok(())
  136. }
  137. }