winer 0.1.5

Inspect Wine runtimes, host OS details, and hosted processes
Documentation
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use core::ffi::{CStr, c_char, c_void};
use core::mem::{MaybeUninit, transmute};
use core::ops::Deref;
use core::ptr::{NonNull, null, null_mut};
use core::str;

use windows::Wdk::System::SystemInformation::{NtQuerySystemInformation, SYSTEM_INFORMATION_CLASS};
use windows::Win32::Foundation::HMODULE;
use windows::Win32::System::Memory::{GetProcessHeap, HeapFree};

use spin::Once;

#[repr(transparent)]
#[derive(Clone, Copy)]
/// A [`Send`] + [`Sync`] wrapper for Windows [`HMODULE`].
struct Module(HMODULE);
unsafe impl Send for Module {}
unsafe impl Sync for Module {}

impl From<HMODULE> for Module {
    fn from(value: HMODULE) -> Self {
        Self(value)
    }
}

impl From<Module> for HMODULE {
    fn from(value: Module) -> Self {
        value.0
    }
}

macro_rules! req_module {
    ($m:literal) => {
        unsafe {
            use windows::Win32::System::LibraryLoader::GetModuleHandleW;
            use windows::core::w;
            GetModuleHandleW(w!($m))
        }
    };
    ($m:literal => $cache:ident) => {
        *$cache.call_once(|| req_module!($m).unwrap().into())
    };
}

macro_rules! import {
    ($hm:expr, $f:literal) => {
        unsafe {
            use windows::Win32::System::LibraryLoader::GetProcAddress;
            use windows::core::s;
            GetProcAddress($hm, s!($f)).map(|v| core::mem::transmute(v))
        }
    };
    ($hm:expr, $f:literal => $cache:ident) => {
        *$cache.call_once(|| import!($hm, $f))
    };
}

static NTDLL: Once<Module> = Once::new();
static KERNEL32: Once<Module> = Once::new();

pub type GetVersionFn = unsafe extern "C" fn() -> *const c_char;
pub type GetBuildIdFn = unsafe extern "C" fn() -> *const c_char;
pub type GetHostVersionFn = unsafe extern "C" fn(*mut *const c_char, *mut *const c_char);

static GET_VERSION: Once<Option<GetVersionFn>> = Once::new();
static GET_BUILD_ID: Once<Option<GetBuildIdFn>> = Once::new();
static GET_HOST_VERSION: Once<Option<GetHostVersionFn>> = Once::new();

/// Locates the `ntdll` module.
///
/// # Panics
///
/// This function will panic if `ntdll` is not found. This is considered a fatal
/// error because `ntdll` is guaranteed to exist on Wine / modern Windows.
pub fn ntdll() -> HMODULE {
    req_module!("ntdll" => NTDLL).into()
}

/// Locates the `kernel32` module.
///
/// # Panics
///
/// This function will panic if `kernel32` is not found. This is considered a
/// fatal error because `kernel32` is guaranteed to exist on Wine / modern
/// Windows.
pub fn kernel32() -> HMODULE {
    req_module!("kernel32" => KERNEL32).into()
}

/// Locates the `wine_get_version` procedure in the `ntdll` module.
pub fn locate_get_version() -> Option<GetVersionFn> {
    import!(ntdll(), "wine_get_version" => GET_VERSION)
}

/// Locates the `wine_get_build_id` procedure in the `ntdll` module.
pub fn locate_get_build_id() -> Option<GetBuildIdFn> {
    import!(ntdll(), "wine_get_build_id" => GET_BUILD_ID)
}

/// Locates the `wine_get_host_version` procedure in the `ntdll` module.
pub fn locate_get_host_version() -> Option<GetHostVersionFn> {
    import!(ntdll(), "wine_get_host_version" => GET_HOST_VERSION)
}

/// Tells whether the program is running under Wine.
///
/// This function basically checks the existence of `wine_get_version`.
pub fn is_wine() -> bool {
    locate_get_version().is_some()
}

