From 2c0e9b912fe341bd1e513614014fa43b666d257d Mon Sep 17 00:00:00 2001 From: Andrzej Janik Date: Sun, 3 Jan 2021 18:45:48 +0100 Subject: [PATCH] Fix Windows ZLUDA injector (#26) Fix various bugs in injector and redirector, make them more robust and enable building them by default --- Cargo.toml | 5 +- detours-sys/Cargo.toml | 39 + detours-sys/LICENSE-APACHE | 202 +++++ detours-sys/LICENSE-MIT | 7 + detours-sys/README.md | 34 + detours-sys/build.rs | 54 ++ detours-sys/build/wrapper.h | 2 + detours-sys/src/bundled_bindings.rs | 1099 +++++++++++++++++++++++++++ detours-sys/src/lib.rs | 78 ++ zluda_inject/Cargo.toml | 7 +- zluda_inject/src/bin.rs | 199 +++-- zluda_inject/src/main.rs | 20 +- zluda_inject/src/win.rs | 21 +- zluda_redirect/Cargo.toml | 3 +- zluda_redirect/src/lib.rs | 255 +++++-- zluda_redirect/src/payload_guid.rs | 6 + 16 files changed, 1893 insertions(+), 138 deletions(-) create mode 100644 detours-sys/Cargo.toml create mode 100644 detours-sys/LICENSE-APACHE create mode 100644 detours-sys/LICENSE-MIT create mode 100644 detours-sys/README.md create mode 100644 detours-sys/build.rs create mode 100644 detours-sys/build/wrapper.h create mode 100644 detours-sys/src/bundled_bindings.rs create mode 100644 detours-sys/src/lib.rs create mode 100644 zluda_redirect/src/payload_guid.rs diff --git a/Cargo.toml b/Cargo.toml index d50aad0..7511701 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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", ] diff --git a/detours-sys/Cargo.toml b/detours-sys/Cargo.toml new file mode 100644 index 0000000..9ba0a3f --- /dev/null +++ b/detours-sys/Cargo.toml @@ -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" diff --git a/detours-sys/LICENSE-APACHE b/detours-sys/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/detours-sys/LICENSE-APACHE @@ -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. diff --git a/detours-sys/LICENSE-MIT b/detours-sys/LICENSE-MIT new file mode 100644 index 0000000..693dd0f --- /dev/null +++ b/detours-sys/LICENSE-MIT @@ -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. diff --git a/detours-sys/README.md b/detours-sys/README.md new file mode 100644 index 0000000..ba5d2bc --- /dev/null +++ b/detours-sys/README.md @@ -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 ) +* MIT license + ([LICENSE-MIT](LICENSE-MIT) or ) + +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. diff --git a/detours-sys/build.rs b/detours-sys/build.rs new file mode 100644 index 0000000..f3da0e6 --- /dev/null +++ b/detours-sys/build.rs @@ -0,0 +1,54 @@ +use std::error::Error; + +#[cfg(not(target_os = "windows"))] +fn main() {} + +#[cfg(target_os = "windows")] +fn main() -> Result<(), Box> { + 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> { + 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> { + 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") + } +} diff --git a/detours-sys/build/wrapper.h b/detours-sys/build/wrapper.h new file mode 100644 index 0000000..9524b80 --- /dev/null +++ b/detours-sys/build/wrapper.h @@ -0,0 +1,2 @@ +#include +#include diff --git a/detours-sys/src/bundled_bindings.rs b/detours-sys/src/bundled_bindings.rs new file mode 100644 index 0000000..7262bc8 --- /dev/null +++ b/detours-sys/src/bundled_bindings.rs @@ -0,0 +1,1099 @@ +/* automatically generated by rust-bindgen 0.56.0 */ + +pub type wchar_t = ::std::os::raw::c_ushort; +pub type ULONG = ::std::os::raw::c_ulong; +pub type DWORD = ::std::os::raw::c_ulong; +pub type BOOL = ::std::os::raw::c_int; +pub type BYTE = ::std::os::raw::c_uchar; +pub type WORD = ::std::os::raw::c_ushort; +pub type LPBYTE = *mut BYTE; +pub type PDWORD = *mut DWORD; +pub type LPVOID = *mut ::std::os::raw::c_void; +pub type LPCVOID = *const ::std::os::raw::c_void; +pub type INT = ::std::os::raw::c_int; +pub type PVOID = *mut ::std::os::raw::c_void; +pub type CHAR = ::std::os::raw::c_char; +pub type LONG = ::std::os::raw::c_long; +pub type WCHAR = wchar_t; +pub type LPWSTR = *mut WCHAR; +pub type LPCWSTR = *const WCHAR; +pub type LPSTR = *mut CHAR; +pub type LPCSTR = *const CHAR; +pub type HANDLE = *mut ::std::os::raw::c_void; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct _GUID { + pub Data1: ::std::os::raw::c_ulong, + pub Data2: ::std::os::raw::c_ushort, + pub Data3: ::std::os::raw::c_ushort, + pub Data4: [::std::os::raw::c_uchar; 8usize], +} +#[test] +fn bindgen_test_layout__GUID() { + assert_eq!( + ::std::mem::size_of::<_GUID>(), + 16usize, + concat!("Size of: ", stringify!(_GUID)) + ); + assert_eq!( + ::std::mem::align_of::<_GUID>(), + 4usize, + concat!("Alignment of ", stringify!(_GUID)) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_GUID>())).Data1 as *const _ as usize }, + 0usize, + concat!( + "Offset of field: ", + stringify!(_GUID), + "::", + stringify!(Data1) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_GUID>())).Data2 as *const _ as usize }, + 4usize, + concat!( + "Offset of field: ", + stringify!(_GUID), + "::", + stringify!(Data2) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_GUID>())).Data3 as *const _ as usize }, + 6usize, + concat!( + "Offset of field: ", + stringify!(_GUID), + "::", + stringify!(Data3) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_GUID>())).Data4 as *const _ as usize }, + 8usize, + concat!( + "Offset of field: ", + stringify!(_GUID), + "::", + stringify!(Data4) + ) + ); +} +pub type GUID = _GUID; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct HINSTANCE__ { + pub unused: ::std::os::raw::c_int, +} +#[test] +fn bindgen_test_layout_HINSTANCE__() { + assert_eq!( + ::std::mem::size_of::(), + 4usize, + concat!("Size of: ", stringify!(HINSTANCE__)) + ); + assert_eq!( + ::std::mem::align_of::(), + 4usize, + concat!("Alignment of ", stringify!(HINSTANCE__)) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::())).unused as *const _ as usize }, + 0usize, + concat!( + "Offset of field: ", + stringify!(HINSTANCE__), + "::", + stringify!(unused) + ) + ); +} +pub type HINSTANCE = *mut HINSTANCE__; +pub type HMODULE = HINSTANCE; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct HWND__ { + pub unused: ::std::os::raw::c_int, +} +#[test] +fn bindgen_test_layout_HWND__() { + assert_eq!( + ::std::mem::size_of::(), + 4usize, + concat!("Size of: ", stringify!(HWND__)) + ); + assert_eq!( + ::std::mem::align_of::(), + 4usize, + concat!("Alignment of ", stringify!(HWND__)) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::())).unused as *const _ as usize }, + 0usize, + concat!( + "Offset of field: ", + stringify!(HWND__), + "::", + stringify!(unused) + ) + ); +} +pub type HWND = *mut HWND__; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct _SECURITY_ATTRIBUTES { + pub nLength: DWORD, + pub lpSecurityDescriptor: LPVOID, + pub bInheritHandle: BOOL, +} +#[test] +fn bindgen_test_layout__SECURITY_ATTRIBUTES() { + assert_eq!( + ::std::mem::size_of::<_SECURITY_ATTRIBUTES>(), + 24usize, + concat!("Size of: ", stringify!(_SECURITY_ATTRIBUTES)) + ); + assert_eq!( + ::std::mem::align_of::<_SECURITY_ATTRIBUTES>(), + 8usize, + concat!("Alignment of ", stringify!(_SECURITY_ATTRIBUTES)) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_SECURITY_ATTRIBUTES>())).nLength as *const _ as usize }, + 0usize, + concat!( + "Offset of field: ", + stringify!(_SECURITY_ATTRIBUTES), + "::", + stringify!(nLength) + ) + ); + assert_eq!( + unsafe { + &(*(::std::ptr::null::<_SECURITY_ATTRIBUTES>())).lpSecurityDescriptor as *const _ + as usize + }, + 8usize, + concat!( + "Offset of field: ", + stringify!(_SECURITY_ATTRIBUTES), + "::", + stringify!(lpSecurityDescriptor) + ) + ); + assert_eq!( + unsafe { + &(*(::std::ptr::null::<_SECURITY_ATTRIBUTES>())).bInheritHandle as *const _ as usize + }, + 16usize, + concat!( + "Offset of field: ", + stringify!(_SECURITY_ATTRIBUTES), + "::", + stringify!(bInheritHandle) + ) + ); +} +pub type LPSECURITY_ATTRIBUTES = *mut _SECURITY_ATTRIBUTES; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct _PROCESS_INFORMATION { + pub hProcess: HANDLE, + pub hThread: HANDLE, + pub dwProcessId: DWORD, + pub dwThreadId: DWORD, +} +#[test] +fn bindgen_test_layout__PROCESS_INFORMATION() { + assert_eq!( + ::std::mem::size_of::<_PROCESS_INFORMATION>(), + 24usize, + concat!("Size of: ", stringify!(_PROCESS_INFORMATION)) + ); + assert_eq!( + ::std::mem::align_of::<_PROCESS_INFORMATION>(), + 8usize, + concat!("Alignment of ", stringify!(_PROCESS_INFORMATION)) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_PROCESS_INFORMATION>())).hProcess as *const _ as usize }, + 0usize, + concat!( + "Offset of field: ", + stringify!(_PROCESS_INFORMATION), + "::", + stringify!(hProcess) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_PROCESS_INFORMATION>())).hThread as *const _ as usize }, + 8usize, + concat!( + "Offset of field: ", + stringify!(_PROCESS_INFORMATION), + "::", + stringify!(hThread) + ) + ); + assert_eq!( + unsafe { + &(*(::std::ptr::null::<_PROCESS_INFORMATION>())).dwProcessId as *const _ as usize + }, + 16usize, + concat!( + "Offset of field: ", + stringify!(_PROCESS_INFORMATION), + "::", + stringify!(dwProcessId) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_PROCESS_INFORMATION>())).dwThreadId as *const _ as usize }, + 20usize, + concat!( + "Offset of field: ", + stringify!(_PROCESS_INFORMATION), + "::", + stringify!(dwThreadId) + ) + ); +} +pub type LPPROCESS_INFORMATION = *mut _PROCESS_INFORMATION; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct _STARTUPINFOA { + pub cb: DWORD, + pub lpReserved: LPSTR, + pub lpDesktop: LPSTR, + pub lpTitle: LPSTR, + pub dwX: DWORD, + pub dwY: DWORD, + pub dwXSize: DWORD, + pub dwYSize: DWORD, + pub dwXCountChars: DWORD, + pub dwYCountChars: DWORD, + pub dwFillAttribute: DWORD, + pub dwFlags: DWORD, + pub wShowWindow: WORD, + pub cbReserved2: WORD, + pub lpReserved2: LPBYTE, + pub hStdInput: HANDLE, + pub hStdOutput: HANDLE, + pub hStdError: HANDLE, +} +#[test] +fn bindgen_test_layout__STARTUPINFOA() { + assert_eq!( + ::std::mem::size_of::<_STARTUPINFOA>(), + 104usize, + concat!("Size of: ", stringify!(_STARTUPINFOA)) + ); + assert_eq!( + ::std::mem::align_of::<_STARTUPINFOA>(), + 8usize, + concat!("Alignment of ", stringify!(_STARTUPINFOA)) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).cb as *const _ as usize }, + 0usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(cb) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).lpReserved as *const _ as usize }, + 8usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(lpReserved) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).lpDesktop as *const _ as usize }, + 16usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(lpDesktop) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).lpTitle as *const _ as usize }, + 24usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(lpTitle) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).dwX as *const _ as usize }, + 32usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(dwX) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).dwY as *const _ as usize }, + 36usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(dwY) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).dwXSize as *const _ as usize }, + 40usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(dwXSize) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).dwYSize as *const _ as usize }, + 44usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(dwYSize) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).dwXCountChars as *const _ as usize }, + 48usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(dwXCountChars) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).dwYCountChars as *const _ as usize }, + 52usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(dwYCountChars) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).dwFillAttribute as *const _ as usize }, + 56usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(dwFillAttribute) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).dwFlags as *const _ as usize }, + 60usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(dwFlags) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).wShowWindow as *const _ as usize }, + 64usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(wShowWindow) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).cbReserved2 as *const _ as usize }, + 66usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(cbReserved2) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).lpReserved2 as *const _ as usize }, + 72usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(lpReserved2) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).hStdInput as *const _ as usize }, + 80usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(hStdInput) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).hStdOutput as *const _ as usize }, + 88usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(hStdOutput) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOA>())).hStdError as *const _ as usize }, + 96usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOA), + "::", + stringify!(hStdError) + ) + ); +} +pub type LPSTARTUPINFOA = *mut _STARTUPINFOA; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct _STARTUPINFOW { + pub cb: DWORD, + pub lpReserved: LPWSTR, + pub lpDesktop: LPWSTR, + pub lpTitle: LPWSTR, + pub dwX: DWORD, + pub dwY: DWORD, + pub dwXSize: DWORD, + pub dwYSize: DWORD, + pub dwXCountChars: DWORD, + pub dwYCountChars: DWORD, + pub dwFillAttribute: DWORD, + pub dwFlags: DWORD, + pub wShowWindow: WORD, + pub cbReserved2: WORD, + pub lpReserved2: LPBYTE, + pub hStdInput: HANDLE, + pub hStdOutput: HANDLE, + pub hStdError: HANDLE, +} +#[test] +fn bindgen_test_layout__STARTUPINFOW() { + assert_eq!( + ::std::mem::size_of::<_STARTUPINFOW>(), + 104usize, + concat!("Size of: ", stringify!(_STARTUPINFOW)) + ); + assert_eq!( + ::std::mem::align_of::<_STARTUPINFOW>(), + 8usize, + concat!("Alignment of ", stringify!(_STARTUPINFOW)) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).cb as *const _ as usize }, + 0usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(cb) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).lpReserved as *const _ as usize }, + 8usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(lpReserved) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).lpDesktop as *const _ as usize }, + 16usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(lpDesktop) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).lpTitle as *const _ as usize }, + 24usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(lpTitle) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).dwX as *const _ as usize }, + 32usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(dwX) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).dwY as *const _ as usize }, + 36usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(dwY) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).dwXSize as *const _ as usize }, + 40usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(dwXSize) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).dwYSize as *const _ as usize }, + 44usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(dwYSize) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).dwXCountChars as *const _ as usize }, + 48usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(dwXCountChars) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).dwYCountChars as *const _ as usize }, + 52usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(dwYCountChars) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).dwFillAttribute as *const _ as usize }, + 56usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(dwFillAttribute) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).dwFlags as *const _ as usize }, + 60usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(dwFlags) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).wShowWindow as *const _ as usize }, + 64usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(wShowWindow) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).cbReserved2 as *const _ as usize }, + 66usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(cbReserved2) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).lpReserved2 as *const _ as usize }, + 72usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(lpReserved2) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).hStdInput as *const _ as usize }, + 80usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(hStdInput) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).hStdOutput as *const _ as usize }, + 88usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(hStdOutput) + ) + ); + assert_eq!( + unsafe { &(*(::std::ptr::null::<_STARTUPINFOW>())).hStdError as *const _ as usize }, + 96usize, + concat!( + "Offset of field: ", + stringify!(_STARTUPINFOW), + "::", + stringify!(hStdError) + ) + ); +} +pub type LPSTARTUPINFOW = *mut _STARTUPINFOW; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct _DETOUR_TRAMPOLINE { + _unused: [u8; 0], +} +pub type PDETOUR_TRAMPOLINE = *mut _DETOUR_TRAMPOLINE; +#[doc = " Binary Typedefs."] +pub type PF_DETOUR_BINARY_BYWAY_CALLBACK = ::std::option::Option< + unsafe extern "C" fn(pContext: PVOID, pszFile: LPCSTR, ppszOutFile: *mut LPCSTR) -> BOOL, +>; +pub type PF_DETOUR_BINARY_FILE_CALLBACK = ::std::option::Option< + unsafe extern "C" fn( + pContext: PVOID, + pszOrigFile: LPCSTR, + pszFile: LPCSTR, + ppszOutFile: *mut LPCSTR, + ) -> BOOL, +>; +pub type PF_DETOUR_BINARY_SYMBOL_CALLBACK = ::std::option::Option< + unsafe extern "C" fn( + pContext: PVOID, + nOrigOrdinal: ULONG, + nOrdinal: ULONG, + pnOutOrdinal: *mut ULONG, + pszOrigSymbol: LPCSTR, + pszSymbol: LPCSTR, + ppszOutSymbol: *mut LPCSTR, + ) -> BOOL, +>; +pub type PF_DETOUR_BINARY_COMMIT_CALLBACK = + ::std::option::Option BOOL>; +pub type PF_DETOUR_ENUMERATE_EXPORT_CALLBACK = ::std::option::Option< + unsafe extern "C" fn(pContext: PVOID, nOrdinal: ULONG, pszName: LPCSTR, pCode: PVOID) -> BOOL, +>; +pub type PF_DETOUR_IMPORT_FILE_CALLBACK = ::std::option::Option< + unsafe extern "C" fn(pContext: PVOID, hModule: HMODULE, pszFile: LPCSTR) -> BOOL, +>; +pub type PF_DETOUR_IMPORT_FUNC_CALLBACK = ::std::option::Option< + unsafe extern "C" fn(pContext: PVOID, nOrdinal: DWORD, pszFunc: LPCSTR, pvFunc: PVOID) -> BOOL, +>; +pub type PF_DETOUR_IMPORT_FUNC_CALLBACK_EX = ::std::option::Option< + unsafe extern "C" fn( + pContext: PVOID, + nOrdinal: DWORD, + pszFunc: LPCSTR, + ppvFunc: *mut PVOID, + ) -> BOOL, +>; +pub type PDETOUR_BINARY = *mut ::std::os::raw::c_void; +extern "C" { + #[doc = " Transaction APIs."] + pub fn DetourTransactionBegin() -> LONG; +} +extern "C" { + pub fn DetourTransactionAbort() -> LONG; +} +extern "C" { + pub fn DetourTransactionCommit() -> LONG; +} +extern "C" { + pub fn DetourTransactionCommitEx(pppFailedPointer: *mut *mut PVOID) -> LONG; +} +extern "C" { + pub fn DetourUpdateThread(hThread: HANDLE) -> LONG; +} +extern "C" { + pub fn DetourAttach(ppPointer: *mut PVOID, pDetour: PVOID) -> LONG; +} +extern "C" { + pub fn DetourAttachEx( + ppPointer: *mut PVOID, + pDetour: PVOID, + ppRealTrampoline: *mut PDETOUR_TRAMPOLINE, + ppRealTarget: *mut PVOID, + ppRealDetour: *mut PVOID, + ) -> LONG; +} +extern "C" { + pub fn DetourDetach(ppPointer: *mut PVOID, pDetour: PVOID) -> LONG; +} +extern "C" { + pub fn DetourSetIgnoreTooSmall(fIgnore: BOOL) -> BOOL; +} +extern "C" { + pub fn DetourSetRetainRegions(fRetain: BOOL) -> BOOL; +} +extern "C" { + pub fn DetourSetSystemRegionLowerBound(pSystemRegionLowerBound: PVOID) -> PVOID; +} +extern "C" { + pub fn DetourSetSystemRegionUpperBound(pSystemRegionUpperBound: PVOID) -> PVOID; +} +extern "C" { + #[doc = " Code Functions."] + pub fn DetourFindFunction(pszModule: LPCSTR, pszFunction: LPCSTR) -> PVOID; +} +extern "C" { + pub fn DetourCodeFromPointer(pPointer: PVOID, ppGlobals: *mut PVOID) -> PVOID; +} +extern "C" { + pub fn DetourCopyInstruction( + pDst: PVOID, + ppDstPool: *mut PVOID, + pSrc: PVOID, + ppTarget: *mut PVOID, + plExtra: *mut LONG, + ) -> PVOID; +} +extern "C" { + pub fn DetourSetCodeModule(hModule: HMODULE, fLimitReferencesToModule: BOOL) -> BOOL; +} +extern "C" { + pub fn DetourAllocateRegionWithinJumpBounds( + pbTarget: LPCVOID, + pcbAllocatedSize: PDWORD, + ) -> PVOID; +} +extern "C" { + #[doc = " Loaded Binary Functions."] + pub fn DetourGetContainingModule(pvAddr: PVOID) -> HMODULE; +} +extern "C" { + pub fn DetourEnumerateModules(hModuleLast: HMODULE) -> HMODULE; +} +extern "C" { + pub fn DetourGetEntryPoint(hModule: HMODULE) -> PVOID; +} +extern "C" { + pub fn DetourGetModuleSize(hModule: HMODULE) -> ULONG; +} +extern "C" { + pub fn DetourEnumerateExports( + hModule: HMODULE, + pContext: PVOID, + pfExport: PF_DETOUR_ENUMERATE_EXPORT_CALLBACK, + ) -> BOOL; +} +extern "C" { + pub fn DetourEnumerateImports( + hModule: HMODULE, + pContext: PVOID, + pfImportFile: PF_DETOUR_IMPORT_FILE_CALLBACK, + pfImportFunc: PF_DETOUR_IMPORT_FUNC_CALLBACK, + ) -> BOOL; +} +extern "C" { + pub fn DetourEnumerateImportsEx( + hModule: HMODULE, + pContext: PVOID, + pfImportFile: PF_DETOUR_IMPORT_FILE_CALLBACK, + pfImportFuncEx: PF_DETOUR_IMPORT_FUNC_CALLBACK_EX, + ) -> BOOL; +} +extern "C" { + pub fn DetourFindPayload(hModule: HMODULE, rguid: *const GUID, pcbData: *mut DWORD) -> PVOID; +} +extern "C" { + pub fn DetourFindPayloadEx(rguid: *const GUID, pcbData: *mut DWORD) -> PVOID; +} +extern "C" { + pub fn DetourGetSizeOfPayloads(hModule: HMODULE) -> DWORD; +} +extern "C" { + #[doc = " Persistent Binary Functions."] + pub fn DetourBinaryOpen(hFile: HANDLE) -> PDETOUR_BINARY; +} +extern "C" { + pub fn DetourBinaryEnumeratePayloads( + pBinary: PDETOUR_BINARY, + pGuid: *mut GUID, + pcbData: *mut DWORD, + pnIterator: *mut DWORD, + ) -> PVOID; +} +extern "C" { + pub fn DetourBinaryFindPayload( + pBinary: PDETOUR_BINARY, + rguid: *const GUID, + pcbData: *mut DWORD, + ) -> PVOID; +} +extern "C" { + pub fn DetourBinarySetPayload( + pBinary: PDETOUR_BINARY, + rguid: *const GUID, + pData: PVOID, + cbData: DWORD, + ) -> PVOID; +} +extern "C" { + pub fn DetourBinaryDeletePayload(pBinary: PDETOUR_BINARY, rguid: *const GUID) -> BOOL; +} +extern "C" { + pub fn DetourBinaryPurgePayloads(pBinary: PDETOUR_BINARY) -> BOOL; +} +extern "C" { + pub fn DetourBinaryResetImports(pBinary: PDETOUR_BINARY) -> BOOL; +} +extern "C" { + pub fn DetourBinaryEditImports( + pBinary: PDETOUR_BINARY, + pContext: PVOID, + pfByway: PF_DETOUR_BINARY_BYWAY_CALLBACK, + pfFile: PF_DETOUR_BINARY_FILE_CALLBACK, + pfSymbol: PF_DETOUR_BINARY_SYMBOL_CALLBACK, + pfCommit: PF_DETOUR_BINARY_COMMIT_CALLBACK, + ) -> BOOL; +} +extern "C" { + pub fn DetourBinaryWrite(pBinary: PDETOUR_BINARY, hFile: HANDLE) -> BOOL; +} +extern "C" { + pub fn DetourBinaryClose(pBinary: PDETOUR_BINARY) -> BOOL; +} +#[doc = " Create Process & Load Dll."] +pub type PDETOUR_CREATE_PROCESS_ROUTINEA = ::std::option::Option< + unsafe extern "C" fn( + lpApplicationName: LPCSTR, + lpCommandLine: LPSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCSTR, + lpStartupInfo: LPSTARTUPINFOA, + lpProcessInformation: LPPROCESS_INFORMATION, + ) -> BOOL, +>; +pub type PDETOUR_CREATE_PROCESS_ROUTINEW = ::std::option::Option< + unsafe extern "C" fn( + lpApplicationName: LPCWSTR, + lpCommandLine: LPWSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCWSTR, + lpStartupInfo: LPSTARTUPINFOW, + lpProcessInformation: LPPROCESS_INFORMATION, + ) -> BOOL, +>; +extern "C" { + pub fn DetourCreateProcessWithDllA( + lpApplicationName: LPCSTR, + lpCommandLine: LPSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCSTR, + lpStartupInfo: LPSTARTUPINFOA, + lpProcessInformation: LPPROCESS_INFORMATION, + lpDllName: LPCSTR, + pfCreateProcessA: PDETOUR_CREATE_PROCESS_ROUTINEA, + ) -> BOOL; +} +extern "C" { + pub fn DetourCreateProcessWithDllW( + lpApplicationName: LPCWSTR, + lpCommandLine: LPWSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCWSTR, + lpStartupInfo: LPSTARTUPINFOW, + lpProcessInformation: LPPROCESS_INFORMATION, + lpDllName: LPCSTR, + pfCreateProcessW: PDETOUR_CREATE_PROCESS_ROUTINEW, + ) -> BOOL; +} +extern "C" { + pub fn DetourCreateProcessWithDllExA( + lpApplicationName: LPCSTR, + lpCommandLine: LPSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCSTR, + lpStartupInfo: LPSTARTUPINFOA, + lpProcessInformation: LPPROCESS_INFORMATION, + lpDllName: LPCSTR, + pfCreateProcessA: PDETOUR_CREATE_PROCESS_ROUTINEA, + ) -> BOOL; +} +extern "C" { + pub fn DetourCreateProcessWithDllExW( + lpApplicationName: LPCWSTR, + lpCommandLine: LPWSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCWSTR, + lpStartupInfo: LPSTARTUPINFOW, + lpProcessInformation: LPPROCESS_INFORMATION, + lpDllName: LPCSTR, + pfCreateProcessW: PDETOUR_CREATE_PROCESS_ROUTINEW, + ) -> BOOL; +} +extern "C" { + pub fn DetourCreateProcessWithDllsA( + lpApplicationName: LPCSTR, + lpCommandLine: LPSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCSTR, + lpStartupInfo: LPSTARTUPINFOA, + lpProcessInformation: LPPROCESS_INFORMATION, + nDlls: DWORD, + rlpDlls: *mut LPCSTR, + pfCreateProcessA: PDETOUR_CREATE_PROCESS_ROUTINEA, + ) -> BOOL; +} +extern "C" { + pub fn DetourCreateProcessWithDllsW( + lpApplicationName: LPCWSTR, + lpCommandLine: LPWSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCWSTR, + lpStartupInfo: LPSTARTUPINFOW, + lpProcessInformation: LPPROCESS_INFORMATION, + nDlls: DWORD, + rlpDlls: *mut LPCSTR, + pfCreateProcessW: PDETOUR_CREATE_PROCESS_ROUTINEW, + ) -> BOOL; +} +extern "C" { + pub fn DetourProcessViaHelperA( + dwTargetPid: DWORD, + lpDllName: LPCSTR, + pfCreateProcessA: PDETOUR_CREATE_PROCESS_ROUTINEA, + ) -> BOOL; +} +extern "C" { + pub fn DetourProcessViaHelperW( + dwTargetPid: DWORD, + lpDllName: LPCSTR, + pfCreateProcessW: PDETOUR_CREATE_PROCESS_ROUTINEW, + ) -> BOOL; +} +extern "C" { + pub fn DetourProcessViaHelperDllsA( + dwTargetPid: DWORD, + nDlls: DWORD, + rlpDlls: *mut LPCSTR, + pfCreateProcessA: PDETOUR_CREATE_PROCESS_ROUTINEA, + ) -> BOOL; +} +extern "C" { + pub fn DetourProcessViaHelperDllsW( + dwTargetPid: DWORD, + nDlls: DWORD, + rlpDlls: *mut LPCSTR, + pfCreateProcessW: PDETOUR_CREATE_PROCESS_ROUTINEW, + ) -> BOOL; +} +extern "C" { + pub fn DetourUpdateProcessWithDll(hProcess: HANDLE, rlpDlls: *mut LPCSTR, nDlls: DWORD) + -> BOOL; +} +extern "C" { + pub fn DetourUpdateProcessWithDllEx( + hProcess: HANDLE, + hImage: HMODULE, + bIs32Bit: BOOL, + rlpDlls: *mut LPCSTR, + nDlls: DWORD, + ) -> BOOL; +} +extern "C" { + pub fn DetourCopyPayloadToProcess( + hProcess: HANDLE, + rguid: *const GUID, + pvData: PVOID, + cbData: DWORD, + ) -> BOOL; +} +extern "C" { + pub fn DetourRestoreAfterWith() -> BOOL; +} +extern "C" { + pub fn DetourRestoreAfterWithEx(pvData: PVOID, cbData: DWORD) -> BOOL; +} +extern "C" { + pub fn DetourIsHelperProcess() -> BOOL; +} +extern "C" { + pub fn DetourFinishHelperProcess(arg1: HWND, arg2: HINSTANCE, arg3: LPSTR, arg4: INT); +} diff --git a/detours-sys/src/lib.rs b/detours-sys/src/lib.rs new file mode 100644 index 0000000..9f18b97 --- /dev/null +++ b/detours-sys/src/lib.rs @@ -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); + } + } +} diff --git a/zluda_inject/Cargo.toml b/zluda_inject/Cargo.toml index 5dbb14b..8f1cde5 100644 --- a/zluda_inject/Cargo.toml +++ b/zluda_inject/Cargo.toml @@ -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" \ No newline at end of file +winapi = { version = "0.3", features = ["jobapi2", "processthreadsapi", "std", "synchapi"] } +detours-sys = { path = "../detours-sys" } diff --git a/zluda_inject/src/bin.rs b/zluda_inject/src/bin.rs index e021a41..af44d74 100644 --- a/zluda_inject/src/bin.rs +++ b/zluda_inject/src/bin.rs @@ -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> { - 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 "), - ) - .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::::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> { + 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::() }; let mut proc_info = unsafe { mem::zeroed::() }; os_call!( @@ -67,22 +48,19 @@ fn main() -> Result<(), Box> { 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::>(); - 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::()) as u32 + &PAYLOAD_GUID, + zluda_path.as_mut_ptr() as *mut _, + (zluda_path.len() * mem::size_of::()) as u32 ), |x| x != 0 ); @@ -94,13 +72,110 @@ fn main() -> Result<(), Box> { 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) { - for x in from.encode_wide() { - to.push(x); +fn kill_child_on_process_exit(child: HANDLE) -> Result<(), Box> { + let job_handle = os_call!(CreateJobObjectA(ptr::null_mut(), ptr::null()), |x| x + != ptr::null_mut()); + let mut info = unsafe { mem::zeroed::() }; + 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 [ARGS]... +ARGS: + Path to the executable to be injected with ZLUDA + ... Arguments that will be passed to +" + ); +} + +// 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 { + 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 { + 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 { + 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::>(); + result.push(0); + result +} diff --git a/zluda_inject/src/main.rs b/zluda_inject/src/main.rs index 6e292f2..f8c1921 100644 --- a/zluda_inject/src/main.rs +++ b/zluda_inject/src/main.rs @@ -1,5 +1,15 @@ -#[cfg(target_os = "windows")] -mod bin; - -#[cfg(not(target_os = "windows"))] -fn main() {} \ No newline at end of file +#[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> { + bin::main_impl() +} + +#[cfg(not(target_os = "windows"))] +fn main() {} diff --git a/zluda_inject/src/win.rs b/zluda_inject/src/win.rs index ec57ffb..4d7fcdd 100644 --- a/zluda_inject/src/win.rs +++ b/zluda_inject/src/win.rs @@ -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 } }; } diff --git a/zluda_redirect/Cargo.toml b/zluda_redirect/Cargo.toml index 46069bc..1b6b958 100644 --- a/zluda_redirect/Cargo.toml +++ b/zluda_redirect/Cargo.toml @@ -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"] } \ No newline at end of file diff --git a/zluda_redirect/src/lib.rs b/zluda_redirect/src/lib.rs index c6cd4be..d0497a3 100644 --- a/zluda_redirect/src/lib.rs +++ b/zluda_redirect/src/lib.rs @@ -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> = 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 = 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( + 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::())); + 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::(), + )) + }; } } None } - -unsafe fn set_zluda_dll_path(path: *const u16, len: usize) { - let len = len as usize; - let mut result = Vec::::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); -} diff --git a/zluda_redirect/src/payload_guid.rs b/zluda_redirect/src/payload_guid.rs new file mode 100644 index 0000000..eaf021d --- /dev/null +++ b/zluda_redirect/src/payload_guid.rs @@ -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], +}; \ No newline at end of file