aboutsummaryrefslogtreecommitdiffhomepage
path: root/zluda_inject
diff options
context:
space:
mode:
authorAndrzej Janik <[email protected]>2020-11-23 20:00:16 +0100
committerAndrzej Janik <[email protected]>2020-11-23 20:01:10 +0100
commiteb7c9aeeee4cf20a4d81a319f4ebf9329efb819f (patch)
treeaf96435ca89cb36ffd414be99acdd1f91c701787 /zluda_inject
parent0415f873ae15aceda87758f9fcce5d38aa68ca75 (diff)
downloadZLUDA-eb7c9aeeee4cf20a4d81a319f4ebf9329efb819f.tar.gz
ZLUDA-eb7c9aeeee4cf20a4d81a319f4ebf9329efb819f.zip
Rename everything
Diffstat (limited to 'zluda_inject')
-rw-r--r--zluda_inject/Cargo.toml16
-rw-r--r--zluda_inject/src/bin.rs106
-rw-r--r--zluda_inject/src/main.rs5
-rw-r--r--zluda_inject/src/win.rs148
4 files changed, 275 insertions, 0 deletions
diff --git a/zluda_inject/Cargo.toml b/zluda_inject/Cargo.toml
new file mode 100644
index 0000000..5dbb14b
--- /dev/null
+++ b/zluda_inject/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "zluda_inject"
+version = "0.0.0"
+authors = ["Andrzej Janik <[email protected]>"]
+edition = "2018"
+
+[[bin]]
+name = "zluda"
+path = "src/main.rs"
+
+[target.'cfg(windows)'.dependencies]
+zluda_redirect = { path = "../zluda_redirect" }
+winapi = { version = "0.3", features = ["processthreadsapi", "std", "synchapi"] }
+detours-sys = "0.1"
+clap = "2.33"
+guid = "0.1" \ No newline at end of file
diff --git a/zluda_inject/src/bin.rs b/zluda_inject/src/bin.rs
new file mode 100644
index 0000000..e021a41
--- /dev/null
+++ b/zluda_inject/src/bin.rs
@@ -0,0 +1,106 @@
+extern crate clap;
+#[macro_use]
+extern crate guid;
+extern crate detours_sys;
+extern crate winapi;
+
+use std::error::Error;
+use std::ffi::OsStr;
+use std::mem;
+use std::os::windows::ffi::OsStrExt;
+use std::ptr;
+
+use winapi::um::processthreadsapi::{GetExitCodeProcess, ResumeThread};
+use winapi::um::synchapi::WaitForSingleObject;
+use winapi::um::winbase::{INFINITE, WAIT_FAILED};
+
+use clap::{App, AppSettings, Arg};
+
+#[macro_use]
+mod win;
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let matches = App::new("ZLUDA injector")
+ .setting(AppSettings::TrailingVarArg)
+ .arg(
+ Arg::with_name("EXE")
+ .help("Path to the executable to be injected with ZLUDA")
+ .required(true),
+ )
+ .arg(
+ Arg::with_name("ARGS")
+ .multiple(true)
+ .help("Arguments that will be passed to <EXE>"),
+ )
+ .get_matches();
+ let exe = matches.value_of_os("EXE").unwrap();
+ let args: Vec<&OsStr> = matches
+ .values_of_os("ARGS")
+ .map(|x| x.collect())
+ .unwrap_or_else(|| Vec::new());
+ let mut cmd_line = Vec::<u16>::with_capacity(exe.len() + 2);
+ cmd_line.push('\"' as u16);
+ copy_to(exe, &mut cmd_line);
+ cmd_line.push('\"' as u16);
+ cmd_line.push(' ' as u16);
+ args.split_last().map(|(last_arg, args)| {
+ for arg in args {
+ cmd_line.reserve(arg.len());
+ copy_to(arg, &mut cmd_line);
+ cmd_line.push(' ' as u16);
+ }
+ copy_to(last_arg, &mut cmd_line);
+ });
+
+ cmd_line.push(0);
+ let mut startup_info = unsafe { mem::zeroed::<detours_sys::_STARTUPINFOW>() };
+ let mut proc_info = unsafe { mem::zeroed::<detours_sys::_PROCESS_INFORMATION>() };
+ os_call!(
+ detours_sys::DetourCreateProcessWithDllExW(
+ ptr::null(),
+ cmd_line.as_mut_ptr(),
+ ptr::null_mut(),
+ ptr::null_mut(),
+ 0,
+ 0,
+ ptr::null_mut(),
+ ptr::null(),
+ &mut startup_info as *mut _,
+ &mut proc_info as *mut _,
+ "zluda_redirect.dll\0".as_ptr() as *const i8,
+ Option::None
+ ),
+ |x| x != 0
+ );
+ let mut exe_path = std::env::current_dir()?
+ .as_os_str()
+ .encode_wide()
+ .collect::<Vec<_>>();
+ let guid = guid! {"C225FC0C-00D7-40B8-935A-7E342A9344C1"};
+ os_call!(
+ detours_sys::DetourCopyPayloadToProcess(
+ proc_info.hProcess,
+ mem::transmute(&guid),
+ exe_path.as_mut_ptr() as *mut _,
+ (exe_path.len() * mem::size_of::<u16>()) as u32
+ ),
+ |x| x != 0
+ );
+ os_call!(ResumeThread(proc_info.hThread), |x| x as i32 != -1);
+ os_call!(WaitForSingleObject(proc_info.hProcess, INFINITE), |x| x
+ != WAIT_FAILED);
+ let mut child_exit_code: u32 = 0;
+ os_call!(
+ GetExitCodeProcess(proc_info.hProcess, &mut child_exit_code as *mut _),
+ |x| x != 0
+ );
+ std::process::exit(child_exit_code as i32)
+}
+
+fn copy_to(from: &OsStr, to: &mut Vec<u16>) {
+ for x in from.encode_wide() {
+ to.push(x);
+ }
+}
+
+//
diff --git a/zluda_inject/src/main.rs b/zluda_inject/src/main.rs
new file mode 100644
index 0000000..6e292f2
--- /dev/null
+++ b/zluda_inject/src/main.rs
@@ -0,0 +1,5 @@
+#[cfg(target_os = "windows")]
+mod bin;
+
+#[cfg(not(target_os = "windows"))]
+fn main() {} \ No newline at end of file
diff --git a/zluda_inject/src/win.rs b/zluda_inject/src/win.rs
new file mode 100644
index 0000000..ec57ffb
--- /dev/null
+++ b/zluda_inject/src/win.rs
@@ -0,0 +1,148 @@
+#![allow(non_snake_case)]
+
+use std::error;
+use std::fmt;
+use std::ptr;
+
+mod c {
+ use std::ffi::c_void;
+ use std::os::raw::c_ulong;
+
+ pub type DWORD = c_ulong;
+ pub type HANDLE = LPVOID;
+ pub type LPVOID = *mut c_void;
+ pub type HINSTANCE = HANDLE;
+ pub type HMODULE = HINSTANCE;
+ pub type WCHAR = u16;
+ pub type LPCWSTR = *const WCHAR;
+ pub type LPWSTR = *mut WCHAR;
+
+ pub const FACILITY_NT_BIT: DWORD = 0x1000_0000;
+ pub const FORMAT_MESSAGE_FROM_HMODULE: DWORD = 0x00000800;
+ pub const FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
+ pub const FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
+
+ extern "system" {
+ pub fn GetLastError() -> DWORD;
+ pub fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE;
+ pub fn FormatMessageW(
+ flags: DWORD,
+ lpSrc: LPVOID,
+ msgId: DWORD,
+ langId: DWORD,
+ buf: LPWSTR,
+ nsize: DWORD,
+ args: *const c_void,
+ ) -> DWORD;
+ }
+}
+
+macro_rules! last_ident {
+ ($i:ident) => {
+ stringify!($i)
+ };
+ ($start:ident, $($cont:ident),+) => {
+ last_ident!($($cont),+)
+ };
+}
+
+macro_rules! os_call {
+ ($($path:ident)::+ ($($args:expr),*), $success:expr) => {
+ let result = unsafe{ $($path)::+ ($($args),+) };
+ if !($success)(result) {
+ let name = last_ident!($($path),+);
+ let err_code = $crate::win::errno();
+ Err($crate::win::OsError{
+ function: name,
+ error_code: err_code as u32,
+ message: $crate::win::error_string(err_code)
+ })?;
+ }
+ };
+}
+
+#[derive(Debug)]
+pub struct OsError {
+ pub function: &'static str,
+ pub error_code: u32,
+ pub message: String,
+}
+
+impl fmt::Display for OsError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{:?}", self)
+ }
+}
+
+impl error::Error for OsError {
+ fn source(&self) -> Option<&(dyn error::Error + 'static)> {
+ None
+ }
+}
+
+pub fn errno() -> i32 {
+ unsafe { c::GetLastError() as i32 }
+}
+
+/// Gets a detailed string description for the given error number.
+pub fn error_string(mut errnum: i32) -> String {
+ // This value is calculated from the macro
+ // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
+ let langId = 0x0800 as c::DWORD;
+
+ let mut buf = [0 as c::WCHAR; 2048];
+
+ unsafe {
+ let mut module = ptr::null_mut();
+ let mut flags = 0;
+
+ // NTSTATUS errors may be encoded as HRESULT, which may returned from
+ // GetLastError. For more information about Windows error codes, see
+ // `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx
+ if (errnum & c::FACILITY_NT_BIT as i32) != 0 {
+ // format according to https://support.microsoft.com/en-us/help/259693
+ const NTDLL_DLL: &[u16] = &[
+ 'N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, '.' as _, 'D' as _, 'L' as _,
+ 'L' as _, 0,
+ ];
+ module = c::GetModuleHandleW(NTDLL_DLL.as_ptr());
+
+ if module != ptr::null_mut() {
+ errnum ^= c::FACILITY_NT_BIT as i32;
+ flags = c::FORMAT_MESSAGE_FROM_HMODULE;
+ }
+ }
+
+ let res = c::FormatMessageW(
+ flags | c::FORMAT_MESSAGE_FROM_SYSTEM | c::FORMAT_MESSAGE_IGNORE_INSERTS,
+ module,
+ errnum as c::DWORD,
+ langId,
+ buf.as_mut_ptr(),
+ buf.len() as c::DWORD,
+ ptr::null(),
+ ) as usize;
+ if res == 0 {
+ // Sometimes FormatMessageW can fail e.g., system doesn't like langId,
+ let fm_err = errno();
+ return format!(
+ "OS Error {} (FormatMessageW() returned error {})",
+ errnum, fm_err
+ );
+ }
+
+ match String::from_utf16(&buf[..res]) {
+ Ok(mut msg) => {
+ // Trim trailing CRLF inserted by FormatMessageW
+ let len = msg.trim_end().len();
+ msg.truncate(len);
+ msg
+ }
+ Err(..) => format!(
+ "OS Error {} (FormatMessageW() returned \
+ invalid UTF-16)",
+ errnum
+ ),
+ }
+ }
+}