/// Host system information
///
/// The information here usually corresponds to `uname -s` (sysname) and
/// `uname -r` (release) on the host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostVersion {
    sysname: &'static CStr,
    release: &'static CStr,
}

impl HostVersion {
    /// Gets host system name [`CStr`].
    pub fn sysname(&self) -> &'static CStr {
        self.sysname
    }

    /// Gets host system name string.
    pub fn sysname_str(&self) -> Result<&'static str, str::Utf8Error> {
        self.sysname.to_str()
    }

    /// Gets host system release [`CStr`].
    pub fn release(&self) -> &'static CStr {
        self.release
    }

    /// Gets host system release string.
    pub fn release_str(&self) -> Result<&'static str, str::Utf8Error> {
        self.release.to_str()
    }
}

/// Gets current Wine runtime.
///
/// Returns [`None`] on non-Wine environment i.e. standard Windows.
pub fn runtime() -> Option<Runtime> {
    Runtime::probe()
}

/// Wine runtime functions
#[derive(Debug, Clone, Copy)]
pub struct Runtime;

impl Runtime {
    fn probe() -> Option<Self> {
        if self::is_wine() { Some(Self) } else { None }
    }

    /// Gets Wine version by calling `wine_get_version` in `ntdll` under the hood.
    #[inline]
    pub fn version(&self) -> &'static CStr {
        let proc = locate_get_version().expect("Runtime ensures that version API exists.");
        unsafe { CStr::from_ptr(proc()) }
    }

    /// Gets Wine version string, a convenient helper that maps [`Runtime::version`].
    ///
    /// A version string looks like `9.0`.
    #[inline]
    pub fn version_str(&self) -> Result<&'static str, str::Utf8Error> {
        self.version().to_str()
    }

    /// Gets Wine build by calling `wine_get_build_id` in `ntdll`.
    #[inline]
    pub fn build_id(&self) -> Option<&'static CStr> {
        let proc = import!(ntdll(), "wine_get_build_id" => GET_BUILD_ID)?;
        Some(unsafe { CStr::from_ptr(proc()) })
    }

    /// Gets Wine build string, a convenient helper that maps [`Runtime::build_id`].
    ///
    /// A build string looks like `wine-9.0 (Ubuntu 9.0~repack-4build3)`.
    #[inline]
    pub fn build_id_str(&self) -> Option<Result<&'static str, str::Utf8Error>> {
        Some(self.build_id()?.to_str())
    }

    /// Gets host system information by calling `wine_get_host_version`.
    #[inline]
    pub fn host_version(&self) -> Option<HostVersion> {
        let proc = import!(ntdll(), "wine_get_host_version" => GET_HOST_VERSION)?;
        let mut sysname_ptr: *const c_char = null();
        let mut release_ptr: *const c_char = null();
        unsafe {
            proc(&mut sysname_ptr, &mut release_ptr);
            Some(HostVersion {
                sysname: CStr::from_ptr(sysname_ptr),
                release: CStr::from_ptr(release_ptr),
            })
        }
    }

    /// Gets host system name.
    #[inline]
    pub fn host_sysname(&self) -> Option<&'static CStr> {
        Some(self.host_version()?.sysname())
    }

    /// Gets host system name string.
    #[inline]
    pub fn host_sysname_str(&self) -> Option<Result<&'static str, str::Utf8Error>> {
        Some(self.host_version()?.sysname_str())
    }

    /// Gets host system release.
    #[inline]
    pub fn host_release(&self) -> Option<&'static CStr> {
        Some(self.host_version()?.release())
    }

    /// Gets host system release string.
    #[inline]
    pub fn host_release_str(&self) -> Option<Result<&'static str, str::Utf8Error>> {
        Some(self.host_version()?.release_str())
    }

    /// Gets general version information.
    ///
    /// It queries the [`SYSTEM_WINE_VERSION_INFORMATION`] information class.
    pub fn info(&self) -> Result<Info, windows::core::Error> {
        let mut buffer = [MaybeUninit::<u8>::uninit(); Info::BUFFER_SIZE];

        // References:
        // https://gitlab.winehq.org/wine/wine/-/blob/ba6adef9bfc209f1247ba88acec64b58d97100c3/dlls/ntdll/unix/system.c#L3684
        unsafe {
            NtQuerySystemInformation(
                SYSTEM_WINE_VERSION_INFORMATION,
                buffer.as_mut_ptr() as *mut c_void,
                Info::BUFFER_SIZE as u32,
                null_mut(),
            )
            .ok()?
        }

        let buffer: [u8; Info::BUFFER_SIZE] = unsafe { transmute(buffer) };

        // Prefix sum
        let mut offsets = [0usize; Info::SEGMENTS];
        let mut ends_at = 0usize;

        // There are 4 parts in the buffer and they're separated by NUL-byte.
        // `snprintf(info, size, "%s%c%s%c%s%c%s", version, 0, wine_build, 0, buf.sysname, 0, buf.release);`
        let iter = buffer.split_inclusive(|b| *b == 0).take(Info::SEGMENTS);
        for (i, segment) in iter.enumerate() {
            let last = offsets[i];
            if let Some(offset) = offsets.get_mut(i + 1) {
                *offset = last + segment.len();
            } else {
                ends_at = offsets.last().unwrap() + segment.len();
            }
        }

        Ok(Info {
            buffer,
            offsets,
            ends_at,
        })
    }
}

