Refactor winapi calls to surface errors

This commit is contained in:
Andrzej Janik 2020-01-06 23:15:00 +01:00
commit 6bd033c369
2 changed files with 238 additions and 179 deletions

View file

@ -9,7 +9,8 @@ use std::ptr;
use clap::{App, AppSettings, Arg};
mod win_err;
#[macro_use]
mod win;
fn main() -> Result<(), Box<dyn Error>> {
let matches = App::new("notCUDA injector")
@ -47,7 +48,7 @@ fn main() -> Result<(), Box<dyn Error>> {
cmd_line.push(0);
let mut startup_info = unsafe { mem::zeroed::<detours_sys::_STARTUPINFOW>() };
let mut proc_info = unsafe { mem::zeroed::<detours_sys::_PROCESS_INFORMATION>() };
let process_success = unsafe {
os_call!(
detours_sys::DetourCreateProcessWithDllExW(
ptr::null(),
cmd_line.as_mut_ptr(),
@ -60,13 +61,25 @@ fn main() -> Result<(), Box<dyn Error>> {
&mut startup_info as *mut _,
&mut proc_info as *mut _,
"nvcuda_redirect.dll".as_ptr() as *const i8,
Option::None,
)
};
if process_success == 0 {
return Err(win_err::error_string(win_err::errno()))?;
}
Option::None
),
0
);
Ok(())
/*
cmd_line.as_mut_ptr(),
ptr::null_mut(),
ptr::null_mut(),
0,
0x10,
ptr::null_mut(),
ptr::null(),
&mut startup_info as *mut _,
&mut proc_info as *mut _,
"nvcuda_redirect.dll".as_ptr() as *const i8,
Option::None,
*/
}
fn copy_to(from: &OsStr, to: &mut Vec<u16>) {

View file

@ -1,10 +1,13 @@
#![allow(non_snake_case)]
use std::error;
use std::error::Error;
use std::fmt;
use std::ptr;
mod c {
use std::ffi::c_void;
use std::os::raw::{c_ulong};
use std::os::raw::c_ulong;
pub type DWORD = c_ulong;
pub type HANDLE = LPVOID;
@ -35,6 +38,49 @@ mod c {
}
}
macro_rules! last_ident {
($i:ident) => {
stringify!($i)
};
($start:ident, $($cont:ident),+) => {
last_ident!($($cont),+)
};
}
macro_rules! os_call {
($($path:ident)::+ ($($args:expr),*), $success:expr) => {
let result = unsafe{ $($path)::+ ($($args),+) };
if result != $success {
let name = last_ident!($($path),+);
let err_code = $crate::win::errno();
Err($crate::win::OsError{
function: name,
error_code: err_code as u32,
message: $crate::win::error_string(err_code)
})?;
}
};
}
#[derive(Debug)]
pub struct OsError {
pub function: &'static str,
pub error_code: u32,
pub message: String,
}
impl fmt::Display for OsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl error::Error for OsError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
None
}
}
pub fn errno() -> i32 {
unsafe { c::GetLastError() as i32 }
}