Debian Codegraph @

src/platform/windows_safe.rs

raw symbols SCIP
1 // spell-checker:ignore (abbrev) MSVC
2 // spell-checker:ignore (API) sysname osname nodename
3 // spell-checker:ignore (jargon) armv aarch
4 // spell-checker:ignore (rust) nonminimal repr stdcall uninit
5 // spell-checker:ignore (uutils) coreutils uutils
6 // spell-checker:ignore (vars) mmbr mmrb
7 // spell-checker:ignore (VSCode) endregion
8 // spell-checker:ignore (WinAPI) ctypes CWSTR DWORDLONG dwStrucVersion FARPROC FIXEDFILEINFO HIWORD HMODULE libloaderapi LOWORD LPCSTR LPCVOID LPCWSTR lpdw LPDWORD lplp LPOSVERSIONINFOEXW LPSYSTEM lptstr LPVOID LPWSTR minwindef ntdef ntstatus OSVERSIONINFOEXW processthreadsapi PUINT SMALLBUSINESS SUITENAME sysinfo sysinfoapi sysinfoapi TCHAR TCHARs ULONGLONG WCHAR WCHARs winapi winbase winver WSTR wstring
9 // spell-checker:ignore (WinOS) ntdll
10
11 #![warn(unused_results)] // enable warnings for unused results
12
13 use std::convert::TryFrom;
14 use std::io;
15 use std::mem::{self, MaybeUninit};
16 use std::ptr;
17
18 use winapi::shared::minwindef::*;
19 use winapi::shared::ntdef::NTSTATUS;
20 use winapi::shared::ntstatus::*;
21 use winapi::um::libloaderapi::*;
22 use winapi::um::processthreadsapi::GetCurrentProcess;
23 use winapi::um::sysinfoapi;
24 use winapi::um::sysinfoapi::*;
25 use winapi::um::winbase::*;
26 use winapi::um::winnt::*;
27 use winapi::um::winver::*;
28
29 use super::util::{to_c_string, to_c_wstring, CWSTR};
30 use super::{WinApiFileVersionInfo, WinApiSystemInfo};
31
32 use super::PathStr;
33 use super::WinOSError;
34
35 //===
36
37 // VS_FIXEDFILEINFO
38 /// WinAPI structure which contains version information for a file.
39 ///
40 /// Implements [`VS_FIXEDFILEINFO`].
41 // ref: [`VS_FIXEDFILEINFO`](https://learn.microsoft.com/en-us/windows/win32/api/verrsrc/ns-verrsrc-vs_fixedfileinfo) @@ <https://archive.is/1sJgX>
42 #[allow(non_snake_case)]
43 #[allow(unused_variables)]
44 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
45 #[repr(C)]
46 pub struct VS_FIXEDFILEINFO {
47 pub dwSignature: DWORD,
48 pub dwStrucVersion: DWORD,
49 pub dwFileVersionMS: DWORD,
50 pub dwFileVersionLS: DWORD,
51 pub dwProductVersionMS: DWORD,
52 pub dwProductVersionLS: DWORD,
53 pub dwFileFlagsMask: DWORD,
54 pub dwFileFlags: DWORD,
55 pub dwFileOS: DWORD,
56 pub dwFileType: DWORD,
57 pub dwFileSubtype: DWORD,
58 pub dwFileDateMS: DWORD,
59 pub dwFileDateLS: DWORD,
60 }
61
62 //===
63
64 //#region unsafe code
65
66 impl WinApiSystemInfo {
67 #[allow(non_snake_case)]
68 /// Returns `wProcessorArchitecture` extracted from the [`SYSTEM_INFO`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info) structure.
69 /// <br> Refer to [`SYSTEM_INFO`](https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info) for more information.
70 pub fn wProcessorArchitecture(&self) -> WORD {
71 unsafe { self.0.u.s().wProcessorArchitecture }
72 }
73 }
74
75 // create_OSVERSIONINFOEXW
76 /// *Returns* an owned, mutable [`OSVERSIONINFOEXW`] structure (fully initialized).
77 // ref: [`OSVERSIONINFOEXW`](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-osversioninfoexw) @@ <https://archive.is/n4hBb>
78 #[allow(non_snake_case)]
79 pub fn create_OSVERSIONINFOEXW(
80 ) -> Result<OSVERSIONINFOEXW, crate::lib_impl::BoxedThreadSafeStdError> {
81 let os_info_size = DWORD::try_from(mem::size_of::<OSVERSIONINFOEXW>())?;
82 let mut os_info: OSVERSIONINFOEXW = unsafe { mem::zeroed() };
83 os_info.dwOSVersionInfoSize = os_info_size;
84 Ok(os_info)
85 }
86
87 // NOTE: WinAPI_... functions are thin-wrapper translations of the underlying WinOS API functions into safe functions
88
89 // WinAPI_FreeLibrary
90 /// Frees the loaded dynamic-link library (DLL) module, decrementing its reference count.
91 /// When the reference count reaches zero, the module is unloaded from the address space of the calling process and the
92 /// handle is no longer valid.
93 ///
94 /// *Returns* BOOL ~ `FALSE` (aka zero) for fn *failure*; o/w non-`FALSE` (aka non-zero) for fn *success*.
95 ///
96 /// Wraps WinOS [`Kernel32/FreeLibrary(...)`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary).
97 #[allow(non_snake_case)]
98 pub fn WinAPI_FreeLibrary(module: HMODULE /* from `hModule: HMODULE` */) -> BOOL {
99 // FreeLibrary
100 // pub unsafe fn FreeLibrary(hLibModule: HMODULE) -> BOOL
101 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary> @@ <https://archive.is/jWCsU>
102 // * *returns* BOOL ~ `FALSE` (aka zero) for fn *failure*; o/w non-`FALSE` (aka non-zero) for fn *success*
103 unsafe { FreeLibrary(module) }
104 }
105
106 // WinAPI_GetComputerNameExW
107 /// Retrieves a NetBIOS or DNS name associated with the local computer; stored into WCHAR vector (`buffer`).
108 ///
109 /// * `name_type` ~ (in) specify requested type of computer name (as [COMPUTER_NAME_FORMAT](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ne-sysinfoapi-computer_name_format))
110 /// * `buffer` ~ (out)
111 /// - for non-`FALSE` return, contains the requested computer name as WSTR (of length `size`)
112 /// - for `FALSE` return, unchanged
113 /// * `size` ~ (out)
114 /// - for non-`FALSE` return, contains the number of TCHARs (aka WCHARs) copied to the destination buffer, *not including* the terminating null character
115 /// - for `FALSE` return, contains the buffer size required for the result, *including* the terminating null character
116 ///
117 /// *Returns* BOOL ~ `FALSE` (aka zero) for fn *failure*; o/w non-`FALSE` (aka non-zero) for fn *success*.
118 ///
119 ///### Notes
120 ///
121 /// Vector capacity cannot be rigorously set because capacity is set as a minimum and may be "rounded up" by the
122 /// implementation. So, for the supplied `buffer`, `buffer.len()`, *not* `buffer.capacity()`, is used as the measure of
123 /// usable buffer size.
124 ///
125 /// Supplying a zero-length `buffer` (or alternatively, `None`) as input will return a value specifying the actual
126 /// required buffer size for the system path.
127 ///
128 /// Wraps WinOS [`Kernel32/GetComputerNameExW(...)`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getcomputernameexw).
129 #[allow(non_snake_case)]
130 pub fn WinAPI_GetComputerNameExW<'a, T>(
131 name_type: COMPUTER_NAME_FORMAT,
132 buffer: T, /* from `lpBuffer: LPWSTR` */
133 size: &mut DWORD, /* from `nSize: LPDWORD` */
134 ) -> BOOL
135 where
136 T: Into<Option<&'a mut Vec<WCHAR>>>,
137 {
138 // pub unsafe fn GetComputerNameExW(NameType: COMPUTER_NAME_FORMAT, lpBuffer: LPWSTR, nSize: LPDWORD) -> BOOL
139 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getcomputernameexw> @@ <https://archive.is/Lgb7p>
140 // * `name_type` ~ (in) [COMPUTER_NAME_FORMAT](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ne-sysinfoapi-computer_name_format) @@ <https://archive.is/s18y0>
141 // * `nSize` ~ (in) specifies the size of the destination buffer (*lpBuffer) in TCHARs (aka WCHARs)
142 // * `nSize` ~ (out) on *fn failure* (aka `FALSE` return), receives the buffer size required for the result, *including* the terminating null character
143 // * `nSize` ~ (out) on *fn success*, receives the number of TCHARs (aka WCHARs) copied to the destination buffer, *not including* the terminating null character
144 // * *returns* BOOL ~ `FALSE` (aka zero) for fn *failure*; o/w non-`FALSE` (aka non-zero) for fn *success*
145 let maybe_buffer = buffer.into();
146 let (buffer_ptr, length) = match maybe_buffer {
147 Some(buf) => (buf.as_mut_ptr(), DWORD::try_from(buf.len()).unwrap_or(0)),
148 None => (ptr::null_mut(), 0),
149 };
150 *size = length;
151 let result = unsafe { GetComputerNameExW(name_type, buffer_ptr, size) };
152 assert!((result == FALSE) || (*size <= length)); // safety sanity check; panics on out-of-bounds memory writes (buffer overrun)
153 result
154 }
155
156 // WinAPI_GetCurrentProcess
157 /// *Returns* a pseudo handle for the current process.
158 ///
159 /// Wraps WinOS [`Kernel32/GetCurrentProcess()`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocess).
160 #[allow(dead_code)] // * fn is used by test(s)
161 #[allow(non_snake_case)]
162 pub fn WinAPI_GetCurrentProcess() -> HANDLE {
163 // GetCurrentProcess
164 // pub unsafe fn GetCurrentProcess() -> HANDLE
165 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocess> @@ <https://archive.is/AmB3f>
166 unsafe { GetCurrentProcess() }
167 }
168
169 // WinAPI_GetFileVersionInfoSizeW
170 /// Determines whether the operating system can retrieve version information for a specified file (`file_path`).
171 /// If version information is available, GetFileVersionInfoSize returns the size, in bytes, of that information.
172 ///
173 /// *Returns* DWORD ~ zero for fn *failure*; o/w size of the file version information, in *bytes*, for fn *success*.
174 ///
175 /// Wraps WinOS [`Version/GetFileVersionInfoSizeW(...)`](https://learn.microsoft.com/en-us/windows/win32/api/winver/nf-winver-getfileversioninfosizew).
176 #[allow(non_snake_case)]
177 pub fn WinAPI_GetFileVersionInfoSizeW<P: AsRef<PathStr>>(
178 file_path: P, /* used to generate `lptstrFilename: LPCWSTR` */ // lpdwHandle: *mut DWORD, /* ignored/not-needed */
179 ) -> DWORD {
180 // GetFileVersionInfoSizeW
181 // pub unsafe fn GetFileVersionInfoSizeW(lptstrFilename: LPCWSTR, lpdwHandle: *mut DWORD) -> DWORD
182 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/winver/nf-winver-getfileversioninfosizew> @@ <https://archive.is/AdMHL>
183 // * returns DWORD ~ on *failure*, 0
184 // * returns DWORD ~ on *success*, size of the file version information, in *bytes*
185 let file_path_cws: CWSTR = to_c_wstring(file_path.as_ref());
186 unsafe {
187 GetFileVersionInfoSizeW(file_path_cws.as_ptr(), ptr::null_mut() /* ignored */)
188 }
189 }
190
191 // WinAPI_GetFileVersionInfoW
192 /// Retrieves version information for the specified file (`file_path`); stored into BYTE vector (`data`).
193 ///
194 /// *Returns* BOOL ~ `FALSE` (aka zero) for fn *failure*; o/w non-`FALSE` (aka non-zero) for fn *success*.
195 ///
196 /// Wraps WinOS [`Version/GetFileVersionInfoW(...)`](https://learn.microsoft.com/en-us/windows/win32/api/winver/nf-winver-getfileversioninfow).
197 #[allow(non_snake_case)]
198 pub fn WinAPI_GetFileVersionInfoW<P: AsRef<PathStr>>(
199 file_path: P, /* used to generate `lptstrFilename: LPCWSTR` */
200 // dwHandle: DWORD, /* ignored/not-needed */
201 // dwLen: DWORD, /* not-needed */
202 data: &mut Vec<BYTE>, /* from `lpData: *mut winapi::ctypes::c_void` */
203 ) -> BOOL {
204 // GetFileVersionInfoW
205 // pub unsafe fn GetFileVersionInfoW(lptstrFilename: LPCWSTR, dwHandle: DWORD, dwLen: DWORD, lpData: *mut c_void) -> BOOL
206 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/winver/nf-winver-getfileversioninfow> @@ <https://archive.is/4rx6D>
207 // * handle/dwHandle == *ignored*
208 // * length/dwLen == maximum size (in bytes) of buffer at data_ptr/lpData
209 // * *returns* BOOL ~ `FALSE` (aka zero) for fn *failure*, o/w non-`FALSE` (aka non-zero) for fn *success*
210 let file_path_cws: CWSTR = to_c_wstring(file_path.as_ref());
211 unsafe {
212 GetFileVersionInfoW(
213 file_path_cws.as_ptr(),
214 0, /* ignored */
215 DWORD::try_from(data.capacity()).unwrap(),
216 data.as_mut_ptr() as *mut _,
217 )
218 }
219 }
220
221 // WinAPI_GetNativeSystemInfo
222 /// *Returns* information (as `SYSTEM_INFO`) about the current system to an application running under WOW64.
223 ///
224 /// If the function is called from a 64-bit application, it is equivalent to the GetSystemInfo function.
225 /// If the function is called from an x86 or x64 application running on a 64-bit system that does not have an Intel64 or
226 // x64 processor (such as ARM64), it will return information as if the system is x86 only if x86 emulation is supported
227 /// (or x64 if x64 emulation is also supported).
228 ///
229 /// Wraps WinOS [`Kernel32/GetNativeSystemInfo(...)`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getnativesysteminfo).
230 #[allow(non_snake_case)]
231 pub fn WinAPI_GetNativeSystemInfo() -> SYSTEM_INFO {
232 // GetNativeSystemInfo
233 // pub unsafe fn GetNativeSystemInfo(lpSystemInfo: LPSYSTEM_INFO)
234 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getnativesysteminfo> @@ <https://archive.is/UV2S2>
235 let mut sysinfo = MaybeUninit::<SYSTEM_INFO>::uninit();
236 unsafe {
237 GetNativeSystemInfo(sysinfo.as_mut_ptr());
238 // SAFETY: `GetNativeSystemInfo()` always succeeds => `sysinfo` was initialized
239 sysinfo.assume_init()
240 }
241 }
242
243 // WinAPI_GetProcAddress
244 /// *Returns* the address of an exported function/procedure or variable (`symbol_name`) from the specified library (`module`).
245 ///
246 /// Wraps WinOS [`Kernel32/GetProcAddress(...)`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress).
247 #[allow(non_snake_case)]
248 pub fn WinAPI_GetProcAddress<P: AsRef<PathStr>>(
249 module: HMODULE, /* from `hModule: HMODULE` */
250 symbol_name: P, /* used to generate `lpProcName: LPCSTR` */
251 ) -> FARPROC {
252 // GetProcAddress
253 // pub unsafe fn GetProcAddress(hModule: HMODULE, lpProcName: LPCSTR) -> FARPROC
254 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress> @@ <https://archive.is/ZPVMr>
255 let symbol_name_cs = to_c_string(symbol_name.as_ref());
256 unsafe { GetProcAddress(module, symbol_name_cs.as_ptr()) }
257 }
258
259 // WinAPI_GetSystemDirectoryW
260 /// Retrieves the path of the system directory; stored into a WCHAR vector (`buffer`).
261 ///
262 /// * `buffer`
263 /// - for non-zero return (*success*) with adequate buffer size, `buffer` will contain the requested WinOS System Directory path as a WSTR
264 /// - for zero (*failure*) or non-zero (*success*) return with inadequate buffer size, `buffer` will be unchanged
265 ///
266 /// *Returns* UINT
267 /// - zero for fn *failure*
268 /// - fn *success* with adequate buffer size, contains the number of WCHARs (aka TCHARs) copied to the destination buffer, *not including* the terminating null character
269 /// - fn *success* with inadequate buffer size, contains the buffer size required for the requested path, *including* the terminating null character
270 ///
271 ///### Notes
272 ///
273 /// Vector capacity cannot be rigorously set because capacity is set as a minimum and may be "rounded up" by the
274 /// implementation. So, for the supplied `buffer`, `buffer.len()`, *not* `buffer.capacity()`, is used as the measure of
275 /// usable buffer size.
276 ///
277 /// Supplying a zero-length `buffer` (or alternatively, `None`) as input will return a value specifying the actual
278 /// required buffer size for the system path.
279 ///
280 /// Wraps WinOS [`Kernel32/GetSystemDirectoryW(...)`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemdirectoryw).
281 #[allow(non_snake_case)]
282 pub fn WinAPI_GetSystemDirectoryW<'a, T>(
283 buffer: T, /* from `lpBuffer: LPWSTR` */ // uSize: UINT, /* not needed */
284 ) -> UINT
285 where
286 T: Into<Option<&'a mut Vec<WCHAR>>>,
287 {
288 // GetSystemDirectoryW
289 // pub unsafe fn GetSystemDirectoryW(lpBuffer: LPWSTR, uSize: UINT) -> UINT
290 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemdirectoryw> @@ <https://archive.is/OTVW8>
291 // * `uSize` ~ (in) specifies the maximum size of the destination buffer (*lpBuffer) in TCHARs (aka WCHARs)
292 // * returns UINT ~ on fn *failure*, 0
293 // * returns UINT ~ on fn *success* and uSize <= length(System Directory string), size of required destination buffer (in TCHARs [aka WCHARs]), *including* the terminating null character
294 // * returns UINT ~ on fn *success* and uSize > length(System Directory string), the number of TCHARs (aka WCHARs) copied to the destination buffer, *not including* the terminating null character
295 let (buffer_ptr, length) = match buffer.into() {
296 Some(buf) => (buf.as_mut_ptr(), UINT::try_from(buf.len()).unwrap_or(0)),
297 None => (ptr::null_mut(), 0),
298 };
299 unsafe { GetSystemDirectoryW(buffer_ptr, length) }
300 }
301
302 // WinAPI_LoadLibrary
303 /// *Returns* a module handle for the specified module (`module_name`), loading the library, if needed, and increasing
304 /// the per-process reference count.
305 ///
306 /// * `module_name` ~ requested library/module <br>
307 /// Note: full path specification of `module_name` has increased safety. If only base name and extension is specified,
308 /// modules with colliding names may cause the return of a random module handle.
309 ///
310 /// This function is multithread-safe.
311 /// But this function cannot be called in certain contexts, such as recursively, by any code path called by a `DllMain`
312 /// function, or within a "module initializer" (such as a C++ constructor for a global variable).
313 ///
314 /// Wraps WinOS [`Kernel32/LoadLibraryW(...)`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlew).
315 // ref: <https://github.com/rust-lang/rust/issues/78444>
316 // ref: <https://stackoverflow.com/questions/7364846/loading-dll-via-getmodulehandle-loadlibrary-and-using-freelibrary>
317 #[allow(non_snake_case)]
318 pub fn WinAPI_LoadLibrary<P: AsRef<PathStr>>(
319 module_name: P, /* used to generate `lpFileName: LPCWSTR` */
320 ) -> HMODULE {
321 // LoadLibraryW
322 // pub unsafe fn LoadLibraryW(lpFileName: LPCWSTR) -> HMODULE
323 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryw> @@ <https://archive.is/N3Fxf>
324 let module_name_cws: CWSTR = to_c_wstring(module_name.as_ref());
325 unsafe { LoadLibraryW(module_name_cws.as_ptr()) }
326 }
327
328 // WinAPI_VerifyVersionInfoW
329 /// Compares a set of operating system version requirements (`version_info`, `type_mask`, and `condition_mask`) to the
330 /// corresponding values for the currently running version of the system.
331 ///
332 /// *Returns* BOOL ~ `FALSE` (aka zero) if resource is non-existent or requirements are not met; o/w non-`FALSE` (aka non-zero)
333 ///
334 /// Wraps WinOS [`Kernel32/VerifyVersionInfoW(...)`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-verifyversioninfow).
335 #[allow(non_snake_case)]
336 pub fn WinAPI_VerifyVersionInfoW(
337 version_info: &OSVERSIONINFOEXW, /* from `lpVersionInformation: LPOSVERSIONINFOEXW` */
338 type_mask: DWORD, /* from `dwTypeMask: DWORD` */
339 condition_mask: DWORDLONG, /* from `dwlConditionMask: DWORDLONG` */
340 ) -> BOOL {
341 // VerifyVersionInfoW
342 // pub unsafe fn VerifyVersionInfoW(lpVersionInformation: LPOSVERSIONINFOEXW, dwTypeMask: DWORD, dwlConditionMask: DWORDLONG) -> BOOL
343 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-verifyversioninfow> @@ <https://archive.is/1h5FF>
344 // version_info/lpVersionInformation ~ pointer to (const) version info requirements for comparison
345 // type_mask ~ mask indicating members of version_info to be tested
346 // condition_mask ~ type of comparison for each version_info member to be compared
347 // * returns BOOL ~ `FALSE` (aka zero) for non-existent resource or invalid requirements; o/w non-`FALSE` (aka non-zero)
348 let version_info_ptr: *const OSVERSIONINFOEXW = version_info;
349 unsafe {
350 VerifyVersionInfoW(
351 version_info_ptr as *mut OSVERSIONINFOEXW, // version_info_ptr *is* `*const OSVERSIONINFOEXW` but misdefined by function declaration
352 type_mask,
353 condition_mask,
354 )
355 }
356 }
357
358 // WinAPI_VerQueryValueW
359 /// Retrieves specified version information (`query`) as a view (`info_view`) into the specified version-information
360 /// resource (`version_info`).
361 ///
362 /// *Returns* BOOL ~ `FALSE` (aka zero) for fn *failure*; o/w non-zero for fn *success*.
363 ///
364 /// Wraps WinOS [`Version/VerQueryValueW(...)`](https://learn.microsoft.com/en-us/windows/win32/api/winver/nf-winver-verqueryvaluew).
365 #[allow(non_snake_case)]
366 pub fn WinAPI_VerQueryValueW<'a, S: AsRef<str>>(
367 version_info: &'a [BYTE], /* from `pBlock: LPCVOID` */
368 query: S, /* from `lpSubBlock: LPCWSTR` */
369 info_view: &'a mut LPVOID, /* from `lplpBuffer: &mut LPVOID` */
370 info_view_length: &'a mut UINT, /* from `puLen: PUINT` */
371 ) -> BOOL {
372 // VerQueryValueW
373 // pub unsafe fn VerQueryValueW(pBlock: LPCVOID, lpSubBlock: LPCWSTR, lplpBuffer: &mut LPVOID, puLen: PUINT) -> BOOL
374 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/winver/nf-winver-verqueryvaluew> @@ <https://archive.is/VqvGQ>
375 // version_info_ptr/pBlock ~ pointer to (const) version info
376 // info_view/lplpBuffer ~ pointer into version info supplied by version_info_ptr (no new allocations)
377 // info_view_length/puLen ~ pointer to size (in characters [TCHARs/WCHARs] for "version info values", in bytes for translation array or root block)
378 // * returns BOOL ~ `FALSE` (aka zero) for invalid/non-existent resource; o/w non-`FALSE` (aka non-zero)
379 let version_info_ptr = version_info.as_ptr() as LPCVOID;
380 unsafe {
381 VerQueryValueW(
382 version_info_ptr,
383 to_c_wstring(query.as_ref()).as_ptr(),
384 info_view,
385 info_view_length,
386 )
387 }
388 }
389
390 // WinAPI_VerSetConditionMask
391 /// Sets the bits of a 64-bit value to indicate the comparison operator to use for a specified operating system version
392 /// attribute (ie, specific member of version_info [[`OSVERSIONINFOEXW`]]). This function is used, possibly repeatedly, to build the
393 /// `condition_mask` parameter of the [WinAPI_VerifyVersionInfoW] function.
394 ///
395 /// * condition_mask ~ baseline value for type of comparisons for each member of version info
396 /// * type_mask ~ mask indicating the member of version info whose comparison operator is being set
397 /// * condition ~ comparison type
398 ///
399 /// *Returns* ULONGLONG ~ updated condition_mask
400 ///
401 /// Wraps WinOS [`Kernel32/VerSetConditionMask(...)`](https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-versetconditionmask).
402 #[allow(non_snake_case)]
403 pub fn WinAPI_VerSetConditionMask(
404 condition_mask: ULONGLONG,
405 type_mask: DWORD,
406 condition: BYTE,
407 ) -> ULONGLONG {
408 // VerSetConditionMask
409 // pub unsafe fn VerSetConditionMask(ConditionMask: ULONGLONG, TypeMask: DWORD, Condition: BYTE) -> ULONGLONG
410 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-versetconditionmask> @@ <https://archive.is/hJtIB>
411 // condition_mask ~ baseline value for type of comparisons for each member of version info (ie, `OSVERSIONINFOEXW`)
412 // type_mask ~ mask indicating the member of version info whose comparison operator is being set
413 // condition ~ comparison type
414 // * returns ULONGLONG ~ updated condition_mask
415 unsafe { sysinfoapi::VerSetConditionMask(condition_mask, type_mask, condition) }
416 }
417
418 // WinOsFileVersionInfoQuery_root
419 /// *Returns* the "root" version information *as view of the internal [`VS_FIXEDFILEINFO`] structure* within the
420 /// specified version-information resource (`version_info`).
421 ///
422 /// Uses WinOS [`Version/WinAPI_VerQueryValueW(...)`](https://learn.microsoft.com/en-us/windows/win32/api/winver/nf-winver-verqueryvaluew).
423 #[allow(non_snake_case)]
424 pub fn WinOsFileVersionInfoQuery_root(
425 version_info: &WinApiFileVersionInfo,
426 ) -> Result<&VS_FIXEDFILEINFO, WinOSError> {
427 // NOTE: this function could be expanded to cover root, translation, and information queries by using an enum for a return value
428
429 // VerQueryValueW
430 // pub unsafe fn VerQueryValueW(pBlock: LPCVOID, lpSubBlock: LPCWSTR, lplpBuffer: &mut LPVOID, puLen: PUINT) -> BOOL
431 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/winver/nf-winver-verqueryvaluew> @@ <https://archive.is/VqvGQ>
432 // version_info_ptr/pBlock ~ pointer to (const) version info
433 // info_view/lplpBuffer ~ pointer into version info supplied by version_info_ptr (no new allocations)
434 // info_view_length/puLen ~ pointer to size (in characters [TCHARs/WCHARs] for "version info values", in bytes for translation array or root block)
435 // * returns BOOL ~ `FALSE` (aka zero) for invalid/non-existent resource; o/w non-`FALSE` (aka non-zero) for *fn success*
436
437 let version_info_data = &version_info.data;
438
439 let mut data_view = ptr::null_mut(); // view into the `version_info_data` block
440 let mut data_view_size = 0;
441
442 let query = "\\"; // "root" query ~ requests the VS_FIXEDFILEINFO structure from within the supplied `version_info`
443 let fixed_file_info_size = UINT::try_from(mem::size_of::<VS_FIXEDFILEINFO>())?; // expected returned data_view_size
444 if WinAPI_VerQueryValueW(
445 version_info_data,
446 query,
447 &mut data_view,
448 &mut data_view_size,
449 ) == 0
450 || (data_view_size != fixed_file_info_size)
451 {
452 return Err(Box::new(io::Error::last_os_error()));
453 }
454
455 assert!(version_info_data.len() >= usize::try_from(data_view_size)?);
456 assert!(data_view_size == fixed_file_info_size);
457 assert!(!data_view.is_null());
458 // * lifetime of block/info is the same as input argument version_info
459 Ok(unsafe { &*(data_view as *const VS_FIXEDFILEINFO) })
460 }
461
462 // KERNEL32_IsWow64Process
463 /// *Returns* an assertion of whether the specified `process` is running under WOW64 on an Intel64 or x64 processor.
464 ///
465 /// Wraps [`Kernel32/IsWow64Process`](https://learn.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-iswow64process).
466 #[allow(dead_code)] // * fn is used by test(s)
467 #[allow(non_snake_case)]
468 pub fn KERNEL32_IsWow64Process(process: HANDLE) -> Result<bool, WinOSError> {
469 // kernel32.dll/IsWow64Process
470 // extern "stdcall" fn(HANDLE, *mut BOOL) -> BOOL
471 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-iswow64process> @@ <https://archive.is/K00m6>
472 let module_file = "kernel32.dll";
473 let symbol_name = "IsWow64Process";
474 let module_path = super::WinOsGetSystemDirectory()?.join(module_file);
475 // let func = super::WinOsGetModuleProcAddress(module_path, procedure); // loads module "permanently" (for the life of current process)
476 let module = WinAPI_LoadLibrary(module_path);
477 let func = WinAPI_GetProcAddress(module, symbol_name);
478 if func.is_null() {
479 return Err(Box::from(format!(
480 "Unable to find DLL procedure '{}' within '{}'",
481 symbol_name, module_file
482 )));
483 }
484
485 let func: extern "stdcall" fn(HANDLE, *mut BOOL) -> BOOL =
486 unsafe { mem::transmute(func as *const ()) };
487
488 let mut is_wow64: BOOL = FALSE;
489 let result: BOOL = func(process, &mut is_wow64);
490
491 let _ = WinAPI_FreeLibrary(module); // FreeLibrary() failure/success can be safely ignored
492
493 Ok((result != FALSE/* func() succeeded` */) && (is_wow64 != FALSE))
494 }
495
496 // NTDLL_RtlGetVersion
497 /// *Returns* version information about the currently running operating system.
498 ///
499 /// Wraps [`NTDLL/RtlGetVersion`](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlgetversion).
500 #[allow(non_snake_case)]
501 pub fn NTDLL_RtlGetVersion() -> Result<OSVERSIONINFOEXW, WinOSError> {
502 // ntdll.dll/RtlGetVersion
503 // extern "stdcall" fn(*mut RTL_OSVERSIONINFOEXW) -> NTSTATUS
504 // ref: <https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlgetversion> @@ <https://archive.is/H1Ls2>
505 // ref: [`RTL_OSVERSIONINFOEXW`](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_osversioninfoexw) @@ <https://archive.is/CtlZS>
506 // note: OSVERSIONINFOEXW == RTL_OSVERSIONINFOEXW ; ref: <https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-osversioninfoexw> @@ <https://archive.is/n4hBb>
507 let module_file = "ntdll.dll";
508 let symbol_name = "RtlGetVersion";
509 let module_path = super::WinOsGetSystemDirectory()?.join(module_file);
510 // let func = super::WinOsGetModuleProcAddress(module_path, procedure); // loads module "permanently" (for the life of current process)
511 let module = WinAPI_LoadLibrary(module_path);
512 let func = WinAPI_GetProcAddress(module, symbol_name);
513 if func.is_null() {
514 return Err(Box::from(format!(
515 "Unable to find DLL procedure '{}' within '{}'",
516 symbol_name, module_file
517 )));
518 }
519 let func: extern "stdcall" fn(*mut RTL_OSVERSIONINFOEXW) -> NTSTATUS =
520 unsafe { mem::transmute(func as *const ()) };
521
522 let mut os_version_info = match create_OSVERSIONINFOEXW() {
523 Ok(value) => value,
524 Err(_) => return Err(Box::from("Unable to create OSVERSIONINFOEXW".to_string())),
525 };
526
527 let result: NTSTATUS = func(&mut os_version_info);
528
529 let _ = WinAPI_FreeLibrary(module); // FreeLibrary() failure/success can be safely ignored
530
531 if result == STATUS_SUCCESS {
532 Ok(os_version_info)
533 } else {
534 Err(Box::from(format!(
535 "RtlGetVersion() failed (result/status: {})",
536 result
537 )))
538 }
539 }
540
541 //#endregion (unsafe code)
542
543 //=== Tests
544
545 #[test]
546 fn structure_clone() {
547 let ffi = VS_FIXEDFILEINFO {
548 dwSignature: 0,
549 dwStrucVersion: 0,
550 dwFileVersionMS: 0,
551 dwFileVersionLS: 0,
552 dwProductVersionMS: 0,
553 dwProductVersionLS: 0,
554 dwFileFlagsMask: 0,
555 dwFileFlags: 0,
556 dwFileOS: 0,
557 dwFileType: 0,
558 dwFileSubtype: 0,
559 dwFileDateMS: 0,
560 dwFileDateLS: 0,
561 };
562 println!("{:?}", ffi);
563 #[allow(clippy::clone_on_copy)] // ignore `clippy::clone_on_copy` warning for direct testing
564 let ffi_clone = ffi.clone();
565 assert_eq!(ffi_clone, ffi);
566 }