forward_dll_mini/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#![doc = r#"# forward-dll-mini

[![Crates.io](https://img.shields.io/crates/v/forward-dll)](https://crates.io/crates/forward-dll)
[![GitHub](https://img.shields.io/badge/Github-forward--dll-blue)](https://github.com/hamflx/forward-dll)

[![Crates.io](https://img.shields.io/crates/v/forward-dll-mini)](https://crates.io/crates/forward-dll-mini)
[![GitHub](https://img.shields.io/badge/Github-forward--dll--mini-blue)](https://github.com/vSylva/forward-dll-mini)

```toml
// Cargo.toml

[lib]
name = "dinput8"
//  name = "d3d11"
//  Not only supports dinput8 and d3d11... test it yourself
crate-type = ["cdylib"]

[build-dependencies]
forward_dll_mini = { git = "https://github.com/vSylva/forward-dll-mini" }
```

```rust
// build.rs

use forward_dll_mini::forward_dll;

fn main() {
    forward_dll("C:\\Windows\\System32\\dinput8.dll").unwrap();
    //  forward_dll("C:\\Windows\\System32\\d3d11.dll").unwrap();
}
```"#]

use std::{collections::HashMap, ffi::NulError, path::PathBuf};

use implib::{def::ModuleDef, Flavor, ImportLibrary, MachineType};
use object::read::pe::{PeFile32, PeFile64};

// #[link(name = "kernel32")]
// extern "system" {

//     pub(crate) fn GetProcAddress(
//         hModule: *mut ::core::ffi::c_void,
//         lpProcName: *const u8,
//     ) -> *mut ::core::ffi::c_void;

//     pub(crate) fn GetModuleHandleExA(
//         dwFlags: ::core::ffi::c_uint,
//         lpModuleName: *const ::core::ffi::c_uchar,
//         phModule: *mut ::core::ffi::c_void,
//     ) -> ::core::ffi::c_long;
//     pub(crate) fn GetLastError() -> ::core::ffi::c_uint;

//     pub(crate) fn LoadLibraryA(
//         lpLibFileName: *const ::core::ffi::c_uchar,
//     ) -> *mut ::core::ffi::c_void;

//     pub(crate) fn FreeLibrary(hLibModule: *mut ::core::ffi::c_void) -> i32;
// }

pub trait ForwardModule {
    fn init(&self) -> ForwardResult<()>;
}

#[derive(Debug)]
pub enum ForwardError {
    Win32Error(&'static str, u32),

    StringError(NulError),

    AlreadyInitialized,
}

impl std::fmt::Display for ForwardError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            ForwardError::Win32Error(func_name, err_code) => {
                write!(f, "Win32Error: {} {}", func_name, err_code)
            }
            ForwardError::StringError(ref err) => write!(f, "StringError: {}", err),
            ForwardError::AlreadyInitialized => write!(f, "AlreadyInitialized"),
        }
    }
}

pub type ForwardResult<T> = std::result::Result<T, ForwardError>;

struct ExportItem {
    ordinal: u32,
    name: Option<String>,
}

pub fn forward_dll(dll_path: &str) -> Result<(), String> {
    forward_dll_with_dev_path(dll_path, dll_path)
}

pub fn forward_dll_with_dev_path(dll_path: &str, dev_dll_path: &str) -> Result<(), String> {
    let exports = get_dll_export_names(dev_dll_path)?;
    forward_dll_impl(dll_path, exports.as_slice())
}

pub fn forward_dll_with_exports(dll_path: &str, exports: &[(u32, &str)]) -> Result<(), String> {
    forward_dll_impl(
        dll_path,
        exports
            .iter()
            .map(|(ord, name)| {
                ExportItem {
                    ordinal: *ord,
                    name: Some(name.to_string()),
                }
            })
            .collect::<Vec<_>>()
            .as_slice(),
    )
}

fn forward_dll_impl(dll_path: &str, exports: &[ExportItem]) -> Result<(), String> {
    const SUFFIX: &str = ".dll";
    let dll_path_without_ext = if dll_path.to_ascii_lowercase().ends_with(SUFFIX) {
        &dll_path[..dll_path.len() - SUFFIX.len()]
    } else {
        dll_path
    };

    let out_dir = get_tmp_dir();

    let mut anonymous_map = HashMap::new();
    let mut anonymous_name_id = 0;

    for ExportItem {
        name,
        ordinal,
    } in exports
    {
        match name {
            Some(name) => {
                println!(
                    "cargo:rustc-link-arg=/EXPORT:{name}={dll_path_without_ext}.{name},@{ordinal}"
                )
            }
            None => {
                anonymous_name_id += 1;
                let fn_name = format!("forward_dll_anonymous_{anonymous_name_id}");
                println!(
                    "cargo:rustc-link-arg=/EXPORT:{fn_name}={dll_path_without_ext}.#{ordinal},@{ordinal},NONAME"
                );
                anonymous_map.insert(ordinal, fn_name);
            }
        };
    }

    let exports_def = String::from("LIBRARY version\nEXPORTS\n")
        + exports
            .iter()
            .map(
                |ExportItem {
                     name,
                     ordinal,
                 }| {
                    match name {
                        Some(name) => format!("  {name} @{ordinal}\n"),
                        None => {
                            let fn_name = anonymous_map.get(ordinal).unwrap();
                            format!("  {fn_name} @{ordinal} NONAME\n")
                        }
                    }
                },
            )
            .collect::<String>()
            .as_str();
    #[cfg(target_arch = "x86_64")]
    let machine = MachineType::AMD64;
    #[cfg(target_arch = "x86")]
    let machine = MachineType::I386;
    let mut def = ModuleDef::parse(&exports_def, machine)
        .map_err(|err| format!("ImportLibrary::new error: {err}"))?;
    for item in def.exports.iter_mut() {
        item.symbol_name = item.name.trim_start_matches('_').to_string();
    }
    let lib = ImportLibrary::from_def(def, machine, Flavor::Msvc);
    let version_lib_path = out_dir.join("version_proxy.lib");
    let mut lib_file = std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(version_lib_path)
        .map_err(|err| format!("OpenOptions::open error: {err}"))?;
    lib.write_to(&mut lib_file)
        .map_err(|err| format!("ImportLibrary::write_to error: {err}"))?;

    println!("cargo:rustc-link-search={}", out_dir.display());
    println!("cargo:rustc-link-lib=version_proxy");

    Ok(())
}

fn get_tmp_dir() -> PathBuf {
    std::env::var("OUT_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            let dir = std::env::temp_dir().join("forward-dll-libs");
            if !dir.exists() {
                std::fs::create_dir_all(&dir).expect("Failed to create temp dir");
            }
            dir
        })
}

fn get_dll_export_names(dll_path: &str) -> Result<Vec<ExportItem>, String> {
    let dll_file = std::fs::read(dll_path).map_err(|err| format!("Failed to read file: {err}"))?;
    let in_data = dll_file.as_slice();

    let kind = object::FileKind::parse(in_data).map_err(|err| format!("Invalid file: {err}"))?;
    let exports = match kind {
        object::FileKind::Pe32 => {
            PeFile32::parse(in_data)
                .map_err(|err| format!("Invalid pe file: {err}"))?
                .export_table()
                .map_err(|err| format!("Invalid pe file: {err}"))?
                .ok_or_else(|| "No export table".to_string())?
                .exports()
        }
        object::FileKind::Pe64 => {
            PeFile64::parse(in_data)
                .map_err(|err| format!("Invalid pe file: {err}"))?
                .export_table()
                .map_err(|err| format!("Invalid pe file: {err}"))?
                .ok_or_else(|| "No export table".to_string())?
                .exports()
        }
        _ => return Err("Invalid file".to_string()),
    }
    .map_err(|err| format!("Invalid file: {err}"))?;

    let mut export_list = Vec::new();
    for export_item in exports {
        let ordinal = export_item.ordinal;
        let name = export_item
            .name
            .map(String::from_utf8_lossy)
            .map(String::from);
        let item = ExportItem {
            name,
            ordinal,
        };
        export_list.push(item);
    }
    Ok(export_list)
}

// pub fn load_library_by_handle(
//     inst: *mut ::core::ffi::c_void,
// ) -> ForwardResult<*mut ::core::ffi::c_void> {
//     let module_handle: *mut ::core::ffi::c_void = ::core::ptr::null_mut();
//     let pin_success =
//         unsafe { crate::GetModuleHandleExA(0x00000004, inst as *const u8, module_handle) } != 0;
//     if !pin_success {
//         return Err(ForwardError::Win32Error("GetModuleHandleExA", unsafe {
//             crate::GetLastError()
//         }));
//     }
//     Ok(module_handle)
// }

// pub fn load_library(lib_filename: &str) -> ForwardResult<*mut ::core::ffi::c_void> {
//     let module_name = std::ffi::CString::new(lib_filename).map_err(ForwardError::StringError)?;
//     let module_handle = unsafe { crate::LoadLibraryA(module_name.as_ptr() as *const u8) };
//     if module_handle.is_null() {
//         return Err(ForwardError::Win32Error("LoadLibraryA", unsafe {
//             crate::GetLastError()
//         }));
//     }
//     Ok(module_handle)
// }

// pub fn free_library(inst: *mut ::core::ffi::c_void) {
//     unsafe { crate::FreeLibrary(inst) };
// }

// pub fn get_proc_address_by_module(
//     inst: *mut ::core::ffi::c_void,
//     proc_name: &str,
// ) -> ForwardResult<unsafe extern "system" fn() -> isize> {
//     let proc_name = std::ffi::CString::new(proc_name).map_err(ForwardError::StringError)?;
//     unsafe {
//         let result = crate::GetProcAddress(inst, proc_name.as_ptr() as *const u8);

//         if result.is_null() {
//             return Err(ForwardError::Win32Error(
//                 "GetProcAddress",
//                 crate::GetLastError(),
//             ));
//         }
//         Ok(::core::mem::transmute(result))
//     }
// }