/// Wine extension of system information class
///
/// References:
/// * <https://gitlab.winehq.org/wine/wine/-/blob/ba6adef9bfc209f1247ba88acec64b58d97100c3/include/winternl.h#L2157>
pub const SYSTEM_WINE_VERSION_INFORMATION: SYSTEM_INFORMATION_CLASS =
    SYSTEM_INFORMATION_CLASS(1000i32);

/// Wine version information
///
/// There is a special information class [`SYSTEM_WINE_VERSION_INFORMATION`]
/// present in Wine, which can be used in `NtQuerySystemInformation`. It fills
/// a buffer with the version, build and host system information in one call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Info {
    buffer: [u8; Info::BUFFER_SIZE],
    offsets: [usize; Info::SEGMENTS],
    ends_at: usize,
}

impl Info {
    /// Wine uses a 256-byte buffer for this information.
    ///
    /// References:
    /// * <https://gitlab.winehq.org/wine/wine/-/blob/ba6adef9bfc209f1247ba88acec64b58d97100c3/dlls/ntdll/version.c#L216>
    const BUFFER_SIZE: usize = 256usize;
    const SEGMENTS: usize = 4;

    #[inline]
    fn cstr_at<const N: usize>(&self) -> &CStr {
        let start = self.offsets[N];
        let end = self.offsets.get(N + 1).copied().unwrap_or(self.ends_at);
        unsafe { CStr::from_bytes_with_nul_unchecked(&self.buffer[start..end]) }
    }

    /// Consumes self and returns the raw buffer
    pub fn into_inner(self) -> [u8; Info::BUFFER_SIZE] {
        self.buffer
    }

    /// Gets version.
    pub fn version(&self) -> &CStr {
        self.cstr_at::<0>()
    }

    /// Gets version string.
    pub fn version_str(&self) -> Result<&str, str::Utf8Error> {
        self.version().to_str()
    }

    /// Gets build.
    pub fn build(&self) -> &CStr {
        self.cstr_at::<1>()
    }

    /// Gets build string.
    pub fn build_str(&self) -> Result<&str, str::Utf8Error> {
        self.build().to_str()
    }

    /// Gets host system name.
    pub fn sysname(&self) -> &CStr {
        self.cstr_at::<2>()
    }

    /// Gets host system name string.
    pub fn sysname_str(&self) -> Result<&str, str::Utf8Error> {
        self.sysname().to_str()
    }

    /// Gets host system release.
    pub fn release(&self) -> &CStr {
        self.cstr_at::<3>()
    }

    /// Gets host system release string.
    pub fn release_str(&self) -> Result<&str, str::Utf8Error> {
        self.release().to_str()
    }
}

