/ crates / emtk / src / injector / mod.rs
mod.rs
 1  use detours_sys::{_PROCESS_INFORMATION, _STARTUPINFOA};
 2  use std::borrow::BorrowMut;
 3  use std::ptr::{null, null_mut};
 4  use std::{ffi::CString, mem::MaybeUninit};
 5  use winapi::um::handleapi::CloseHandle;
 6  use winapi::um::processthreadsapi::ResumeThread;
 7  
 8  /// Inject a DLL into a target process.
 9  ///
10  /// # Safety
11  ///
12  /// This function is unsafe because it is injecting a DLL into a live process.
13  pub unsafe fn inject(dll_path: &str, target_exe: &str) -> std::io::Result<()> {
14  	let binding = CString::new(target_exe)?;
15  	let mut target_exe = binding.as_c_str();
16  	let dll_path = CString::new(dll_path).unwrap();
17  
18  	dbg!(&target_exe, &dll_path);
19  
20  	let mut process_info: _PROCESS_INFORMATION = MaybeUninit::zeroed().assume_init();
21  	let mut startup_info: _STARTUPINFOA = MaybeUninit::zeroed().assume_init();
22  
23  	let mut curr_exe_path = std::env::current_exe().unwrap();
24  	curr_exe_path.pop();
25  
26  	let result = detours_sys::DetourCreateProcessWithDllExA(
27  		null(),
28  		target_exe.borrow_mut().as_ptr() as _,
29  		null_mut(),
30  		null_mut(),
31  		0,
32  		0,
33  		null_mut(),
34  		null(),
35  		&mut startup_info as *mut _,
36  		&mut process_info as *mut _,
37  		dll_path.as_ptr() as _,
38  		None,
39  	);
40  
41  	if result == 0 {
42  		eprintln!("CreateProcessA failed: {}", result);
43  		return Err(std::io::Error::last_os_error());
44  	}
45  
46  	ResumeThread(process_info.hThread as _);
47  	CloseHandle(process_info.hProcess as _);
48  	CloseHandle(process_info.hThread as _);
49  
50  	Ok(())
51  }