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
use std::any::Any;
#[cfg(windows)]
#[allow(nonstandard_style)]
pub fn acquire_global_lock(name: &str) -> Box<dyn Any> {
    use std::ffi::CString;
    use std::io;
    type LPSECURITY_ATTRIBUTES = *mut u8;
    type BOOL = i32;
    type LPCSTR = *const u8;
    type HANDLE = *mut u8;
    type DWORD = u32;
    const INFINITE: DWORD = !0;
    const WAIT_OBJECT_0: DWORD = 0;
    const WAIT_ABANDONED: DWORD = 0x00000080;
    extern "system" {
        fn CreateMutexA(lpMutexAttributes: LPSECURITY_ATTRIBUTES,
                        bInitialOwner: BOOL,
                        lpName: LPCSTR)
                        -> HANDLE;
        fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
        fn ReleaseMutex(hMutex: HANDLE) -> BOOL;
        fn CloseHandle(hObject: HANDLE) -> BOOL;
    }
    struct Handle(HANDLE);
    impl Drop for Handle {
        fn drop(&mut self) {
            unsafe {
                CloseHandle(self.0);
            }
        }
    }
    struct Guard(Handle);
    impl Drop for Guard {
        fn drop(&mut self) {
            unsafe {
                ReleaseMutex((self.0).0);
            }
        }
    }
    let cname = CString::new(name).unwrap();
    unsafe {
        
        
        
        
        
        let mutex = CreateMutexA(std::ptr::null_mut(), 0, cname.as_ptr() as *const u8);
        if mutex.is_null() {
            panic!("failed to create global mutex named `{}`: {}",
                   name,
                   io::Error::last_os_error());
        }
        let mutex = Handle(mutex);
        
        
        
        
        
        
        
        
        
        
        
        match WaitForSingleObject(mutex.0, INFINITE) {
            WAIT_OBJECT_0 | WAIT_ABANDONED => {}
            code => {
                panic!("WaitForSingleObject failed on global mutex named \
                        `{}`: {} (ret={:x})",
                       name,
                       io::Error::last_os_error(),
                       code);
            }
        }
        
        Box::new(Guard(mutex))
    }
}
#[cfg(not(windows))]
pub fn acquire_global_lock(_name: &str) -> Box<dyn Any> {
    Box::new(())
}