/// An owned pointer allocated by Wine extensions.
///
/// The memory is assumed to be allocated from the process heap and will be
/// freed with [`HeapFree`][heapfree] on [`Drop`].
///
/// [heapfree]: https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapfree
#[repr(transparent)]
pub struct Owned<T: ?Sized> {
    pointer: NonNull<T>,
}

unsafe impl<T: ?Sized> Send for Owned<T> {}
unsafe impl<T: ?Sized> Sync for Owned<T> {}

impl<T: ?Sized> Owned<T> {
    #[inline]
    const fn new(ptr: *mut T) -> Option<Self> {
        match NonNull::new(ptr) {
            Some(pointer) => Some(Self { pointer }),
            None => None,
        }
    }

    #[inline]
    pub const fn as_nonnull(&self) -> NonNull<T> {
        self.pointer
    }

    #[inline]
    pub const fn as_ptr(&self) -> *const T {
        self.pointer.as_ptr() as *const _
    }

    #[inline]
    pub const fn as_mut_ptr(&self) -> *mut T {
        self.pointer.as_ptr()
    }
}

impl<T: ?Sized> Deref for Owned<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { self.pointer.as_ref() }
    }
}

impl<T: ?Sized> Drop for Owned<T> {
    fn drop(&mut self) {
        unsafe {
            if let Ok(heap) = GetProcessHeap() {
                let _ = HeapFree(heap, Default::default(), Some(self.as_ptr() as *const _));
            }
        }
    }
}

/// Wine path conversions
pub mod path {
    use super::Owned;
    use super::kernel32;

    use core::ffi::{CStr, c_char};
    use windows::core::{PCWSTR, PWSTR};

    use spin::Once;

    #[cfg(feature = "wine-std")]
    use std::ffi::{CString, OsString};
    #[cfg(feature = "wine-std")]
    use std::os::windows::ffi::{OsStrExt, OsStringExt};
    #[cfg(feature = "wine-std")]
    use std::path::{Path, PathBuf};
    #[cfg(feature = "wine-std")]
    pub use typed_path::{UnixPath, UnixPathBuf};
    #[cfg(feature = "wine-std")]
    use windows::Win32::Storage::FileSystem::{GetLongPathNameW, GetShortPathNameW};

    pub type GetUnixFileNameFn = unsafe extern "C" fn(PCWSTR) -> *mut c_char;
    pub type GetDosFileNameFn = unsafe extern "C" fn(*const c_char) -> PWSTR;

    /// Alias of [`widestring::U16CStr`]
    pub type U16CStr = widestring::U16CStr;

    static GET_UNIX_FILE_NAME: Once<Option<GetUnixFileNameFn>> = Once::new();
    static GET_DOS_FILE_NAME: Once<Option<GetDosFileNameFn>> = Once::new();

    /// Locates the `wine_get_unix_file_name` procedure in the `kernel32` module.
    pub fn locate_get_unix_file_name() -> Option<GetUnixFileNameFn> {
        import!(kernel32(), "wine_get_unix_file_name" => GET_UNIX_FILE_NAME)
    }

    /// Locates the `wine_get_dos_file_name` procedure in the `kernel32` module.
    pub fn locate_get_dos_file_name() -> Option<GetDosFileNameFn> {
        import!(kernel32(), "wine_get_dos_file_name" => GET_DOS_FILE_NAME)
    }

    /// Converts a Unix path to Windows path (wide string).
    ///
    /// # Safety
    ///
    /// The raw path must point to a valid NUL-terminated C string.
    pub unsafe fn get_dos_file_name(path: *const c_char) -> Option<Owned<u16>> {
        let proc = locate_get_dos_file_name()?;
        Owned::new(unsafe { proc(path) }.0)
    }

    /// Converts a Windows path (wide string) to host Unix path.
    ///
    /// # Safety
    ///
    /// The raw path must point to a valid NUL-terminated UTF-16 string.
    pub unsafe fn get_unix_file_name(path: *const u16) -> Option<Owned<c_char>> {
        let proc = locate_get_unix_file_name()?;
        Owned::new(unsafe { proc(PCWSTR::from_raw(path)) })
    }

