Debian Codegraph @

debian/rust-vendor/platform-info/src/platform/windows.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // (c) Alex Lyon <[email protected]>
4 //
5 // For the full copyright and license information, please view the LICENSE file
6 // that was distributed with this source code.
7
8 // Note: there no standardization of values for platform info (or `uname`), so mimic some current practices
9 // busybox-v1.35.0 * `busybox uname -a` => "Windows_NT HOSTNAME 10.0 19044 x86_64 MS/Windows"
10 // python-v3.8.3 => `uname_result(system='Windows', node='HOSTNAME', release='10', version='10.0.19044', machine='AMD64')`
11
12 // refs/research:
13 // [rust ~ std::ffi](https://doc.rust-lang.org/std/ffi)
14 // [rust ~ std::os::windows::ffi](https://doc.rust-lang.org/std/os/windows/ffi)
15 // [WTF-8/WTF-16](https://simonsapin.github.io/wtf-8/#ill-formed-utf-16) @@ <https://archive.is/MG7Aa>
16 // [UCS-2/UTF-8/UTF-16](https://unascribed.com/b/2019-08-02-the-tragedy-of-ucs2.html) @@ <https://archive.is/x4SxI>
17 // [Byte-to/from-String Conversions](https://nicholasbishop.github.io/rust-conversions) @@ <https://archive.is/AnDCY>
18 // [NT Version Info](https://en.wikipedia.org/wiki/Windows_NT) @@ <https://archive.is/GnnvF>
19 // [NT Version Info (summary)](https://simple.wikipedia.org/wiki/Windows_NT) @@ <https://archive.is/T2StZ>
20 // [NT Version Info (detailed)](https://en.wikipedia.org/wiki/Comparison_of_Microsoft_Windows_versions#Windows_NT) @@ <https://archive.is/FSkhj>
21
22 // spell-checker:ignore (abbrev/acronyms) MSVC POSIX SuperH
23 // spell-checker:ignore (API) sysname osname nodename
24 // spell-checker:ignore (jargon) armv aarch hasher mmbr
25 // spell-checker:ignore (people) Roy Ivy III * rivy
26 // spell-checker:ignore (rust) repr stdcall uninit
27 // spell-checker:ignore (uutils) coreutils uutils
28 // 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 VERSIONINFO WCHAR WCHARs winapi winbase winver WSTR wstring
29 // spell-checker:ignore (WinOS) ntdll
30
31 #![warn(unused_results)] // enable warnings for unused results
32
33 use std::convert::TryFrom;
34 use std::ffi::{OsStr, OsString};
35 use std::fmt;
36 use std::fmt::{Debug, Formatter};
37 use std::io;
38 use std::os::windows::ffi::OsStringExt;
39
40 use windows_sys::Win32::Foundation::FALSE;
41 use windows_sys::Win32::System::SystemInformation::{
42 ComputerNamePhysicalDnsHostname, PROCESSOR_ARCHITECTURE_ALPHA, PROCESSOR_ARCHITECTURE_ALPHA64,
43 PROCESSOR_ARCHITECTURE_AMD64, PROCESSOR_ARCHITECTURE_ARM, PROCESSOR_ARCHITECTURE_ARM64,
44 PROCESSOR_ARCHITECTURE_IA64, PROCESSOR_ARCHITECTURE_INTEL, PROCESSOR_ARCHITECTURE_MIPS,
45 PROCESSOR_ARCHITECTURE_PPC, PROCESSOR_ARCHITECTURE_SHX, SYSTEM_INFO, VER_PRODUCT_TYPE,
46 VER_SUITENAME,
47 };
48
49 // Windows type aliases not exported by windows-sys
50 #[allow(non_camel_case_types, clippy::upper_case_acronyms)]
51 pub(crate) type BYTE = u8;
52 #[allow(non_camel_case_types, clippy::upper_case_acronyms)]
53 pub(crate) type WORD = u16;
54 #[allow(non_camel_case_types, clippy::upper_case_acronyms)]
55 pub(crate) type DWORD = u32;
56 #[allow(non_camel_case_types, clippy::upper_case_acronyms)]
57 pub(crate) type UINT = u32;
58
59 // VER_* constants defined locally with types matching their usage context.
60 // windows-sys exports these as u32, but wProductType is u8 and VerSetConditionMask condition is u8.
61 const VER_EQUAL: BYTE = 1;
62 const VER_NT_WORKSTATION: BYTE = 1;
63 const VER_SUITE_WH_SERVER: DWORD = 32768;
64 #[cfg(test)]
65 const VER_NT_SERVER: BYTE = 3;
66 #[cfg(test)]
67 const VER_SUITE_PERSONAL: DWORD = 0x0000_0200;
68 #[cfg(test)]
69 const VER_SUITE_SMALLBUSINESS: DWORD = 0x0000_0001;
70
71 use crate::{PlatformInfoAPI, PlatformInfoError, UNameAPI};
72
73 use super::PathStr;
74 use super::PathString;
75
76 type WinOSError = crate::lib_impl::BoxedThreadSafeStdError;
77
78 mod windows_safe;
79 use windows_safe::{
80 create_OSVERSIONINFOEXW, NTDLL_RtlGetVersion, WinAPI_GetComputerNameExW,
81 WinAPI_GetFileVersionInfoSizeW, WinAPI_GetFileVersionInfoW, WinAPI_GetNativeSystemInfo,
82 WinAPI_GetSystemDirectoryW, WinAPI_VerSetConditionMask, WinAPI_VerifyVersionInfoW,
83 WinOsFileVersionInfoQuery_root,
84 };
85 #[cfg(test)]
86 use windows_safe::{KERNEL32_IsWow64Process, WinAPI_GetCurrentProcess};
87
88 //===
89
90 // PlatformInfo
91 /// Handles initial retrieval and holds cached information for the current platform (Windows/WinOS in this case).
92 #[derive(Clone, Debug, PartialEq, Eq)]
93 pub struct PlatformInfo {
94 /// Cached computer name.
95 pub computer_name: OsString,
96 /// Wraps a cached [`WinApiSystemInfo`].
97 pub system_info: WinApiSystemInfo,
98 /// Wraps a cached [`WinOsVersionInfo`].
99 pub version_info: WinOsVersionInfo,
100 // * private-use fields
101 sysname: OsString,
102 nodename: OsString,
103 release: OsString,
104 version: OsString,
105 machine: OsString,
106 processor: OsString,
107 osname: OsString,
108 }
109
110 impl PlatformInfoAPI for PlatformInfo {
111 // * note: due to the method of information retrieval, this *may* fail
112 fn new() -> Result<Self, PlatformInfoError> {
113 let computer_name = WinOsGetComputerName()?;
114 let system_info = WinApiSystemInfo(WinAPI_GetNativeSystemInfo());
115 let version_info = os_version_info()?;
116
117 let sysname = determine_sysname();
118 let nodename = computer_name.clone();
119 let release = version_info.release.clone();
120 let version = version_info.version.clone();
121 let machine = determine_machine(&system_info);
122 let processor = OsString::from(crate::lib_impl::map_processor(&machine.to_string_lossy()));
123 let osname = determine_osname(&version_info);
124
125 Ok(Self {
126 computer_name,
127 system_info,
128 version_info,
129 /* private use */
130 sysname,
131 nodename,
132 release,
133 version,
134 machine,
135 processor,
136 osname,
137 })
138 }
139 }
140
141 impl UNameAPI for PlatformInfo {
142 fn sysname(&self) -> &OsStr {
143 &self.sysname
144 }
145
146 fn nodename(&self) -> &OsStr {
147 &self.nodename
148 }
149
150 fn release(&self) -> &OsStr {
151 &self.release
152 }
153
154 fn version(&self) -> &OsStr {
155 &self.version
156 }
157
158 fn machine(&self) -> &OsStr {
159 &self.machine
160 }
161
162 fn processor(&self) -> &OsStr {
163 &self.processor
164 }
165
166 fn osname(&self) -> &OsStr {
167 &self.osname
168 }
169 }
170
171 //===
172
173 // WinApiSystemInfo
174 /// Contains information about the current computer system.
175 ///
176 /// Wraps [SYSTEM_INFO](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info).
177 #[derive(Clone, Copy /* , Debug, PartialEq, Eq *//* note: implemented elsewhere */)]
178 pub struct WinApiSystemInfo(
179 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info> @@ <https://archive.is/cqbrj>
180 SYSTEM_INFO,
181 );
182
183 // WinOsVersionInfo
184 /// Contains `WinOS` version information as [`OsString`]'s; for more info, see [NT Version Info (detailed)](https://en.wikipedia.org/wiki/Comparison_of_Microsoft_Windows_versions#Windows_NT).
185 #[derive(Clone, Debug, PartialEq, Eq)]
186 pub struct WinOsVersionInfo {
187 // ref: [NT Version Info (detailed)](https://en.wikipedia.org/wiki/Comparison_of_Microsoft_Windows_versions#Windows_NT) @@ <https://archive.is/FSkhj>
188 /// "Friendly" OS name (eg, "Windows 10")
189 pub os_name: OsString,
190 /// General/main OS version (eg, "10.0")
191 pub release: OsString,
192 /// Specific OS version (eg, "19045")
193 pub version: OsString,
194 }
195
196 //===
197
198 pub mod util {
199 use std::ffi::CString;
200 use std::ffi::OsStr;
201 use std::os::windows::ffi::OsStrExt;
202
203 /// `WinOS` wide character (`wchar_t` / `u16`)
204 #[allow(non_camel_case_types, clippy::upper_case_acronyms)]
205 pub type WCHAR = u16;
206 /// `WinOS` wide-character string buffer
207 /// <br>Note: `WCHAR` (aka `TCHAR`) == `wchar_t` == `u16`
208 #[allow(clippy::upper_case_acronyms)]
209 pub type WSTR = Vec<WCHAR>;
210 /// NUL-terminated `WinOS` wide-character string buffer
211 /// <br>Note: `WCHAR` (aka `TCHAR`) == `wchar_t` == `u16`
212 #[allow(clippy::upper_case_acronyms)]
213 pub type CWSTR = Vec<WCHAR>;
214
215 // to_c_string()
216 /// Convert the leading non-NUL content of any string (which is cheaply convertible to an `OsStr`) into a `CString`, without error.
217 ///
218 /// Any non-Unicode sequences are replaced with [U+FFFD (REPLACEMENT CHARACTER)](https://en.wikipedia.org/wiki/Specials_(Unicode_block)).
219 pub fn to_c_string<S: AsRef<OsStr>>(os_str: S) -> CString {
220 let nul = '\0';
221 let s = os_str.as_ref().to_string_lossy();
222 let leading_s = s.split(nul).next().unwrap_or(""); // string slice of leading non-NUL characters
223
224 let maybe_c_string = CString::new(leading_s);
225 assert!(maybe_c_string.is_ok()); //* failure here == algorithmic/logic error => panic
226 maybe_c_string.unwrap()
227 }
228
229 /// Convert the leading non-NUL content of any string (which is cheaply convertible to an `OsStr`) into a CWSTR, without error.
230 pub fn to_c_wstring<S: AsRef<OsStr>>(os_str: S) -> CWSTR {
231 let nul: WCHAR = 0;
232 let mut wstring: WSTR = os_str.as_ref().encode_wide().collect();
233 wstring.push(nul);
234
235 let maybe_index_first_nul = wstring.iter().position(|&i| i == nul);
236 assert!(maybe_index_first_nul.is_some()); //* failure here == algorithmic/logic error => panic
237 let index_first_nul = maybe_index_first_nul.unwrap();
238 assert!(index_first_nul < wstring.len()); //* failure here == algorithmic/logic error => panic
239 CWSTR::from(&wstring[..=index_first_nul])
240 }
241 }
242
243 //===
244
245 // MmbrVersion
246 /// Contains a version specification as major, minor, build, and revision DWORDs (ie, from *major*.*minor*.*build*.*release* version style).
247 #[derive(Clone, Debug, PartialEq, Eq)]
248 struct MmbrVersion {
249 major: DWORD,
250 minor: DWORD,
251 build: DWORD,
252 release: DWORD,
253 }
254
255 // WinApiFileVersionInfo
256 /// Contains file version info (`VS_VERSIONINFO`) wrapped as a byte vector (`data`).
257 ///
258 /// Wraps [VS_VERSIONINFO](https://learn.microsoft.com/en-us/windows/win32/menurc/vs-versioninfo).
259 #[derive(Clone, Debug, PartialEq, Eq)]
260 pub struct WinApiFileVersionInfo {
261 data: Vec<BYTE>,
262 }
263
264 //===
265
266 impl Debug for WinApiSystemInfo {
267 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
268 f.debug_struct("WinApiSystemInfo")
269 .field("wProcessorArchitecture", &self.wProcessorArchitecture())
270 .field("dwPageSize", &self.0.dwPageSize)
271 .field(
272 "lpMinimumApplicationAddress",
273 &self.0.lpMinimumApplicationAddress,
274 )
275 .field(
276 "lpMaximumApplicationAddress",
277 &self.0.lpMaximumApplicationAddress,
278 )
279 .field("dwActiveProcessorMask", &self.0.dwActiveProcessorMask)
280 .field("dwNumberOfProcessors", &self.0.dwNumberOfProcessors)
281 .field("dwProcessorType", &self.0.dwProcessorType)
282 .field("dwAllocationGranularity", &self.0.dwAllocationGranularity)
283 .field("wProcessorLevel", &self.0.wProcessorLevel)
284 .field("wProcessorRevision", &self.0.wProcessorRevision)
285 .finish()
286 }
287 }
288
289 impl PartialEq for WinApiSystemInfo {
290 fn eq(&self, other: &Self) -> bool {
291 (
292 self.wProcessorArchitecture(),
293 self.0.dwPageSize,
294 self.0.lpMinimumApplicationAddress,
295 self.0.lpMaximumApplicationAddress,
296 self.0.dwActiveProcessorMask,
297 self.0.dwNumberOfProcessors,
298 self.0.dwProcessorType,
299 self.0.dwAllocationGranularity,
300 self.0.wProcessorLevel,
301 self.0.wProcessorRevision,
302 ) == (
303 other.wProcessorArchitecture(),
304 other.0.dwPageSize,
305 other.0.lpMinimumApplicationAddress,
306 other.0.lpMaximumApplicationAddress,
307 other.0.dwActiveProcessorMask,
308 other.0.dwNumberOfProcessors,
309 other.0.dwProcessorType,
310 other.0.dwAllocationGranularity,
311 other.0.wProcessorLevel,
312 other.0.wProcessorRevision,
313 )
314 }
315 }
316
317 impl Eq for WinApiSystemInfo {}
318
319 //===
320
321 // WinOSGetComputerName
322 /// *Returns* a `NetBIOS` or DNS name associated with the local computer.
323 #[allow(non_snake_case)]
324 fn WinOsGetComputerName() -> Result<OsString, WinOSError> {
325 //## NameType ~ using "ComputerNameDnsHostname" vs "ComputerNamePhysicalDnsHostname"
326 // * "ComputerNamePhysicalDnsHostname" *may* have a different (more specific) name when in a DNS cluster
327 // * `uname -n` may show the more specific cluster name (see https://clusterlabs.org/pacemaker/doc/deprecated/en-US/Pacemaker/1.1/html/Clusters_from_Scratch/_short_node_names.html)
328 // * under Linux/Wine, they are *exactly* the same ([from Wine patches msgs](https://www.winehq.org/pipermail/wine-patches/2002-November/004080.html))
329 // * probably want the more specific in-cluster name, but, functionally, any difference will be very rare
330 // ref: [COMPUTER_NAME_FORMAT](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ne-sysinfoapi-computer_name_format) @@ <https://archive.is/s18y0>
331 let name_type = ComputerNamePhysicalDnsHostname; // or ComputerNameDnsHostname
332
333 let mut size: DWORD = 0;
334 let _ = WinAPI_GetComputerNameExW(name_type, None, &mut size);
335 let mut data = vec![0; usize::try_from(size)?];
336 let result = WinAPI_GetComputerNameExW(name_type, &mut data, &mut size);
337 if result == FALSE {
338 return Err(Box::new(io::Error::last_os_error()));
339 }
340 Ok(OsString::from_wide(&data[..usize::try_from(size)?]))
341 }
342
343 // WinOsGetFileVersionInfo
344 /// *Returns* the file version information block for the specified file (`file_path`).
345 #[allow(non_snake_case)]
346 fn WinOsGetFileVersionInfo<P: AsRef<PathStr>>(
347 file_path: P,
348 ) -> Result<WinApiFileVersionInfo, WinOSError> {
349 let file_version_size = WinAPI_GetFileVersionInfoSizeW(&file_path);
350 if file_version_size == 0 {
351 return Err(Box::new(io::Error::last_os_error()));
352 }
353 let mut data: Vec<BYTE> = vec![0; usize::try_from(file_version_size)?];
354 let result = WinAPI_GetFileVersionInfoW(&file_path, &mut data);
355 if result == FALSE {
356 return Err(Box::new(io::Error::last_os_error()));
357 }
358 Ok(WinApiFileVersionInfo { data })
359 }
360
361 // WinOSGetSystemDirectory
362 /// *Returns* a resolved path to the Windows System Directory (aka `%SystemRoot%`).
363 #[allow(non_snake_case)]
364 fn WinOsGetSystemDirectory() -> Result<PathString, WinOSError> {
365 let required_capacity: UINT = WinAPI_GetSystemDirectoryW(None);
366 let mut data = vec![0; usize::try_from(required_capacity)?];
367 let result = WinAPI_GetSystemDirectoryW(&mut data);
368 if result == 0 {
369 return Err(Box::new(io::Error::last_os_error()));
370 }
371 let path = PathString::from(OsString::from_wide(&data[..usize::try_from(result)?]));
372 Ok(path)
373 }
374
375 //===
376
377 // os_version_info
378 /// *Returns* OS version info (as [`WinOsVersionInfo`]) using a DLL procedure call, with fallback version info from a
379 /// known system file.
380 ///
381 /// This call and fallback recipe is necessary because Microsoft deprecated the previously used `GetVersionEx()`, making
382 /// it useless for Windows 8.1 and later windows versions.
383 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getversionexw> @@ <https://archive.is/bYAwT>
384 // ref: <https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-osversioninfoexw> @@ <https://archive.is/n4hBb>
385 fn os_version_info() -> Result<WinOsVersionInfo, WinOSError> {
386 match os_version_info_from_dll() {
387 Ok(os_info) => Ok(os_info),
388 Err(_) => {
389 // as a last resort, try to get the relevant info by loading the version info from a system file
390 // Note: this file version may be just the current "base" version and not the actual most up-to-date version info
391 // * eg: kernel32.dll (or ntdll.dll) version => "10.0.19041.2130" _vs_ `cmd /c ver` => "10.0.19044.2364"
392 version_info_from_file("" /* use default file */)
393 // .or. `return version_info_from_file::<_, &str>(None /* use default file */);`
394 }
395 }
396 }
397
398 // os_version_info_from_dll
399 /// *Returns* version info (as [`WinOsVersionInfo`]) obtained via `NTDLL/RtlGetVersion()`.
400 fn os_version_info_from_dll() -> Result<WinOsVersionInfo, WinOSError> {
401 let os_info = NTDLL_RtlGetVersion()?;
402 Ok(WinOsVersionInfo {
403 os_name: winos_name(
404 os_info.dwMajorVersion,
405 os_info.dwMinorVersion,
406 os_info.dwBuildNumber,
407 os_info.wProductType,
408 os_info.wSuiteMask.into(),
409 )
410 .into(),
411 release: format!("{}.{}", os_info.dwMajorVersion, os_info.dwMinorVersion).into(),
412 version: format!("{}", os_info.dwBuildNumber).into(),
413 })
414 }
415
416 // version_info_from_file
417 /// *Returns* version info (as [`WinOsVersionInfo`]) obtained from `file_path`.
418 ///
419 /// `file_path` ~ if empty or `None`, default to the full path of "kernel32.dll" (a known, omnipresent, system file)
420 fn version_info_from_file<I, P>(file_path: I) -> Result<WinOsVersionInfo, WinOSError>
421 where
422 I: Into<Option<P>>,
423 P: AsRef<PathStr>,
424 {
425 let file_path: PathString = match file_path.into() {
426 Some(ref p) if !p.as_ref().as_os_str().is_empty() => p.as_ref().into(),
427 _ => WinOsGetSystemDirectory()?.join("kernel32.dll"),
428 };
429 let file_info = WinOsGetFileVersionInfo(file_path)?;
430
431 let v = mmbr_from_file_version(&file_info)?;
432
433 let mut info = create_OSVERSIONINFOEXW()?;
434 info.wSuiteMask = WORD::try_from(VER_SUITE_WH_SERVER)?;
435 info.wProductType = VER_NT_WORKSTATION;
436
437 let mask = WinAPI_VerSetConditionMask(0, VER_SUITENAME, VER_EQUAL);
438 let suite_mask = if WinAPI_VerifyVersionInfoW(&info, VER_SUITENAME, mask) == FALSE {
439 0
440 } else {
441 VER_SUITE_WH_SERVER
442 };
443
444 let mask = WinAPI_VerSetConditionMask(0, VER_PRODUCT_TYPE, VER_EQUAL);
445 let product_type = if WinAPI_VerifyVersionInfoW(&info, VER_PRODUCT_TYPE, mask) == FALSE {
446 0
447 } else {
448 VER_NT_WORKSTATION
449 };
450
451 Ok(WinOsVersionInfo {
452 os_name: winos_name(v.major, v.minor, v.build, product_type, suite_mask).into(),
453 release: format!("{}.{}", v.major, v.minor).into(),
454 version: format!("{}", v.build).into(),
455 })
456 }
457
458 // mmbr_from_file_version
459 /// *Returns* version (as an [`MmbrVersion`]) copied from a view (aka slice) into the supplied `file_version_info`.
460 fn mmbr_from_file_version(
461 file_version_info: &WinApiFileVersionInfo,
462 ) -> Result<MmbrVersion, WinOSError> {
463 let info = WinOsFileVersionInfoQuery_root(file_version_info)?;
464 Ok(MmbrVersion {
465 major: info.dwProductVersionMS >> 16,
466 minor: info.dwProductVersionMS & 0xffff,
467 build: info.dwProductVersionLS >> 16,
468 release: info.dwProductVersionLS & 0xffff,
469 })
470 }
471
472 // winos_name
473 /// *Returns* "friendly" `WinOS` name.
474 fn winos_name(
475 major: DWORD,
476 minor: DWORD,
477 build: DWORD,
478 product_type: BYTE,
479 suite_mask: DWORD,
480 ) -> String {
481 // [NT Version Info (detailed)](https://en.wikipedia.org/wiki/Comparison_of_Microsoft_Windows_versions#Windows_NT) @@ <https://archive.is/FSkhj>
482 let default_name = if product_type == VER_NT_WORKSTATION {
483 format!("{} {}.{}", "Windows", major, minor)
484 } else {
485 format!("{} {}.{}", "Windows Server", major, minor)
486 };
487
488 let name = match major {
489 5 => match minor {
490 0 => "Windows 2000",
491 1 => "Windows XP",
492 2 if product_type == VER_NT_WORKSTATION => "Windows XP Professional x64 Edition",
493 2 if suite_mask == VER_SUITE_WH_SERVER => "Windows Home Server",
494 2 => "Windows Server 2003",
495 _ => &default_name,
496 },
497 6 => match minor {
498 0 if product_type == VER_NT_WORKSTATION => "Windows Vista",
499 0 => "Windows Server 2008",
500 1 if product_type != VER_NT_WORKSTATION => "Windows Server 2008 R2",
501 1 => "Windows 7",
502 2 if product_type != VER_NT_WORKSTATION => "Windows Server 2012",
503 2 => "Windows 8",
504 3 if product_type != VER_NT_WORKSTATION => "Windows Server 2012 R2",
505 3 => "Windows 8.1",
506 _ => &default_name,
507 },
508 10 => match minor {
509 0 if product_type == VER_NT_WORKSTATION && (build >= 22000) => "Windows 11",
510 0 if product_type != VER_NT_WORKSTATION && (14000..17000).contains(&build) => {
511 "Windows Server 2016"
512 }
513 0 if product_type != VER_NT_WORKSTATION && (17000..19000).contains(&build) => {
514 "Windows Server 2019"
515 }
516 0 if product_type != VER_NT_WORKSTATION && (build >= 20000) => "Windows Server 2022",
517 _ => "Windows 10",
518 },
519 _ => &default_name,
520 };
521
522 name.to_string()
523 }
524
525 //===
526
527 fn determine_machine(system_info: &WinApiSystemInfo) -> OsString {
528 let arch = system_info.wProcessorArchitecture();
529
530 // ref: [SYSTEM_INFO structure](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info) @@ <https://archive.is/cqbrj>
531 // ref: [LLVM Triples](https://llvm.org/doxygen/classllvm_1_1Triple.html) @@ <https://archive.is/MwVL8>
532 // ref: [SuperH](https://en.wikipedia.org/wiki/SuperH) @@ <https://archive.is/ckr6a>
533 // ref: [OldNewThing ~ SuperH](https://devblogs.microsoft.com/oldnewthing/20190805-00/?p=102749) @@ <https://archive.is/KWlyV>
534 let arch_str = match arch {
535 PROCESSOR_ARCHITECTURE_AMD64 => "x86_64",
536 PROCESSOR_ARCHITECTURE_INTEL => match system_info.0.wProcessorLevel {
537 4 => "i486",
538 5 => "i586",
539 6 => "i686",
540 _ => "i386",
541 },
542 PROCESSOR_ARCHITECTURE_IA64 => "ia64",
543 PROCESSOR_ARCHITECTURE_ARM => "arm", // `arm` may be under-specified compared to GNU implementations
544 PROCESSOR_ARCHITECTURE_ARM64 => "aarch64", // alternatively, `arm64` may be more correct
545 PROCESSOR_ARCHITECTURE_MIPS => "mips",
546 PROCESSOR_ARCHITECTURE_PPC => "powerpc",
547 PROCESSOR_ARCHITECTURE_ALPHA | PROCESSOR_ARCHITECTURE_ALPHA64 => "alpha",
548 PROCESSOR_ARCHITECTURE_SHX => "superh", // a "SuperH" processor
549 _ => "unknown",
550 };
551
552 OsString::from(arch_str)
553 }
554
555 fn determine_osname(version_info: &WinOsVersionInfo) -> OsString {
556 let mut osname = OsString::from(crate::lib_impl::HOST_OS_NAME);
557 osname.extend([
558 OsString::from(" ("),
559 version_info.os_name.clone(),
560 OsString::from(")"),
561 ]);
562 osname
563 }
564
565 fn determine_sysname() -> OsString {
566 // As of 2023-02, possible Windows kernels == [ "Windows_9x", "Windows_NT" ]
567 // * "Windows_9x" hit end-of-service-life on 2006-07-11 (ref: [Windows_9x](https://en.wikipedia.org/wiki/Windows_9x) @@ <https://archive.is/wip/K6fhN>)
568 OsString::from("Windows_NT") // compatible with `busybox` and MS (from std::env::var("OS"))
569 }
570
571 //=== Tests
572
573 #[test]
574 fn test_sysname() {
575 let info = PlatformInfo::new().unwrap();
576 let sysname = info.sysname().to_os_string();
577 let expected = std::env::var_os("OS").unwrap_or_else(|| OsString::from("Windows_NT"));
578 println!("sysname=[{}]'{:#?}'", sysname.len(), sysname);
579 assert_eq!(sysname, expected);
580 }
581
582 #[test]
583 #[allow(non_snake_case)]
584 fn test_nodename_no_trailing_NUL() {
585 let info = PlatformInfo::new().unwrap();
586 let nodename = info.nodename().to_string_lossy();
587 let trimmed = nodename.trim().trim_end_matches('\0');
588 println!("nodename=[{}]'{}'", nodename.len(), nodename);
589 assert_eq!(nodename, trimmed);
590 }
591
592 #[test]
593 fn test_machine() {
594 let is_wow64 = KERNEL32_IsWow64Process(WinAPI_GetCurrentProcess()).unwrap_or_else(|err| {
595 println!("ERR: IsWow64Process(): {err:#?}");
596 false
597 });
598
599 let target = if cfg!(target_arch = "x86_64") || (cfg!(target_arch = "x86") && is_wow64) {
600 vec!["x86_64"]
601 } else if cfg!(target_arch = "x86") {
602 vec!["i386", "i486", "i586", "i686"]
603 } else if cfg!(target_arch = "arm") {
604 vec!["arm"]
605 } else if cfg!(target_arch = "aarch64") {
606 // NOTE: keeping both of these until the correct behavior is sorted out
607 vec!["arm64", "aarch64"]
608 } else if cfg!(target_arch = "powerpc") {
609 vec!["powerpc"]
610 } else if cfg!(target_arch = "mips") {
611 vec!["mips"]
612 } else {
613 // NOTE: the other architecture are currently not valid targets for Rust (in fact, I am
614 // almost certain some of these are not even valid targets for the Windows build)
615 vec!["unknown"]
616 };
617 println!("target={target:#?}");
618
619 let info = PlatformInfo::new().unwrap();
620 let machine = info.machine().to_string_lossy();
621 println!("machine=[{}]'{}'", machine.len(), machine);
622
623 assert!(target.contains(&&machine[..]));
624 }
625
626 #[test]
627 fn test_osname() {
628 let info = PlatformInfo::new().unwrap();
629 let osname = info.osname().to_string_lossy();
630 println!("osname=[{}]'{}'", osname.len(), osname);
631 assert!(osname.starts_with(crate::lib_impl::HOST_OS_NAME));
632 }
633
634 #[test]
635 fn test_version_vs_version() {
636 let version_via_dll = os_version_info_from_dll().unwrap();
637 let version_via_file = version_info_from_file::<_, &str>(None).unwrap();
638 assert_eq!(version_via_file, version_info_from_file("").unwrap());
639
640 println!("version (via dll) = '{version_via_dll:#?}'");
641 println!("version (via known file) = '{version_via_file:#?}'");
642
643 assert_eq!(version_via_dll.os_name, version_via_file.os_name);
644 assert_eq!(version_via_dll.release, version_via_file.release);
645 // the "version" portions may differ, but should have only slight variation
646 // * assume that "version" is convertible to u32 + "version" from file is always earlier/smaller and may differ only below the thousands digit
647 // * ref: [NT Version Info (detailed)](https://en.wikipedia.org/wiki/Comparison_of_Microsoft_Windows_versions#Windows_NT) @@ <https://archive.is/FSkhj>
648 let version_via_dll_n = version_via_dll
649 .version
650 .to_string_lossy()
651 .parse::<u32>()
652 .unwrap();
653 let version_via_file_n = version_via_file
654 .version
655 .to_string_lossy()
656 .parse::<u32>()
657 .unwrap();
658 assert!(version_via_dll_n.checked_sub(version_via_file_n) < Some(1000));
659 }
660
661 #[test]
662 #[allow(clippy::too_many_lines)]
663 fn test_known_winos_names() {
664 // ref: [NT Version Info (detailed)](https://en.wikipedia.org/wiki/Comparison_of_Microsoft_Windows_versions#Windows_NT) @@ <https://archive.is/FSkhj>
665 assert_eq!(
666 winos_name(3, 1, 528, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
667 "Windows 3.1"
668 );
669 assert_eq!(
670 winos_name(3, 5, 807, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
671 "Windows 3.5"
672 );
673 assert_eq!(
674 winos_name(3, 51, 1057, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
675 "Windows 3.51"
676 );
677 assert_eq!(
678 winos_name(4, 0, 1381, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
679 "Windows 4.0"
680 );
681 assert_eq!(
682 winos_name(5, 0, 2195, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
683 "Windows 2000"
684 );
685 assert_eq!(
686 winos_name(5, 1, 2600, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
687 "Windows XP"
688 );
689 assert_eq!(
690 winos_name(5, 2, 3790, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
691 "Windows XP Professional x64 Edition"
692 );
693 assert_eq!(
694 winos_name(5, 2, 3790, VER_NT_SERVER, VER_SUITE_WH_SERVER),
695 "Windows Home Server"
696 );
697 assert_eq!(
698 winos_name(5, 2, 3790, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
699 "Windows Server 2003"
700 );
701 assert_eq!(
702 winos_name(5, 2, 3790, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
703 "Windows Server 2003"
704 );
705 assert_eq!(
706 winos_name(6, 0, 6000, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
707 "Windows Vista"
708 );
709 assert_eq!(
710 winos_name(6, 0, 6001, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
711 "Windows Server 2008"
712 );
713 assert_eq!(
714 winos_name(6, 1, 7600, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
715 "Windows 7"
716 );
717 assert_eq!(
718 winos_name(6, 1, 7600, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
719 "Windows Server 2008 R2"
720 );
721 assert_eq!(
722 winos_name(6, 2, 9200, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
723 "Windows Server 2012"
724 );
725 assert_eq!(
726 winos_name(6, 2, 9200, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
727 "Windows 8"
728 );
729 assert_eq!(
730 winos_name(6, 3, 9600, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
731 "Windows 8.1"
732 );
733 assert_eq!(
734 winos_name(6, 3, 9600, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
735 "Windows Server 2012 R2"
736 );
737 assert_eq!(
738 winos_name(10, 0, 10240, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
739 "Windows 10"
740 );
741 assert_eq!(
742 winos_name(10, 0, 17134, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
743 "Windows 10"
744 );
745 assert_eq!(
746 winos_name(10, 0, 19141, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
747 "Windows 10"
748 );
749 assert_eq!(
750 winos_name(10, 0, 19145, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
751 "Windows 10"
752 );
753 assert_eq!(
754 winos_name(10, 0, 14393, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
755 "Windows Server 2016"
756 );
757 assert_eq!(
758 winos_name(10, 0, 17763, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
759 "Windows Server 2019"
760 );
761 assert_eq!(
762 winos_name(10, 0, 20348, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
763 "Windows Server 2022"
764 );
765 assert_eq!(
766 winos_name(10, 0, 22000, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
767 "Windows 11"
768 );
769 assert_eq!(
770 winos_name(10, 0, 22621, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
771 "Windows 11"
772 );
773 // test unmatched versions (triggers `_` matches and returns a `default_name`)
774 assert_eq!(
775 winos_name(5, 9, 3790, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
776 "Windows 5.9"
777 );
778 assert_eq!(
779 winos_name(5, 9, 3790, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
780 "Windows Server 5.9"
781 );
782 assert_eq!(
783 winos_name(6, 9, 9600, VER_NT_WORKSTATION, VER_SUITE_PERSONAL),
784 "Windows 6.9"
785 );
786 assert_eq!(
787 winos_name(6, 9, 9600, VER_NT_SERVER, VER_SUITE_SMALLBUSINESS),
788 "Windows Server 6.9"
789 );
790 }
791
792 #[test]
793 fn test_processor() {
794 let info = PlatformInfo::new().unwrap();
795 let processor = info.processor().to_string_lossy();
796
797 // Processor should not be empty
798 assert!(!processor.is_empty());
799
800 // On common Windows platforms, verify expected mappings
801 #[cfg(target_arch = "x86_64")]
802 assert_eq!(processor, "x86_64", "Windows x86_64 should pass through");
803
804 #[cfg(target_arch = "x86")]
805 assert_eq!(processor, "i686", "Windows x86 should normalize to i686");
806
807 #[cfg(target_arch = "aarch64")]
808 assert_eq!(
809 processor, "aarch64",
810 "Windows ARM64 should pass through as aarch64"
811 );
812
813 println!("Windows processor=[{}]'{}'", processor.len(), processor);
814 }
815
816 #[test]
817 fn structure_clone() {
818 let info = PlatformInfo::new().unwrap();
819 println!("{info:?}");
820 #[allow(clippy::redundant_clone)] // ignore `clippy::redundant_clone` warning for direct testing
821 let info_copy = info.clone();
822 assert_eq!(info_copy, info);
823
824 let mmbr = MmbrVersion {
825 major: 1,
826 minor: 2,
827 build: 3,
828 release: 4,
829 };
830 println!("{mmbr:?}");
831 #[allow(clippy::redundant_clone)] // ignore `clippy::redundant_clone` warning for direct testing
832 let mmbr_copy = mmbr.clone();
833 assert_eq!(mmbr_copy, mmbr);
834
835 let fvi = WinApiFileVersionInfo {
836 data: vec![1, 2, 3, 4],
837 };
838 println!("{fvi:?}");
839 #[allow(clippy::redundant_clone)] // ignore `clippy::redundant_clone` warning for direct testing
840 let fvi_copy = fvi.clone();
841 assert_eq!(fvi_copy, fvi);
842 }