Fix Windows ZLUDA injector (#26)

Fix various bugs in injector and redirector, make them more robust and enable building them by default
This commit is contained in:
Andrzej Janik 2021-01-03 18:45:48 +01:00 committed by GitHub
parent 659b2c6ec4
commit 2c0e9b912f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 1893 additions and 138 deletions

View file

@ -1,12 +1,13 @@
[workspace]
members = [
"detours-sys",
"level_zero-sys",
"level_zero",
"spirv_tools-sys",
"zluda",
#"zluda_inject",
#"zluda_redirect",
"zluda_inject",
"zluda_redirect",
"ptx",
]

39
detours-sys/Cargo.toml Normal file
View file

@ -0,0 +1,39 @@
[package]
name = "detours-sys"
version = "0.1.2"
authors = ["Diana <5275194+DianaNites@users.noreply.github.com>"]
edition = "2018"
links = "detours"
# Package stuff
description = "Rust bindings to Microsoft Detours"
documentation = "https://github.com/microsoft/Detours/wiki/Reference"
homepage = "https://github.com/DianaNites/detours"
repository = "https://github.com/DianaNites/detours"
readme = "README.md"
keywords = [
"detours",
"hooking",
"injection",
]
categories = [
"external-ffi-bindings",
"os::windows-apis",
]
license = "MIT OR Apache-2.0"
exclude = [
"/.vscode/**"
]
[badges]
maintenance = { status = "as-is" }
[dev-dependencies.winapi]
version = "0.3"
features = [
"synchapi",
"processthreadsapi",
"sysinfoapi",
]
[build-dependencies]
cc = "1.0"

202
detours-sys/LICENSE-APACHE Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

7
detours-sys/LICENSE-MIT Normal file
View file

@ -0,0 +1,7 @@
Copyright 2019 Diana
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

34
detours-sys/README.md Normal file
View file

@ -0,0 +1,34 @@
# Detours-sys
[![Crates.io](https://img.shields.io/crates/v/detours-sys.svg)](https://crates.io/crates/detours-sys)
![maintenance-as-is](https://img.shields.io/badge/maintenance-as--is-yellow.svg)
Rust bindings to [Microsoft Detours](https://github.com/Microsoft/Detours)
## Usage
See the [Detours Documentation](https://github.com/Microsoft/Detours/wiki) for details.
## Details
Use the `buildtime_generation` feature to generate bindings at build time,
otherwise use pregenerated bindings.
Note that this will require a relatively recent version of Clang be installed.
## License
Licensed under either of
* Apache License, Version 2.0
([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
* MIT license
([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
at your option.
## Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.

54
detours-sys/build.rs Normal file
View file

@ -0,0 +1,54 @@
use std::error::Error;
#[cfg(not(target_os = "windows"))]
fn main() {}
#[cfg(target_os = "windows")]
fn main() -> Result<(), Box<dyn Error>> {
windows::main_impl()
}
#[cfg(target_os = "windows")]
mod windows {
use std::error::Error;
const CPP_FILES: [&'static str; 5] = [
"../ext/detours/src/creatwth.cpp",
"../ext/detours/src/detours.cpp",
"../ext/detours/src/disasm.cpp",
"../ext/detours/src/image.cpp",
"../ext/detours/src/modules.cpp",
];
pub fn main_impl() -> Result<(), Box<dyn Error>> {
println!("cargo:rerun-if-changed=build/wrapper.h");
for f in &CPP_FILES {
println!("cargo:rerun-if-changed={}", f);
}
build_detours()
}
fn build_detours() -> Result<(), Box<dyn Error>> {
add_target_options(
cc::Build::new()
.include("../ext/detours/src")
.files(&CPP_FILES),
)
.try_compile("detours")?;
Ok(())
}
#[cfg(target_env = "msvc")]
fn add_target_options(build: &mut cc::Build) -> &mut cc::Build {
build
}
#[cfg(not(target_env = "msvc"))]
fn add_target_options(build: &mut cc::Build) -> &mut cc::Build {
build
.compiler("clang")
.cpp(true)
.flag("-fms-extensions")
.flag("-Wno-everything")
}
}

View file

@ -0,0 +1,2 @@
#include <windows.h>
#include <detours.h>

File diff suppressed because it is too large Load diff

78
detours-sys/src/lib.rs Normal file
View file

@ -0,0 +1,78 @@
#![cfg(target_os = "windows")]
//! Bindings to the Microsoft Detours API.
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
// Rebuild with:
// bindgen ..\build\wrapper.h --whitelist-function "Detour.*" -o bundled_bindings.rs -- "-fms-compatibility" "-fms-extensions" --target=x86_64-pc-windows-msvc -I ..\..\ext\detours\src\
include!("bundled_bindings.rs");
#[cfg(test)]
mod tests {
use super::*;
use std::{ffi, ptr};
use winapi::{
shared::minwindef::LPVOID,
um::{processthreadsapi::GetCurrentThread, synchapi::Sleep, sysinfoapi::GetTickCount},
};
static mut TRUE_SLEEP: unsafe extern "system" fn(DWORD) = Sleep;
static mut SLEPT: LONG = 0;
// Detour function that replaces the Sleep API.
unsafe extern "system" fn TimedSleep(dwMilliseconds: DWORD) {
// Save the before and after times around calling the Sleep API.
let dwBeg: DWORD = GetTickCount();
TRUE_SLEEP(dwMilliseconds);
let dwEnd: DWORD = GetTickCount();
SLEPT = (dwEnd - dwBeg) as i32;
}
extern "system" fn DllMain(_: HINSTANCE, reason: DWORD, _: LPVOID) -> BOOL {
if unsafe { DetourIsHelperProcess() } == 1 {
return 1;
}
let tru = unsafe { &mut TRUE_SLEEP as *mut _ as *mut *mut ffi::c_void };
let new = TimedSleep as *mut ffi::c_void;
match reason {
// DLL_PROCESS_ATTACH
1 => unsafe {
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread() as _);
DetourAttach(tru, new);
DetourTransactionCommit();
},
// DLL_PROCESS_DETACH
0 => unsafe {
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread() as _);
DetourDetach(tru, new);
DetourTransactionCommit();
},
_ => (),
}
1
}
#[test]
fn hook_self() {
unsafe {
DllMain(ptr::null_mut(), 1, ptr::null_mut());
let slept;
Sleep(500);
slept = SLEPT;
assert_ne!(SLEPT, 0);
DllMain(ptr::null_mut(), 0, ptr::null_mut());
Sleep(500);
assert_eq!(slept, SLEPT);
}
}
}

View file

@ -9,8 +9,5 @@ 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"
winapi = { version = "0.3", features = ["jobapi2", "processthreadsapi", "std", "synchapi"] }
detours-sys = { path = "../detours-sys" }

View file

@ -1,58 +1,39 @@
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::env;
use std::env::Args;
use std::mem;
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::ptr;
use std::{error::Error, process};
use mem::size_of_val;
use winapi::um::{
jobapi2::{AssignProcessToJobObject, SetInformationJobObject},
processthreadsapi::{GetExitCodeProcess, ResumeThread},
synchapi::WaitForSingleObject,
winbase::CreateJobObjectA,
winnt::{
JobObjectExtendedLimitInformation, HANDLE, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
},
};
use winapi::um::processthreadsapi::{GetExitCodeProcess, ResumeThread};
use winapi::um::synchapi::WaitForSingleObject;
use winapi::um::winbase::{INFINITE, WAIT_FAILED};
use clap::{App, AppSettings, Arg};
static REDIRECT_DLL: &'static str = "zluda_redirect.dll";
static ZLUDA_DLL: &'static str = "nvcuda.dll";
#[macro_use]
mod win;
include!("../../zluda_redirect/src/payload_guid.rs");
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);
pub fn main_impl() -> Result<(), Box<dyn Error>> {
let args = env::args();
if args.len() == 0 {
print_help();
process::exit(1);
}
let mut cmd_line = construct_command_line(args);
let injector_path = env::current_exe()?;
let injector_dir = injector_path.parent().unwrap();
let redirect_path = create_redirect_path(injector_dir);
let mut startup_info = unsafe { mem::zeroed::<detours_sys::_STARTUPINFOW>() };
let mut proc_info = unsafe { mem::zeroed::<detours_sys::_PROCESS_INFORMATION>() };
os_call!(
@ -67,22 +48,19 @@ fn main() -> Result<(), Box<dyn Error>> {
ptr::null(),
&mut startup_info as *mut _,
&mut proc_info as *mut _,
"zluda_redirect.dll\0".as_ptr() as *const i8,
redirect_path.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"};
kill_child_on_process_exit(proc_info.hProcess)?;
let mut zluda_path = create_zluda_path(injector_dir);
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
&PAYLOAD_GUID,
zluda_path.as_mut_ptr() as *mut _,
(zluda_path.len() * mem::size_of::<u16>()) as u32
),
|x| x != 0
);
@ -94,13 +72,110 @@ fn main() -> Result<(), Box<dyn Error>> {
GetExitCodeProcess(proc_info.hProcess, &mut child_exit_code as *mut _),
|x| x != 0
);
std::process::exit(child_exit_code as i32)
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);
fn kill_child_on_process_exit(child: HANDLE) -> Result<(), Box<dyn Error>> {
let job_handle = os_call!(CreateJobObjectA(ptr::null_mut(), ptr::null()), |x| x
!= ptr::null_mut());
let mut info = unsafe { mem::zeroed::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() };
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
os_call!(
SetInformationJobObject(
job_handle,
JobObjectExtendedLimitInformation,
&mut info as *mut _ as *mut _,
size_of_val(&info) as u32
),
|x| x != 0
);
os_call!(AssignProcessToJobObject(job_handle, child), |x| x != 0);
Ok(())
}
fn print_help() {
println!(
"USAGE:
zluda <EXE> [ARGS]...
ARGS:
<EXE> Path to the executable to be injected with ZLUDA
<ARGS>... Arguments that will be passed to <EXE>
"
);
}
// Adapted from https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way
fn construct_command_line(args: Args) -> Vec<u16> {
let mut cmd_line = Vec::new();
let args_len = args.len();
for (idx, arg) in args.enumerate().skip(1) {
if !arg.contains(&[' ', '\t', '\n', '\u{2B7F}', '\"'][..]) {
cmd_line.extend(arg.encode_utf16());
} else {
cmd_line.push('"' as u16); // "
let mut char_iter = arg.chars().peekable();
loop {
let mut current = char_iter.next();
let mut backslashes = 0;
match current {
Some('\\') => {
backslashes = 1;
while let Some('\\') = char_iter.peek() {
backslashes += 1;
char_iter.next();
}
current = char_iter.next();
}
_ => {}
}
match current {
None => {
for _ in 0..(backslashes * 2) {
cmd_line.push('\\' as u16);
}
break;
}
Some('"') => {
for _ in 0..(backslashes * 2 + 1) {
cmd_line.push('\\' as u16);
}
cmd_line.push('"' as u16);
}
Some(c) => {
for _ in 0..backslashes {
cmd_line.push('\\' as u16);
}
let mut temp = [0u16; 2];
cmd_line.extend(&*c.encode_utf16(&mut temp));
}
}
}
cmd_line.push('"' as u16);
}
if idx < args_len - 1 {
cmd_line.push(' ' as u16);
}
}
cmd_line.push(0);
cmd_line
}
//
fn create_redirect_path(injector_dir: &Path) -> Vec<u8> {
let mut injector_dir = injector_dir.to_path_buf();
injector_dir.push(REDIRECT_DLL);
let mut result = injector_dir.to_string_lossy().into_owned().into_bytes();
result.push(0);
result
}
fn create_zluda_path(injector_dir: &Path) -> Vec<u16> {
let mut injector_dir = injector_dir.to_path_buf();
injector_dir.push(ZLUDA_DLL);
let mut result = injector_dir
.to_string_lossy()
.as_ref()
.encode_utf16()
.collect::<Vec<_>>();
result.push(0);
result
}

View file

@ -1,5 +1,15 @@
#[cfg(target_os = "windows")]
mod bin;
#[cfg(not(target_os = "windows"))]
fn main() {}
#[macro_use]
#[cfg(target_os = "windows")]
mod win;
#[cfg(target_os = "windows")]
mod bin;
use std::error::Error;
#[cfg(target_os = "windows")]
fn main() -> Result<(), Box<dyn Error>> {
bin::main_impl()
}
#[cfg(not(target_os = "windows"))]
fn main() {}

View file

@ -48,15 +48,18 @@ macro_rules! last_ident {
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)
})?;
{
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)
})?;
}
result
}
};
}