    /// Converts a Unix path (C string) to Windows path (UTF-16 string).
    pub fn unix2dos_str(path: &CStr) -> Option<Owned<U16CStr>> {
        let proc = locate_get_dos_file_name()?;
        let pwstr = unsafe { proc(path.as_ptr()) };
        let wstr = unsafe { U16CStr::from_ptr_str(pwstr.0 as *const _) };
        Owned::new(wstr as *const _ as *mut _)
    }

    /// Converts a Windows path (UTF-16 string) to Unix path (C string).
    pub fn dos2unix_str(path: &U16CStr) -> Option<Owned<CStr>> {
        let proc = locate_get_unix_file_name()?;
        let cstr = unsafe { CStr::from_ptr(proc(PCWSTR::from_raw(path.as_ptr()))) };
        Owned::new(cstr as *const _ as *mut _)
    }

    /// Converts a [`UnixPath`] to Windows [`PathBuf`].
    #[cfg(feature = "wine-std")]
    pub fn unix2dos(path: &UnixPath) -> Option<PathBuf> {
        use widestring::U16CStr;

        let path_cstr = CString::new(path.as_bytes()).ok()?;
        let result = unsafe { get_dos_file_name(path_cstr.as_ptr()) }?;
        let wstr = unsafe { U16CStr::from_ptr_str(result.as_ptr() as *const _) };
        Some(OsString::from_wide(wstr.as_slice()).into())
    }

    /// Converts a Windows [`Path`] to host [`UnixPathBuf`].
    #[cfg(feature = "wine-std")]
    pub fn dos2unix(path: impl AsRef<Path>) -> Option<UnixPathBuf> {
        use core::iter::once;

        let buf = path
            .as_ref()
            .as_os_str()
            .encode_wide()
            .chain(once(0))
            .collect::<Vec<_>>();

        let result = unsafe { get_unix_file_name(buf.as_ptr()) }?;
        let cstr = unsafe { CStr::from_ptr(result.as_ptr()) };
        Some(UnixPath::new(cstr.to_bytes()).to_path_buf())
    }

    /// Path extension trait for short / long paths
    #[cfg(feature = "wine-std")]
    pub trait PathExt {
        /// Converts the path to Windows short form
        fn to_short_path(&self) -> windows::core::Result<PathBuf>;
        /// Converts the path to Windows long form
        fn to_long_path(&self) -> windows::core::Result<PathBuf>;
    }

    #[cfg(feature = "wine-std")]
    type GetPathNameFn = unsafe fn(PWSTR, Option<&mut [u16]>) -> u32;

    #[cfg(feature = "wine-std")]
    fn short_long_convert(proc: GetPathNameFn, path: &Path) -> windows::core::Result<PathBuf> {
        use core::iter::once;
        use windows::Win32::Foundation::GetLastError;

        let mut encoded = path
            .as_os_str()
            .encode_wide()
            .chain(once(0))
            .collect::<Vec<_>>();

        let pwstr = PWSTR::from_raw(encoded.as_mut_ptr());

        // required buffer size in u16 (including NUL)
        let cap = unsafe { proc(pwstr, None) } as usize;
        if cap == 0 {
            Err(unsafe { GetLastError() }.into())
        } else {
            let mut buf = vec![0; cap];
            // copied length in u16 (without NUL) i.e. len = cap - 1
            let len = unsafe { proc(pwstr, Some(buf.as_mut_slice())) } as usize;
            // invariant: len + 1 = buf.len() = cap
            debug_assert_eq!(len + 1, buf.len());
            Ok(OsString::from_wide(&buf[..len]).into())
        }
    }

    #[cfg(feature = "wine-std")]
    impl PathExt for Path {
        fn to_short_path(&self) -> windows::core::Result<PathBuf> {
            short_long_convert(GetShortPathNameW, self)
        }

        fn to_long_path(&self) -> windows::core::Result<PathBuf> {
            short_long_convert(GetLongPathNameW, self)
        }
    }
}