Debian Codegraph @

src/platform/windows.rs

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