View file

@ -8,7 +8,6 @@ edition = "2018"
crate-type = ["cdylib"]
[target.'cfg(windows)'.dependencies]
detours-sys = "0.1"
detours-sys = { path = "../detours-sys" }
wchar = "0.6"
guid = "0.1"
winapi = { version = "0.3", features = ["processthreadsapi", "winbase", "winnt", "winerror", "libloaderapi", "std"] }

View file

@ -1,105 +1,254 @@
#![cfg(windows)]
#![cfg(target_os = "windows")]
extern crate detours_sys;
#[macro_use]
extern crate guid;
extern crate winapi;
use std::mem;
use std::{mem, ptr, slice};
use detours_sys::{
DetourAttach, DetourDetach, DetourRestoreAfterWith, DetourTransactionBegin,
DetourTransactionCommit, DetourUpdateThread,
};
use wchar::{wch, wch_c};
use winapi::shared::minwindef::{DWORD, FALSE, HMODULE, TRUE};
use winapi::um::libloaderapi::LoadLibraryExW;
use wchar::wch;
use winapi::um::processthreadsapi::GetCurrentThread;
use winapi::um::winbase::lstrcmpiW;
use winapi::um::winnt::{DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, HANDLE, LPCWSTR};
use winapi::{
shared::minwindef::{DWORD, FALSE, HMODULE, TRUE},
um::{libloaderapi::LoadLibraryExA, winnt::LPCSTR},
};
use winapi::{
shared::winerror::NO_ERROR,
um::libloaderapi::{LoadLibraryA, LoadLibraryExW, LoadLibraryW},
};
const NVCUDA_PATH: &[u16] = wch_c!(r"C:\WINDOWS\system32\nvcuda.dll");
const ZLUDA_DLL: &[u16] = wch!(r"nvcuda.dll");
static mut ZLUDA_PATH: Option<Vec<u16>> = None;
include!("payload_guid.rs");
static mut LOAD_LIBRARY_EX: unsafe extern "system" fn(
const NVCUDA_UTF8: &'static str = "NVCUDA.DLL";
const NVCUDA_UTF16: &[u16] = wch!("NVCUDA.DLL");
static mut ZLUDA_PATH_UTF8: Vec<u8> = Vec::new();
static mut ZLUDA_PATH_UTF16: Option<&'static [u16]> = None;
static mut LOAD_LIBRARY_A: unsafe extern "system" fn(lpLibFileName: LPCSTR) -> HMODULE =
LoadLibraryA;
static mut LOAD_LIBRARY_W: unsafe extern "system" fn(lpLibFileName: LPCWSTR) -> HMODULE =
LoadLibraryW;
static mut LOAD_LIBRARY_EX_A: unsafe extern "system" fn(
lpLibFileName: LPCSTR,
hFile: HANDLE,
dwFlags: DWORD,
) -> HMODULE = LoadLibraryExA;
static mut LOAD_LIBRARY_EX_W: unsafe extern "system" fn(
lpLibFileName: LPCWSTR,
hFile: HANDLE,
dwFlags: DWORD,
) -> HMODULE = LoadLibraryExW;
#[allow(non_snake_case)]
#[no_mangle]
unsafe extern "system" fn ZludaLoadLibraryA(lpLibFileName: LPCSTR) -> HMODULE {
let nvcuda_file_name = if is_nvcuda_dll_utf8(lpLibFileName as *const _) {
ZLUDA_PATH_UTF8.as_ptr() as *const _
} else {
lpLibFileName
};
(LOAD_LIBRARY_A)(nvcuda_file_name)
}
#[allow(non_snake_case)]
unsafe extern "system" fn ZludaLoadLibraryW(lpLibFileName: LPCWSTR) -> HMODULE {
let nvcuda_file_name = if is_nvcuda_dll_utf16(lpLibFileName) {
ZLUDA_PATH_UTF16.unwrap().as_ptr()
} else {
lpLibFileName
};
(LOAD_LIBRARY_W)(nvcuda_file_name)
}
#[allow(non_snake_case)]
unsafe extern "system" fn ZludaLoadLibraryExA(
lpLibFileName: LPCSTR,
hFile: HANDLE,
dwFlags: DWORD,
) -> HMODULE {
let nvcuda_file_name = if is_nvcuda_dll_utf8(lpLibFileName as *const _) {
ZLUDA_PATH_UTF8.as_ptr() as *const _
} else {
lpLibFileName
};
(LOAD_LIBRARY_EX_A)(nvcuda_file_name, hFile, dwFlags)
}
#[allow(non_snake_case)]
unsafe extern "system" fn ZludaLoadLibraryExW(
lpLibFileName: LPCWSTR,
hFile: HANDLE,
dwFlags: DWORD,
) -> HMODULE {
let nvcuda_file_name = if lstrcmpiW(lpLibFileName, NVCUDA_PATH.as_ptr()) == 0 {
ZLUDA_PATH.as_ref().unwrap().as_ptr()
let nvcuda_file_name = if is_nvcuda_dll_utf16(lpLibFileName) {
ZLUDA_PATH_UTF16.unwrap().as_ptr()
} else {
lpLibFileName
};
(LOAD_LIBRARY_EX)(nvcuda_file_name, hFile, dwFlags)
(LOAD_LIBRARY_EX_W)(nvcuda_file_name, hFile, dwFlags)
}
fn is_nvcuda_dll_utf8(lib: *const u8) -> bool {
is_nvcuda_dll(lib, 0, NVCUDA_UTF8.as_bytes(), |c| {
if c >= 'a' as u8 && c <= 'z' as u8 {
c - 32
} else {
c
}
})
}
fn is_nvcuda_dll_utf16(lib: *const u16) -> bool {
is_nvcuda_dll(lib, 0u16, NVCUDA_UTF16, |c| {
if c >= 'a' as u16 && c <= 'z' as u16 {
c - 32
} else {
c
}
})
}
fn is_nvcuda_dll<T: Copy + PartialEq>(
lib: *const T,
zero: T,
dll_name: &[T],
uppercase: impl Fn(T) -> T,
) -> bool {
let mut len = 0;
loop {
if unsafe { *lib.offset(len) } == zero {
break;
}
len += 1;
}
if (len as usize) < dll_name.len() {
return false;
}
let slice =
unsafe { slice::from_raw_parts(lib.offset(len - dll_name.len() as isize), dll_name.len()) };
for i in 0..dll_name.len() {
if uppercase(slice[i]) != dll_name[i] {
return false;
}
}
true
}
#[allow(non_snake_case)]
#[no_mangle]
unsafe extern "system" fn DllMain(_: *const u8, dwReason: u32, _: *const u8) -> i32 {
if dwReason == DLL_PROCESS_ATTACH {
DetourRestoreAfterWith();
if DetourRestoreAfterWith() == FALSE {
return FALSE;
}
match get_zluda_dll_path() {
Some((path, len)) => set_zluda_dll_path(path, len),
Some(path) => {
ZLUDA_PATH_UTF16 = Some(path);
ZLUDA_PATH_UTF8 = String::from_utf16_lossy(path).into_bytes();
}
None => return FALSE,
}
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(
std::mem::transmute(&mut LOAD_LIBRARY_EX),
if DetourTransactionBegin() != NO_ERROR as i32 {
return FALSE;
}
if DetourUpdateThread(GetCurrentThread()) != NO_ERROR as i32 {
return FALSE;
}
if DetourAttach(
mem::transmute(&mut LOAD_LIBRARY_A),
ZludaLoadLibraryA as *mut _,
) != NO_ERROR as i32
{
return FALSE;
}
if DetourAttach(
mem::transmute(&mut LOAD_LIBRARY_W),
ZludaLoadLibraryW as *mut _,
) != NO_ERROR as i32
{
return FALSE;
}
if DetourAttach(
mem::transmute(&mut LOAD_LIBRARY_EX_A),
ZludaLoadLibraryExA as *mut _,
) != NO_ERROR as i32
{
return FALSE;
}
if DetourAttach(
mem::transmute(&mut LOAD_LIBRARY_EX_W),
ZludaLoadLibraryExW as *mut _,
);
DetourTransactionCommit();
) != NO_ERROR as i32
{
return FALSE;
}
if DetourTransactionCommit() != NO_ERROR as i32 {
return FALSE;
}
} else if dwReason == DLL_PROCESS_DETACH {
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(
std::mem::transmute(&mut LOAD_LIBRARY_EX),
if DetourTransactionBegin() != NO_ERROR as i32 {
return FALSE;
}
if DetourUpdateThread(GetCurrentThread()) != NO_ERROR as i32 {
return FALSE;
}
if DetourDetach(
mem::transmute(&mut LOAD_LIBRARY_A),
ZludaLoadLibraryA as *mut _,
) != NO_ERROR as i32
{
return FALSE;
}
if DetourDetach(
mem::transmute(&mut LOAD_LIBRARY_W),
ZludaLoadLibraryW as *mut _,
) != NO_ERROR as i32
{
return FALSE;
}
if DetourDetach(
mem::transmute(&mut LOAD_LIBRARY_EX_A),
ZludaLoadLibraryExA as *mut _,
) != NO_ERROR as i32
{
return FALSE;
}
if DetourDetach(
mem::transmute(&mut LOAD_LIBRARY_EX_W),
ZludaLoadLibraryExW as *mut _,
);
DetourTransactionCommit();
) != NO_ERROR as i32
{
return FALSE;
}
if DetourTransactionCommit() != NO_ERROR as i32 {
return FALSE;
}
}
TRUE
}
fn get_zluda_dll_path() -> Option<(*const u16, usize)> {
let guid = guid! {"C225FC0C-00D7-40B8-935A-7E342A9344C1"};
let mut module = std::ptr::null_mut();
fn get_zluda_dll_path() -> Option<&'static [u16]> {
let mut module = ptr::null_mut();
loop {
module = unsafe { detours_sys::DetourEnumerateModules(module) };
if module == std::ptr::null_mut() {
if module == ptr::null_mut() {
break;
}
let mut size = 0;
let payload = unsafe {
detours_sys::DetourFindPayload(module, std::mem::transmute(&guid), &mut size)
};
if payload != std::ptr::null_mut() {
return Some((payload as *const _, (size as usize) / mem::size_of::<u16>()));
let payload = unsafe { detours_sys::DetourFindPayload(module, &PAYLOAD_GUID, &mut size) };
if payload != ptr::null_mut() {
return unsafe {
Some(slice::from_raw_parts(
payload as *const _,
(size as usize) / mem::size_of::<u16>(),
))
};
}
}
None
}
unsafe fn set_zluda_dll_path(path: *const u16, len: usize) {
let len = len as usize;
let mut result = Vec::<u16>::with_capacity(len + ZLUDA_DLL.len() + 2);
for i in 0..len {
result.push(*path.add(i));
}
result.push(0x5c); // \
for c in ZLUDA_DLL.iter().copied() {
result.push(c);
}
result.push(0);
ZLUDA_PATH = Some(result);
}

View file

@ -0,0 +1,6 @@
const PAYLOAD_GUID: detours_sys::GUID = detours_sys::GUID {
Data1: 0xC225FC0C,
Data2: 0x00D7,
Data3: 0x40B8,
Data4: [0x93, 0x5A, 0x7E, 0x34, 0x2A, 0x93, 0x44, 0xC1],
};