diff options
| author | Alex Crichton <alex@alexcrichton.com> | 2015-11-02 16:23:22 -0800 |
|---|---|---|
| committer | Alex Crichton <alex@alexcrichton.com> | 2015-11-09 22:55:50 -0800 |
| commit | 3d28b8b98e6e4f55ef4ecd8babf0a050f48a3d11 (patch) | |
| tree | 343087c9e62da65e2780db851682280697064c5b /src/libstd/sys/windows | |
| parent | c8a29c2092cec369a751051a2bfed093522ff6e8 (diff) | |
| download | rust-3d28b8b98e6e4f55ef4ecd8babf0a050f48a3d11.tar.gz rust-3d28b8b98e6e4f55ef4ecd8babf0a050f48a3d11.zip | |
std: Migrate to the new libc
* Delete `sys::unix::{c, sync}` as these are now all folded into libc itself
* Update all references to use `libc` as a result.
* Update all references to the new flat namespace.
* Moves all windows bindings into sys::c
Diffstat (limited to 'src/libstd/sys/windows')
| -rw-r--r-- | src/libstd/sys/windows/backtrace.rs | 297 | ||||
| -rw-r--r-- | src/libstd/sys/windows/c.rs | 1287 | ||||
| -rw-r--r-- | src/libstd/sys/windows/compat.rs | 11 | ||||
| -rw-r--r-- | src/libstd/sys/windows/condvar.rs | 6 | ||||
| -rw-r--r-- | src/libstd/sys/windows/ext/io.rs | 3 | ||||
| -rw-r--r-- | src/libstd/sys/windows/fs.rs | 163 | ||||
| -rw-r--r-- | src/libstd/sys/windows/handle.rs | 35 | ||||
| -rw-r--r-- | src/libstd/sys/windows/mod.rs | 61 | ||||
| -rw-r--r-- | src/libstd/sys/windows/net.rs | 72 | ||||
| -rw-r--r-- | src/libstd/sys/windows/os.rs | 85 | ||||
| -rw-r--r-- | src/libstd/sys/windows/pipe.rs | 7 | ||||
| -rw-r--r-- | src/libstd/sys/windows/printing/gnu.rs | 9 | ||||
| -rw-r--r-- | src/libstd/sys/windows/printing/msvc.rs | 35 | ||||
| -rw-r--r-- | src/libstd/sys/windows/process.rs | 68 | ||||
| -rw-r--r-- | src/libstd/sys/windows/stack_overflow.rs | 5 | ||||
| -rw-r--r-- | src/libstd/sys/windows/stdio.rs | 11 | ||||
| -rw-r--r-- | src/libstd/sys/windows/thread.rs | 9 | ||||
| -rw-r--r-- | src/libstd/sys/windows/thread_local.rs | 43 | ||||
| -rw-r--r-- | src/libstd/sys/windows/time.rs | 15 |
19 files changed, 1345 insertions, 877 deletions
diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index b562e772b9c..d106bc3285c 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -27,12 +27,13 @@ use io::prelude::*; use dynamic_lib::DynamicLibrary; -use intrinsics; use io; -use libc; +use libc::c_void; +use mem; use path::Path; use ptr; use sync::StaticMutex; +use sys::c; macro_rules! sym{ ($lib:expr, $e:expr, $t:ident) => (unsafe { let lib = $lib; @@ -50,264 +51,50 @@ mod printing; #[path = "printing/gnu.rs"] mod printing; -#[allow(non_snake_case)] -extern "system" { - fn GetCurrentProcess() -> libc::HANDLE; - fn GetCurrentThread() -> libc::HANDLE; - fn RtlCaptureContext(ctx: *mut arch::CONTEXT); -} - type SymFromAddrFn = - extern "system" fn(libc::HANDLE, u64, *mut u64, - *mut SYMBOL_INFO) -> libc::BOOL; + extern "system" fn(c::HANDLE, u64, *mut u64, + *mut c::SYMBOL_INFO) -> c::BOOL; type SymGetLineFromAddr64Fn = - extern "system" fn(libc::HANDLE, u64, *mut u32, - *mut IMAGEHLP_LINE64) -> libc::BOOL; + extern "system" fn(c::HANDLE, u64, *mut u32, + *mut c::IMAGEHLP_LINE64) -> c::BOOL; type SymInitializeFn = - extern "system" fn(libc::HANDLE, *mut libc::c_void, - libc::BOOL) -> libc::BOOL; + extern "system" fn(c::HANDLE, *mut c_void, + c::BOOL) -> c::BOOL; type SymCleanupFn = - extern "system" fn(libc::HANDLE) -> libc::BOOL; + extern "system" fn(c::HANDLE) -> c::BOOL; type StackWalk64Fn = - extern "system" fn(libc::DWORD, libc::HANDLE, libc::HANDLE, - *mut STACKFRAME64, *mut arch::CONTEXT, - *mut libc::c_void, *mut libc::c_void, - *mut libc::c_void, *mut libc::c_void) -> libc::BOOL; - -const MAX_SYM_NAME: usize = 2000; -const IMAGE_FILE_MACHINE_I386: libc::DWORD = 0x014c; -const IMAGE_FILE_MACHINE_IA64: libc::DWORD = 0x0200; -const IMAGE_FILE_MACHINE_AMD64: libc::DWORD = 0x8664; - -#[repr(C)] -struct SYMBOL_INFO { - SizeOfStruct: libc::c_ulong, - TypeIndex: libc::c_ulong, - Reserved: [u64; 2], - Index: libc::c_ulong, - Size: libc::c_ulong, - ModBase: u64, - Flags: libc::c_ulong, - Value: u64, - Address: u64, - Register: libc::c_ulong, - Scope: libc::c_ulong, - Tag: libc::c_ulong, - NameLen: libc::c_ulong, - MaxNameLen: libc::c_ulong, - // note that windows has this as 1, but it basically just means that - // the name is inline at the end of the struct. For us, we just bump - // the struct size up to MAX_SYM_NAME. - Name: [libc::c_char; MAX_SYM_NAME], -} - -#[repr(C)] -struct IMAGEHLP_LINE64 { - SizeOfStruct: u32, - Key: *const libc::c_void, - LineNumber: u32, - Filename: *const libc::c_char, - Address: u64, -} - -#[repr(C)] -enum ADDRESS_MODE { - AddrMode1616, - AddrMode1632, - AddrModeReal, - AddrModeFlat, -} - -struct ADDRESS64 { - Offset: u64, - Segment: u16, - Mode: ADDRESS_MODE, -} - -pub struct STACKFRAME64 { - AddrPC: ADDRESS64, - AddrReturn: ADDRESS64, - AddrFrame: ADDRESS64, - AddrStack: ADDRESS64, - AddrBStore: ADDRESS64, - FuncTableEntry: *mut libc::c_void, - Params: [u64; 4], - Far: libc::BOOL, - Virtual: libc::BOOL, - Reserved: [u64; 3], - KdHelp: KDHELP64, -} - -struct KDHELP64 { - Thread: u64, - ThCallbackStack: libc::DWORD, - ThCallbackBStore: libc::DWORD, - NextCallback: libc::DWORD, - FramePointer: libc::DWORD, - KiCallUserMode: u64, - KeUserCallbackDispatcher: u64, - SystemRangeStart: u64, - KiUserExceptionDispatcher: u64, - StackBase: u64, - StackLimit: u64, - Reserved: [u64; 5], -} + extern "system" fn(c::DWORD, c::HANDLE, c::HANDLE, + *mut c::STACKFRAME64, *mut c::CONTEXT, + *mut c_void, *mut c_void, + *mut c_void, *mut c_void) -> c::BOOL; #[cfg(target_arch = "x86")] -mod arch { - use libc; - - const MAXIMUM_SUPPORTED_EXTENSION: usize = 512; - - #[repr(C)] - pub struct CONTEXT { - ContextFlags: libc::DWORD, - Dr0: libc::DWORD, - Dr1: libc::DWORD, - Dr2: libc::DWORD, - Dr3: libc::DWORD, - Dr6: libc::DWORD, - Dr7: libc::DWORD, - FloatSave: FLOATING_SAVE_AREA, - SegGs: libc::DWORD, - SegFs: libc::DWORD, - SegEs: libc::DWORD, - SegDs: libc::DWORD, - Edi: libc::DWORD, - Esi: libc::DWORD, - Ebx: libc::DWORD, - Edx: libc::DWORD, - Ecx: libc::DWORD, - Eax: libc::DWORD, - Ebp: libc::DWORD, - Eip: libc::DWORD, - SegCs: libc::DWORD, - EFlags: libc::DWORD, - Esp: libc::DWORD, - SegSs: libc::DWORD, - ExtendedRegisters: [u8; MAXIMUM_SUPPORTED_EXTENSION], - } - - #[repr(C)] - pub struct FLOATING_SAVE_AREA { - ControlWord: libc::DWORD, - StatusWord: libc::DWORD, - TagWord: libc::DWORD, - ErrorOffset: libc::DWORD, - ErrorSelector: libc::DWORD, - DataOffset: libc::DWORD, - DataSelector: libc::DWORD, - RegisterArea: [u8; 80], - Cr0NpxState: libc::DWORD, - } - - pub fn init_frame(frame: &mut super::STACKFRAME64, - ctx: &CONTEXT) -> libc::DWORD { - frame.AddrPC.Offset = ctx.Eip as u64; - frame.AddrPC.Mode = super::ADDRESS_MODE::AddrModeFlat; - frame.AddrStack.Offset = ctx.Esp as u64; - frame.AddrStack.Mode = super::ADDRESS_MODE::AddrModeFlat; - frame.AddrFrame.Offset = ctx.Ebp as u64; - frame.AddrFrame.Mode = super::ADDRESS_MODE::AddrModeFlat; - super::IMAGE_FILE_MACHINE_I386 - } +pub fn init_frame(frame: &mut c::STACKFRAME64, + ctx: &c::CONTEXT) -> c::DWORD { + frame.AddrPC.Offset = ctx.Eip as u64; + frame.AddrPC.Mode = c::ADDRESS_MODE::AddrModeFlat; + frame.AddrStack.Offset = ctx.Esp as u64; + frame.AddrStack.Mode = c::ADDRESS_MODE::AddrModeFlat; + frame.AddrFrame.Offset = ctx.Ebp as u64; + frame.AddrFrame.Mode = c::ADDRESS_MODE::AddrModeFlat; + c::IMAGE_FILE_MACHINE_I386 } #[cfg(target_arch = "x86_64")] -mod arch { - #![allow(deprecated)] - - use libc::{c_longlong, c_ulonglong}; - use libc::types::os::arch::extra::{WORD, DWORD, DWORDLONG}; - use simd; - - #[repr(C)] - pub struct CONTEXT { - _align_hack: [simd::u64x2; 0], // FIXME align on 16-byte - P1Home: DWORDLONG, - P2Home: DWORDLONG, - P3Home: DWORDLONG, - P4Home: DWORDLONG, - P5Home: DWORDLONG, - P6Home: DWORDLONG, - - ContextFlags: DWORD, - MxCsr: DWORD, - - SegCs: WORD, - SegDs: WORD, - SegEs: WORD, - SegFs: WORD, - SegGs: WORD, - SegSs: WORD, - EFlags: DWORD, - - Dr0: DWORDLONG, - Dr1: DWORDLONG, - Dr2: DWORDLONG, - Dr3: DWORDLONG, - Dr6: DWORDLONG, - Dr7: DWORDLONG, - - Rax: DWORDLONG, - Rcx: DWORDLONG, - Rdx: DWORDLONG, - Rbx: DWORDLONG, - Rsp: DWORDLONG, - Rbp: DWORDLONG, - Rsi: DWORDLONG, - Rdi: DWORDLONG, - R8: DWORDLONG, - R9: DWORDLONG, - R10: DWORDLONG, - R11: DWORDLONG, - R12: DWORDLONG, - R13: DWORDLONG, - R14: DWORDLONG, - R15: DWORDLONG, - - Rip: DWORDLONG, - - FltSave: FLOATING_SAVE_AREA, - - VectorRegister: [M128A; 26], - VectorControl: DWORDLONG, - - DebugControl: DWORDLONG, - LastBranchToRip: DWORDLONG, - LastBranchFromRip: DWORDLONG, - LastExceptionToRip: DWORDLONG, - LastExceptionFromRip: DWORDLONG, - } - - #[repr(C)] - pub struct M128A { - _align_hack: [simd::u64x2; 0], // FIXME align on 16-byte - Low: c_ulonglong, - High: c_longlong - } - - #[repr(C)] - pub struct FLOATING_SAVE_AREA { - _align_hack: [simd::u64x2; 0], // FIXME align on 16-byte - _Dummy: [u8; 512] // FIXME: Fill this out - } - - pub fn init_frame(frame: &mut super::STACKFRAME64, - ctx: &CONTEXT) -> DWORD { - frame.AddrPC.Offset = ctx.Rip as u64; - frame.AddrPC.Mode = super::ADDRESS_MODE::AddrModeFlat; - frame.AddrStack.Offset = ctx.Rsp as u64; - frame.AddrStack.Mode = super::ADDRESS_MODE::AddrModeFlat; - frame.AddrFrame.Offset = ctx.Rbp as u64; - frame.AddrFrame.Mode = super::ADDRESS_MODE::AddrModeFlat; - super::IMAGE_FILE_MACHINE_AMD64 - } +pub fn init_frame(frame: &mut c::STACKFRAME64, + ctx: &c::CONTEXT) -> c::DWORD { + frame.AddrPC.Offset = ctx.Rip as u64; + frame.AddrPC.Mode = c::ADDRESS_MODE::AddrModeFlat; + frame.AddrStack.Offset = ctx.Rsp as u64; + frame.AddrStack.Mode = c::ADDRESS_MODE::AddrModeFlat; + frame.AddrFrame.Offset = ctx.Rbp as u64; + frame.AddrFrame.Mode = c::ADDRESS_MODE::AddrModeFlat; + c::IMAGE_FILE_MACHINE_AMD64 } struct Cleanup { - handle: libc::HANDLE, + handle: c::HANDLE, SymCleanup: SymCleanupFn, } @@ -335,16 +122,16 @@ pub fn write(w: &mut Write) -> io::Result<()> { let StackWalk64 = sym!(&dbghelp, "StackWalk64", StackWalk64Fn); // Allocate necessary structures for doing the stack walk - let process = unsafe { GetCurrentProcess() }; - let thread = unsafe { GetCurrentThread() }; - let mut context: arch::CONTEXT = unsafe { intrinsics::init() }; - unsafe { RtlCaptureContext(&mut context); } - let mut frame: STACKFRAME64 = unsafe { intrinsics::init() }; - let image = arch::init_frame(&mut frame, &context); + let process = unsafe { c::GetCurrentProcess() }; + let thread = unsafe { c::GetCurrentThread() }; + let mut context: c::CONTEXT = unsafe { mem::zeroed() }; + unsafe { c::RtlCaptureContext(&mut context); } + let mut frame: c::STACKFRAME64 = unsafe { mem::zeroed() }; + let image = init_frame(&mut frame, &context); // Initialize this process's symbols - let ret = SymInitialize(process, ptr::null_mut(), libc::TRUE); - if ret != libc::TRUE { return Ok(()) } + let ret = SymInitialize(process, ptr::null_mut(), c::TRUE); + if ret != c::TRUE { return Ok(()) } let _c = Cleanup { handle: process, SymCleanup: SymCleanup }; // And now that we're done with all the setup, do the stack walking! @@ -356,7 +143,7 @@ pub fn write(w: &mut Write) -> io::Result<()> { ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), - ptr::null_mut()) == libc::TRUE{ + ptr::null_mut()) == c::TRUE { let addr = frame.AddrPC.Offset; if addr == frame.AddrReturn.Offset || addr == 0 || frame.AddrReturn.Offset == 0 { break } diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs index 270e260d504..42f182eb010 100644 --- a/src/libstd/sys/windows/c.rs +++ b/src/libstd/sys/windows/c.rs @@ -10,87 +10,336 @@ //! C definitions used by libnative that don't belong in liblibc -#![allow(bad_style, dead_code, overflowing_literals)] +#![allow(bad_style, overflowing_literals, dead_code, deprecated, unused_imports)] -use libc; -use libc::{c_uint, c_ulong}; -use libc::{DWORD, BOOL, BOOLEAN, ERROR_CALL_NOT_IMPLEMENTED, LPVOID, HANDLE}; -use libc::{LPCWSTR, LONG}; +use os::raw::{c_int, c_uint, c_ulong, c_long, c_longlong, c_ushort}; +use os::raw::{c_char, c_short, c_ulonglong}; +use libc::{wchar_t, size_t, c_void}; use ptr; +use simd; pub use self::GET_FILEEX_INFO_LEVELS::*; pub use self::FILE_INFO_BY_HANDLE_CLASS::*; -pub use libc::consts::os::extra::{ - FILE_ATTRIBUTE_READONLY, - FILE_ATTRIBUTE_DIRECTORY, - WSAPROTOCOL_LEN, -}; -pub use libc::types::os::arch::extra::{GROUP, GUID, WSAPROTOCOLCHAIN}; +pub use self::EXCEPTION_DISPOSITION::*; -pub const WSADESCRIPTION_LEN: usize = 256; -pub const WSASYS_STATUS_LEN: usize = 128; -pub const FIONBIO: libc::c_long = 0x8004667e; +pub type DWORD = c_ulong; +pub type HANDLE = LPVOID; +pub type HINSTANCE = HANDLE; +pub type HMODULE = HINSTANCE; +pub type BOOL = c_int; +pub type BYTE = u8; +pub type BOOLEAN = BYTE; +pub type GROUP = c_uint; +pub type LONG_PTR = isize; +pub type LARGE_INTEGER = c_longlong; +pub type LONG = c_long; +pub type UINT = c_uint; +pub type WCHAR = u16; +pub type USHORT = c_ushort; +pub type SIZE_T = usize; +pub type WORD = u16; +pub type CHAR = c_char; +pub type HCRYPTPROV = LONG_PTR; +pub type ULONG_PTR = c_ulonglong; +pub type ULONG = c_ulong; +pub type ULONGLONG = u64; +pub type DWORDLONG = ULONGLONG; + +pub type LPBOOL = *mut BOOL; +pub type LPBYTE = *mut BYTE; +pub type LPBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION; +pub type LPCSTR = *const CHAR; +pub type LPCVOID = *const c_void; +pub type LPCWSTR = *const WCHAR; +pub type LPDWORD = *mut DWORD; +pub type LPHANDLE = *mut HANDLE; +pub type LPOVERLAPPED = *mut OVERLAPPED; +pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION; +pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; +pub type LPSTARTUPINFO = *mut STARTUPINFO; +pub type LPVOID = *mut c_void; +pub type LPWCH = *mut WCHAR; +pub type LPWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW; +pub type LPWSADATA = *mut WSADATA; +pub type LPWSANETWORKEVENTS = *mut WSANETWORKEVENTS; +pub type LPWSAPROTOCOLCHAIN = *mut WSAPROTOCOLCHAIN; +pub type LPWSAPROTOCOL_INFO = *mut WSAPROTOCOL_INFO; +pub type LPWSTR = *mut WCHAR; + +pub type PCONDITION_VARIABLE = *mut CONDITION_VARIABLE; +pub type PLARGE_INTEGER = *mut c_longlong; +pub type PSRWLOCK = *mut SRWLOCK; + +pub type SOCKET = ::os::windows::raw::SOCKET; +pub type socklen_t = c_int; +pub type ADDRESS_FAMILY = USHORT; + +pub const TRUE: BOOL = 1; +pub const FALSE: BOOL = 0; + +pub const FILE_ATTRIBUTE_READONLY: DWORD = 0x1; +pub const FILE_ATTRIBUTE_DIRECTORY: DWORD = 0x10; +pub const FILE_ATTRIBUTE_NORMAL: DWORD = 0x80; +pub const FILE_ATTRIBUTE_REPARSE_POINT: DWORD = 0x400; +pub const FILE_SHARE_DELETE: DWORD = 0x4; +pub const FILE_SHARE_READ: DWORD = 0x1; +pub const FILE_SHARE_WRITE: DWORD = 0x2; +pub const CREATE_ALWAYS: DWORD = 2; +pub const CREATE_NEW: DWORD = 1; +pub const OPEN_ALWAYS: DWORD = 4; +pub const OPEN_EXISTING: DWORD = 3; +pub const TRUNCATE_EXISTING: DWORD = 5; +pub const FILE_APPEND_DATA: DWORD = 0x00000004; +pub const FILE_READ_DATA: DWORD = 0x00000001; +pub const FILE_WRITE_DATA: DWORD = 0x00000002; +pub const STANDARD_RIGHTS_READ: DWORD = 0x20000; +pub const STANDARD_RIGHTS_WRITE: DWORD = 0x20000; +pub const FILE_WRITE_EA: DWORD = 0x00000010; +pub const FILE_READ_EA: DWORD = 0x00000008; +pub const SYNCHRONIZE: DWORD = 0x00100000; +pub const FILE_WRITE_ATTRIBUTES: DWORD = 0x00000100; +pub const FILE_READ_ATTRIBUTES: DWORD = 0x00000080; +pub const FILE_GENERIC_READ: DWORD = STANDARD_RIGHTS_READ | FILE_READ_DATA | + FILE_READ_ATTRIBUTES | + FILE_READ_EA | + SYNCHRONIZE; +pub const FILE_GENERIC_WRITE: DWORD = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | + FILE_WRITE_ATTRIBUTES | + FILE_WRITE_EA | + FILE_APPEND_DATA | + SYNCHRONIZE; + +#[repr(C)] +#[derive(Copy)] +pub struct WIN32_FIND_DATAW { + pub dwFileAttributes: DWORD, + pub ftCreationTime: FILETIME, + pub ftLastAccessTime: FILETIME, + pub ftLastWriteTime: FILETIME, + pub nFileSizeHigh: DWORD, + pub nFileSizeLow: DWORD, + pub dwReserved0: DWORD, + pub dwReserved1: DWORD, + pub cFileName: [wchar_t; 260], // #define MAX_PATH 260 + pub cAlternateFileName: [wchar_t; 14], +} +impl Clone for WIN32_FIND_DATAW { + fn clone(&self) -> Self { *self } +} + +pub const FIONBIO: c_long = 0x8004667e; pub const FD_SETSIZE: usize = 64; -pub const MSG_DONTWAIT: libc::c_int = 0; -pub const ERROR_ENVVAR_NOT_FOUND: libc::c_int = 203; -pub const ERROR_ILLEGAL_CHARACTER: libc::c_int = 582; -pub const ENABLE_ECHO_INPUT: libc::DWORD = 0x4; -pub const ENABLE_EXTENDED_FLAGS: libc::DWORD = 0x80; -pub const ENABLE_INSERT_MODE: libc::DWORD = 0x20; -pub const ENABLE_LINE_INPUT: libc::DWORD = 0x2; -pub const ENABLE_PROCESSED_INPUT: libc::DWORD = 0x1; -pub const ENABLE_QUICK_EDIT_MODE: libc::DWORD = 0x40; -pub const WSA_INVALID_EVENT: WSAEVENT = 0 as WSAEVENT; +pub const MSG_DONTWAIT: c_int = 0; +pub const ENABLE_ECHO_INPUT: DWORD = 0x4; +pub const ENABLE_EXTENDED_FLAGS: DWORD = 0x80; +pub const ENABLE_INSERT_MODE: DWORD = 0x20; +pub const ENABLE_LINE_INPUT: DWORD = 0x2; +pub const ENABLE_PROCESSED_INPUT: DWORD = 0x1; +pub const ENABLE_QUICK_EDIT_MODE: DWORD = 0x40; -pub const FD_ACCEPT: libc::c_long = 0x08; +pub const FD_ACCEPT: c_long = 0x08; pub const FD_MAX_EVENTS: usize = 10; -pub const WSA_INFINITE: libc::DWORD = libc::INFINITE; -pub const WSA_WAIT_TIMEOUT: libc::DWORD = libc::consts::os::extra::WAIT_TIMEOUT; -pub const WSA_WAIT_EVENT_0: libc::DWORD = libc::consts::os::extra::WAIT_OBJECT_0; -pub const WSA_WAIT_FAILED: libc::DWORD = libc::consts::os::extra::WAIT_FAILED; -pub const WSAESHUTDOWN: libc::c_int = 10058; -pub const WSA_FLAG_OVERLAPPED: libc::DWORD = 0x01; -pub const WSA_FLAG_NO_HANDLE_INHERIT: libc::DWORD = 0x80; - -pub const ERROR_NO_MORE_FILES: libc::DWORD = 18; -pub const TOKEN_READ: libc::DWORD = 0x20008; -pub const FILE_FLAG_OPEN_REPARSE_POINT: libc::DWORD = 0x00200000; -pub const FILE_FLAG_BACKUP_SEMANTICS: libc::DWORD = 0x02000000; + +pub const WSA_INVALID_EVENT: WSAEVENT = 0 as WSAEVENT; +pub const WSA_INFINITE: DWORD = INFINITE; +pub const WSA_WAIT_TIMEOUT: DWORD = WAIT_TIMEOUT; +pub const WSA_WAIT_EVENT_0: DWORD = WAIT_OBJECT_0; +pub const WSA_WAIT_FAILED: DWORD = WAIT_FAILED; +pub const WSA_FLAG_OVERLAPPED: DWORD = 0x01; +pub const WSA_FLAG_NO_HANDLE_INHERIT: DWORD = 0x80; + +pub const WSADESCRIPTION_LEN: usize = 256; +pub const WSASYS_STATUS_LEN: usize = 128; +pub const WSAPROTOCOL_LEN: DWORD = 255; +pub const INVALID_SOCKET: SOCKET = !0; + +pub const WSAEINTR: c_int = 10004; +pub const WSAEBADF: c_int = 10009; +pub const WSAEACCES: c_int = 10013; +pub const WSAEFAULT: c_int = 10014; +pub const WSAEINVAL: c_int = 10022; +pub const WSAEMFILE: c_int = 10024; +pub const WSAEWOULDBLOCK: c_int = 10035; +pub const WSAEINPROGRESS: c_int = 10036; +pub const WSAEALREADY: c_int = 10037; +pub const WSAENOTSOCK: c_int = 10038; +pub const WSAEDESTADDRREQ: c_int = 10039; +pub const WSAEMSGSIZE: c_int = 10040; +pub const WSAEPROTOTYPE: c_int = 10041; +pub const WSAENOPROTOOPT: c_int = 10042; +pub const WSAEPROTONOSUPPORT: c_int = 10043; +pub const WSAESOCKTNOSUPPORT: c_int = 10044; +pub const WSAEOPNOTSUPP: c_int = 10045; +pub const WSAEPFNOSUPPORT: c_int = 10046; +pub const WSAEAFNOSUPPORT: c_int = 10047; +pub const WSAEADDRINUSE: c_int = 10048; +pub const WSAEADDRNOTAVAIL: c_int = 10049; +pub const WSAENETDOWN: c_int = 10050; +pub const WSAENETUNREACH: c_int = 10051; +pub const WSAENETRESET: c_int = 10052; +pub const WSAECONNABORTED: c_int = 10053; +pub const WSAECONNRESET: c_int = 10054; +pub const WSAENOBUFS: c_int = 10055; +pub const WSAEISCONN: c_int = 10056; +pub const WSAENOTCONN: c_int = 10057; +pub const WSAESHUTDOWN: c_int = 10058; +pub const WSAETOOMANYREFS: c_int = 10059; +pub const WSAETIMEDOUT: c_int = 10060; +pub const WSAECONNREFUSED: c_int = 10061; +pub const WSAELOOP: c_int = 10062; +pub const WSAENAMETOOLONG: c_int = 10063; +pub const WSAEHOSTDOWN: c_int = 10064; +pub const WSAEHOSTUNREACH: c_int = 10065; +pub const WSAENOTEMPTY: c_int = 10066; +pub const WSAEPROCLIM: c_int = 10067; +pub const WSAEUSERS: c_int = 10068; +pub const WSAEDQUOT: c_int = 10069; +pub const WSAESTALE: c_int = 10070; +pub const WSAEREMOTE: c_int = 10071; +pub const WSASYSNOTREADY: c_int = 10091; +pub const WSAVERNOTSUPPORTED: c_int = 10092; +pub const WSANOTINITIALISED: c_int = 10093; +pub const WSAEDISCON: c_int = 10101; +pub const WSAENOMORE: c_int = 10102; +pub const WSAECANCELLED: c_int = 10103; +pub const WSAEINVALIDPROCTABLE: c_int = 10104; +pub const NI_MAXHOST: DWORD = 1025; + +pub const MAX_PROTOCOL_CHAIN: DWORD = 7; + +pub const TOKEN_READ: DWORD = 0x20008; +pub const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000; +pub const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000; pub const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024; -pub const FSCTL_GET_REPARSE_POINT: libc::DWORD = 0x900a8; -pub const IO_REPARSE_TAG_SYMLINK: libc::DWORD = 0xa000000c; -pub const IO_REPARSE_TAG_MOUNT_POINT: libc::DWORD = 0xa0000003; -pub const FSCTL_SET_REPARSE_POINT: libc::DWORD = 0x900a4; -pub const FSCTL_DELETE_REPARSE_POINT: libc::DWORD = 0x900ac; +pub const FSCTL_GET_REPARSE_POINT: DWORD = 0x900a8; +pub const IO_REPARSE_TAG_SYMLINK: DWORD = 0xa000000c; +pub const IO_REPARSE_TAG_MOUNT_POINT: DWORD = 0xa0000003; +pub const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4; +pub const FSCTL_DELETE_REPARSE_POINT: DWORD = 0x900ac; -pub const SYMBOLIC_LINK_FLAG_DIRECTORY: libc::DWORD = 0x1; +pub const SYMBOLIC_LINK_FLAG_DIRECTORY: DWORD = 0x1; // Note that these are not actually HANDLEs, just values to pass to GetStdHandle -pub const STD_INPUT_HANDLE: libc::DWORD = -10i32 as libc::DWORD; -pub const STD_OUTPUT_HANDLE: libc::DWORD = -11i32 as libc::DWORD; -pub const STD_ERROR_HANDLE: libc::DWORD = -12i32 as libc::DWORD; +pub const STD_INPUT_HANDLE: DWORD = -10i32 as DWORD; +pub const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD; +pub const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD; + +pub const HANDLE_FLAG_INHERIT: DWORD = 0x00000001; + +pub const PROGRESS_CONTINUE: DWORD = 0; +pub const PROGRESS_CANCEL: DWORD = 1; +pub const PROGRESS_STOP: DWORD = 2; +pub const PROGRESS_QUIET: DWORD = 3; + +pub const TOKEN_ADJUST_PRIVILEGES: DWORD = 0x0020; +pub const SE_PRIVILEGE_ENABLED: DWORD = 2; + -pub const HANDLE_FLAG_INHERIT: libc::DWORD = 0x00000001; +pub const ERROR_SUCCESS: DWORD = 0; +pub const ERROR_INVALID_FUNCTION: DWORD = 1; +pub const ERROR_FILE_NOT_FOUND: DWORD = 2; +pub const ERROR_PATH_NOT_FOUND: DWORD = 3; +pub const ERROR_ACCESS_DENIED: DWORD = 5; +pub const ERROR_INVALID_HANDLE: DWORD = 6; +pub const ERROR_NO_MORE_FILES: DWORD = 18; +pub const ERROR_BROKEN_PIPE: DWORD = 109; +pub const ERROR_DISK_FULL: DWORD = 112; +pub const ERROR_CALL_NOT_IMPLEMENTED: DWORD = 120; +pub const ERROR_INSUFFICIENT_BUFFER: DWORD = 122; +pub const ERROR_INVALID_NAME: DWORD = 123; +pub const ERROR_ALREADY_EXISTS: DWORD = 183; +pub const ERROR_PIPE_BUSY: DWORD = 231; +pub const ERROR_NO_DATA: DWORD = 232; +pub const ERROR_INVALID_ADDRESS: DWORD = 487; +pub const ERROR_PIPE_CONNECTED: DWORD = 535; +pub const ERROR_ILLEGAL_CHARACTER: DWORD = 582; +pub const ERROR_ENVVAR_NOT_FOUND: DWORD = 203; +pub const ERROR_NOTHING_TO_TERMINATE: DWORD = 758; +pub const ERROR_OPERATION_ABORTED: DWORD = 995; +pub const ERROR_IO_PENDING: DWORD = 997; +pub const ERROR_FILE_INVALID: DWORD = 1006; +pub const ERROR_NOT_FOUND: DWORD = 1168; +pub const ERROR_TIMEOUT: DWORD = 0x5B4; + +pub const INVALID_HANDLE_VALUE: HANDLE = !0 as HANDLE; + +pub const FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000; +pub const FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200; + +pub const TLS_OUT_OF_INDEXES: DWORD = 0xFFFFFFFF; + +pub const DLL_THREAD_DETACH: DWORD = 3; +pub const DLL_PROCESS_DETACH: DWORD = 0; + +pub const INFINITE: DWORD = !0; + +pub const DUPLICATE_SAME_ACCESS: DWORD = 0x00000002; + +pub const CONDITION_VARIABLE_INIT: CONDITION_VARIABLE = CONDITION_VARIABLE { + ptr: ptr::null_mut(), +}; +pub const SRWLOCK_INIT: SRWLOCK = SRWLOCK { ptr: ptr::null_mut() }; -pub const PROGRESS_CONTINUE: libc::DWORD = 0; -pub const PROGRESS_CANCEL: libc::DWORD = 1; -pub const PROGRESS_STOP: libc::DWORD = 2; -pub const PROGRESS_QUIET: libc::DWORD = 3; +pub const STILL_ACTIVE: DWORD = 259; -pub const TOKEN_ADJUST_PRIVILEGES: libc::DWORD = 0x0020; -pub const SE_PRIVILEGE_ENABLED: libc::DWORD = 2; +pub const DETACHED_PROCESS: DWORD = 0x00000008; +pub const CREATE_NEW_PROCESS_GROUP: DWORD = 0x00000200; +pub const CREATE_UNICODE_ENVIRONMENT: DWORD = 0x00000400; +pub const STARTF_USESTDHANDLES: DWORD = 0x00000100; + +pub const AF_INET: c_int = 2; +pub const AF_INET6: c_int = 23; +pub const SD_BOTH: c_int = 2; +pub const SD_RECEIVE: c_int = 0; +pub const SD_SEND: c_int = 1; +pub const SOCK_DGRAM: c_int = 2; +pub const SOCK_STREAM: c_int = 1; +pub const SOL_SOCKET: c_int = 0xffff; +pub const SO_RCVTIMEO: c_int = 0x1006; +pub const SO_SNDTIMEO: c_int = 0x1005; +pub const SO_REUSEADDR: c_int = 0x0004; + +pub const VOLUME_NAME_DOS: DWORD = 0x0; +pub const MOVEFILE_REPLACE_EXISTING: DWORD = 1; + +pub const FILE_BEGIN: DWORD = 0; +pub const FILE_CURRENT: DWORD = 1; +pub const FILE_END: DWORD = 2; + +pub const WAIT_ABANDONED: DWORD = 0x00000080; +pub const WAIT_OBJECT_0: DWORD = 0x00000000; +pub const WAIT_TIMEOUT: DWORD = 0x00000102; +pub const WAIT_FAILED: DWORD = !0; + +pub const MAX_SYM_NAME: usize = 2000; +pub const IMAGE_FILE_MACHINE_I386: DWORD = 0x014c; +pub const IMAGE_FILE_MACHINE_IA64: DWORD = 0x0200; +pub const IMAGE_FILE_MACHINE_AMD64: DWORD = 0x8664; + +pub const PROV_RSA_FULL: DWORD = 1; +pub const CRYPT_SILENT: DWORD = 64; +pub const CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000; pub const EXCEPTION_CONTINUE_SEARCH: LONG = 0; -pub const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15; pub const EXCEPTION_STACK_OVERFLOW: DWORD = 0xc00000fd; - -pub const ERROR_PATH_NOT_FOUND: libc::c_int = 3; +pub const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15; +pub const EXCEPTION_NONCONTINUABLE: DWORD = 0x1; // Noncontinuable exception +pub const EXCEPTION_UNWINDING: DWORD = 0x2; // Unwind is in progress +pub const EXCEPTION_EXIT_UNWIND: DWORD = 0x4; // Exit unwind is in progress +pub const EXCEPTION_STACK_INVALID: DWORD = 0x8; // Stack out of limits or unaligned +pub const EXCEPTION_NESTED_CALL: DWORD = 0x10; // Nested exception handler call +pub const EXCEPTION_TARGET_UNWIND: DWORD = 0x20; // Target unwind in progress +pub const EXCEPTION_COLLIDED_UNWIND: DWORD = 0x40; // Collided exception handler call +pub const EXCEPTION_UNWIND: DWORD = EXCEPTION_UNWINDING | + EXCEPTION_EXIT_UNWIND | + EXCEPTION_TARGET_UNWIND | + EXCEPTION_COLLIDED_UNWIND; #[repr(C)] #[cfg(target_arch = "x86")] pub struct WSADATA { - pub wVersion: libc::WORD, - pub wHighVersion: libc::WORD, + pub wVersion: WORD, + pub wHighVersion: WORD, pub szDescription: [u8; WSADESCRIPTION_LEN + 1], pub szSystemStatus: [u8; WSASYS_STATUS_LEN + 1], pub iMaxSockets: u16, @@ -100,8 +349,8 @@ pub struct WSADATA { #[repr(C)] #[cfg(target_arch = "x86_64")] pub struct WSADATA { - pub wVersion: libc::WORD, - pub wHighVersion: libc::WORD, + pub wVersion: WORD, + pub wHighVersion: WORD, pub iMaxSockets: u16, pub iMaxUdpDg: u16, pub lpVendorInfo: *mut u8, @@ -109,56 +358,50 @@ pub struct WSADATA { pub szSystemStatus: [u8; WSASYS_STATUS_LEN + 1], } -pub type LPWSADATA = *mut WSADATA; - #[repr(C)] pub struct WSANETWORKEVENTS { - pub lNetworkEvents: libc::c_long, - pub iErrorCode: [libc::c_int; FD_MAX_EVENTS], + pub lNetworkEvents: c_long, + pub iErrorCode: [c_int; FD_MAX_EVENTS], } -pub type LPWSANETWORKEVENTS = *mut WSANETWORKEVENTS; - -pub type WSAEVENT = libc::HANDLE; +pub type WSAEVENT = HANDLE; #[repr(C)] pub struct WSAPROTOCOL_INFO { - pub dwServiceFlags1: libc::DWORD, - pub dwServiceFlags2: libc::DWORD, - pub dwServiceFlags3: libc::DWORD, - pub dwServiceFlags4: libc::DWORD, - pub dwProviderFlags: libc::DWORD, + pub dwServiceFlags1: DWORD, + pub dwServiceFlags2: DWORD, + pub dwServiceFlags3: DWORD, + pub dwServiceFlags4: DWORD, + pub dwProviderFlags: DWORD, pub ProviderId: GUID, - pub dwCatalogEntryId: libc::DWORD, + pub dwCatalogEntryId: DWORD, pub ProtocolChain: WSAPROTOCOLCHAIN, - pub iVersion: libc::c_int, - pub iAddressFamily: libc::c_int, - pub iMaxSockAddr: libc::c_int, - pub iMinSockAddr: libc::c_int, - pub iSocketType: libc::c_int, - pub iProtocol: libc::c_int, - pub iProtocolMaxOffset: libc::c_int, - pub iNetworkByteOrder: libc::c_int, - pub iSecurityScheme: libc::c_int, - pub dwMessageSize: libc::DWORD, - pub dwProviderReserved: libc::DWORD, + pub iVersion: c_int, + pub iAddressFamily: c_int, + pub iMaxSockAddr: c_int, + pub iMinSockAddr: c_int, + pub iSocketType: c_int, + pub iProtocol: c_int, + pub iProtocolMaxOffset: c_int, + pub iNetworkByteOrder: c_int, + pub iSecurityScheme: c_int, + pub dwMessageSize: DWORD, + pub dwProviderReserved: DWORD, pub szProtocol: [u16; (WSAPROTOCOL_LEN as usize) + 1], } -pub type LPWSAPROTOCOL_INFO = *mut WSAPROTOCOL_INFO; - #[repr(C)] pub struct fd_set { - fd_count: libc::c_uint, - fd_array: [libc::SOCKET; FD_SETSIZE], + fd_count: c_uint, + fd_array: [SOCKET; FD_SETSIZE], } -pub fn fd_set(set: &mut fd_set, s: libc::SOCKET) { +pub fn fd_set(set: &mut fd_set, s: SOCKET) { set.fd_array[set.fd_count as usize] = s; set.fd_count += 1; } -pub type SHORT = libc::c_short; +pub type SHORT = c_short; #[repr(C)] pub struct COORD { @@ -178,39 +421,37 @@ pub struct SMALL_RECT { pub struct CONSOLE_SCREEN_BUFFER_INFO { pub dwSize: COORD, pub dwCursorPosition: COORD, - pub wAttributes: libc::WORD, + pub wAttributes: WORD, pub srWindow: SMALL_RECT, pub dwMaximumWindowSize: COORD, } pub type PCONSOLE_SCREEN_BUFFER_INFO = *mut CONSOLE_SCREEN_BUFFER_INFO; #[repr(C)] -#[derive(Clone)] +#[derive(Copy, Clone)] pub struct WIN32_FILE_ATTRIBUTE_DATA { - pub dwFileAttributes: libc::DWORD, - pub ftCreationTime: libc::FILETIME, - pub ftLastAccessTime: libc::FILETIME, - pub ftLastWriteTime: libc::FILETIME, - pub nFileSizeHigh: libc::DWORD, - pub nFileSizeLow: libc::DWORD, + pub dwFileAttributes: DWORD, + pub ftCreationTime: FILETIME, + pub ftLastAccessTime: FILETIME, + pub ftLastWriteTime: FILETIME, + pub nFileSizeHigh: DWORD, + pub nFileSizeLow: DWORD, } #[repr(C)] pub struct BY_HANDLE_FILE_INFORMATION { - pub dwFileAttributes: libc::DWORD, - pub ftCreationTime: libc::FILETIME, - pub ftLastAccessTime: libc::FILETIME, - pub ftLastWriteTime: libc::FILETIME, - pub dwVolumeSerialNumber: libc::DWORD, - pub nFileSizeHigh: libc::DWORD, - pub nFileSizeLow: libc::DWORD, - pub nNumberOfLinks: libc::DWORD, - pub nFileIndexHigh: libc::DWORD, - pub nFileIndexLow: libc::DWORD, + pub dwFileAttributes: DWORD, + pub ftCreationTime: FILETIME, + pub ftLastAccessTime: FILETIME, + pub ftLastWriteTime: FILETIME, + pub dwVolumeSerialNumber: DWORD, + pub nFileSizeHigh: DWORD, + pub nFileSizeLow: DWORD, + pub nNumberOfLinks: DWORD, + pub nFileIndexHigh: DWORD, + pub nFileIndexLow: DWORD, } -pub type LPBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION; - #[repr(C)] pub enum GET_FILEEX_INFO_LEVELS { GetFileExInfoStandard, @@ -245,38 +486,32 @@ pub enum FILE_INFO_BY_HANDLE_CLASS { #[repr(C)] pub struct FILE_END_OF_FILE_INFO { - pub EndOfFile: libc::LARGE_INTEGER, + pub EndOfFile: LARGE_INTEGER, } #[repr(C)] pub struct REPARSE_DATA_BUFFER { - pub ReparseTag: libc::c_uint, - pub ReparseDataLength: libc::c_ushort, - pub Reserved: libc::c_ushort, + pub ReparseTag: c_uint, + pub ReparseDataLength: c_ushort, + pub Reserved: c_ushort, pub rest: (), } #[repr(C)] pub struct SYMBOLIC_LINK_REPARSE_BUFFER { - pub SubstituteNameOffset: libc::c_ushort, - pub SubstituteNameLength: libc::c_ushort, - pub PrintNameOffset: libc::c_ushort, - pub PrintNameLength: libc::c_ushort, - pub Flags: libc::c_ulong, - pub PathBuffer: libc::WCHAR, + pub SubstituteNameOffset: c_ushort, + pub SubstituteNameLength: c_ushort, + pub PrintNameOffset: c_ushort, + pub PrintNameLength: c_ushort, + pub Flags: c_ulong, + pub PathBuffer: WCHAR, } -pub type PCONDITION_VARIABLE = *mut CONDITION_VARIABLE; -pub type PSRWLOCK = *mut SRWLOCK; -pub type ULONG = c_ulong; -pub type ULONG_PTR = c_ulong; -pub type LPBOOL = *mut BOOL; - pub type LPPROGRESS_ROUTINE = ::option::Option<unsafe extern "system" fn( - TotalFileSize: libc::LARGE_INTEGER, - TotalBytesTransferred: libc::LARGE_INTEGER, - StreamSize: libc::LARGE_INTEGER, - StreamBytesTransferred: libc::LARGE_INTEGER, + TotalFileSize: LARGE_INTEGER, + TotalBytesTransferred: LARGE_INTEGER, + StreamSize: LARGE_INTEGER, + StreamBytesTransferred: LARGE_INTEGER, dwStreamNumber: DWORD, dwCallbackReason: DWORD, hSourceFile: HANDLE, @@ -298,22 +533,17 @@ pub struct CRITICAL_SECTION { SpinCount: ULONG_PTR } -pub const CONDITION_VARIABLE_INIT: CONDITION_VARIABLE = CONDITION_VARIABLE { - ptr: ptr::null_mut(), -}; -pub const SRWLOCK_INIT: SRWLOCK = SRWLOCK { ptr: ptr::null_mut() }; - #[repr(C)] pub struct LUID { - pub LowPart: libc::DWORD, - pub HighPart: libc::c_long, + pub LowPart: DWORD, + pub HighPart: c_long, } pub type PLUID = *mut LUID; #[repr(C)] pub struct TOKEN_PRIVILEGES { - pub PrivilegeCount: libc::DWORD, + pub PrivilegeCount: DWORD, pub Privileges: [LUID_AND_ATTRIBUTES; 1], } @@ -322,18 +552,18 @@ pub type PTOKEN_PRIVILEGES = *mut TOKEN_PRIVILEGES; #[repr(C)] pub struct LUID_AND_ATTRIBUTES { pub Luid: LUID, - pub Attributes: libc::DWORD, + pub Attributes: DWORD, } #[repr(C)] pub struct REPARSE_MOUNTPOINT_DATA_BUFFER { - pub ReparseTag: libc::DWORD, - pub ReparseDataLength: libc::DWORD, - pub Reserved: libc::WORD, - pub ReparseTargetLength: libc::WORD, - pub ReparseTargetMaximumLength: libc::WORD, - pub Reserved1: libc::WORD, - pub ReparseTarget: libc::WCHAR, + pub ReparseTag: DWORD, + pub ReparseDataLength: DWORD, + pub Reserved: WORD, + pub ReparseTargetLength: WORD, + pub ReparseTargetMaximumLength: WORD, + pub Reserved1: WORD, + pub ReparseTarget: WCHAR, } #[repr(C)] @@ -349,70 +579,383 @@ pub struct EXCEPTION_RECORD { #[repr(C)] pub struct EXCEPTION_POINTERS { pub ExceptionRecord: *mut EXCEPTION_RECORD, - pub ContextRecord: LPVOID + pub ContextRecord: *mut CONTEXT, } pub type PVECTORED_EXCEPTION_HANDLER = extern "system" fn(ExceptionInfo: *mut EXCEPTION_POINTERS) -> LONG; +#[repr(C)] +pub struct GUID { + pub Data1: DWORD, + pub Data2: WORD, + pub Data3: WORD, + pub Data4: [BYTE; 8], +} + +#[repr(C)] +pub struct WSAPROTOCOLCHAIN { + pub ChainLen: c_int, + pub ChainEntries: [DWORD; MAX_PROTOCOL_CHAIN as usize], +} + +#[repr(C)] +pub struct SECURITY_ATTRIBUTES { + pub nLength: DWORD, + pub lpSecurityDescriptor: LPVOID, + pub bInheritHandle: BOOL, +} + +#[repr(C)] +pub struct PROCESS_INFORMATION { + pub hProcess: HANDLE, + pub hThread: HANDLE, + pub dwProcessId: DWORD, + pub dwThreadId: DWORD, +} + +#[repr(C)] +pub struct STARTUPINFO { + pub cb: DWORD, + pub lpReserved: LPWSTR, + pub lpDesktop: LPWSTR, + pub lpTitle: LPWSTR, + pub dwX: DWORD, + pub dwY: DWORD, + pub dwXSize: DWORD, + pub dwYSize: DWORD, + pub dwXCountChars: DWORD, + pub dwYCountCharts: DWORD, + pub dwFillAttribute: DWORD, + pub dwFlags: DWORD, + pub wShowWindow: WORD, + pub cbReserved2: WORD, + pub lpReserved2: LPBYTE, + pub hStdInput: HANDLE, + pub hStdOutput: HANDLE, + pub hStdError: HANDLE, +} + +#[repr(C)] +pub struct SOCKADDR { + pub sa_family: ADDRESS_FAMILY, + pub sa_data: [CHAR; 14], +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct FILETIME { + pub dwLowDateTime: DWORD, + pub dwHighDateTime: DWORD, +} + +#[repr(C)] +pub struct OVERLAPPED { + pub Internal: *mut c_ulong, + pub InternalHigh: *mut c_ulong, + pub Offset: DWORD, + pub OffsetHigh: DWORD, + pub hEvent: HANDLE, +} + +#[repr(C)] +pub struct SYMBOL_INFO { + pub SizeOfStruct: c_ulong, + pub TypeIndex: c_ulong, + pub Reserved: [u64; 2], + pub Index: c_ulong, + pub Size: c_ulong, + pub ModBase: u64, + pub Flags: c_ulong, + pub Value: u64, + pub Address: u64, + pub Register: c_ulong, + pub Scope: c_ulong, + pub Tag: c_ulong, + pub NameLen: c_ulong, + pub MaxNameLen: c_ulong, + // note that windows has this as 1, but it basically just means that + // the name is inline at the end of the struct. For us, we just bump + // the struct size up to MAX_SYM_NAME. + pub Name: [c_char; MAX_SYM_NAME], +} + +#[repr(C)] +pub struct IMAGEHLP_LINE64 { + pub SizeOfStruct: u32, + pub Key: *const c_void, + pub LineNumber: u32, + pub Filename: *const c_char, + pub Address: u64, +} + +#[repr(C)] +pub enum ADDRESS_MODE { + AddrMode1616, + AddrMode1632, + AddrModeReal, + AddrModeFlat, +} + +#[repr(C)] +pub struct ADDRESS64 { + pub Offset: u64, + pub Segment: u16, + pub Mode: ADDRESS_MODE, +} + +#[repr(C)] +pub struct STACKFRAME64 { + pub AddrPC: ADDRESS64, + pub AddrReturn: ADDRESS64, + pub AddrFrame: ADDRESS64, + pub AddrStack: ADDRESS64, + pub AddrBStore: ADDRESS64, + pub FuncTableEntry: *mut c_void, + pub Params: [u64; 4], + pub Far: BOOL, + pub Virtual: BOOL, + pub Reserved: [u64; 3], + pub KdHelp: KDHELP64, +} + +#[repr(C)] +pub struct KDHELP64 { + pub Thread: u64, + pub ThCallbackStack: DWORD, + pub ThCallbackBStore: DWORD, + pub NextCallback: DWORD, + pub FramePointer: DWORD, + pub KiCallUserMode: u64, + pub KeUserCallbackDispatcher: u64, + pub SystemRangeStart: u64, + pub KiUserExceptionDispatcher: u64, + pub StackBase: u64, + pub StackLimit: u64, + pub Reserved: [u64; 5], +} + +#[cfg(target_arch = "x86")] +#[repr(C)] +pub struct CONTEXT { + pub ContextFlags: DWORD, + pub Dr0: DWORD, + pub Dr1: DWORD, + pub Dr2: DWORD, + pub Dr3: DWORD, + pub Dr6: DWORD, + pub Dr7: DWORD, + pub FloatSave: FLOATING_SAVE_AREA, + pub SegGs: DWORD, + pub SegFs: DWORD, + pub SegEs: DWORD, + pub SegDs: DWORD, + pub Edi: DWORD, + pub Esi: DWORD, + pub Ebx: DWORD, + pub Edx: DWORD, + pub Ecx: DWORD, + pub Eax: DWORD, + pub Ebp: DWORD, + pub Eip: DWORD, + pub SegCs: DWORD, + pub EFlags: DWORD, + pub Esp: DWORD, + pub SegSs: DWORD, + pub ExtendedRegisters: [u8; 512], +} + +#[cfg(target_arch = "x86")] +#[repr(C)] +pub struct FLOATING_SAVE_AREA { + pub ControlWord: DWORD, + pub StatusWord: DWORD, + pub TagWord: DWORD, + pub ErrorOffset: DWORD, + pub ErrorSelector: DWORD, + pub DataOffset: DWORD, + pub DataSelector: DWORD, + pub RegisterArea: [u8; 80], + pub Cr0NpxState: DWORD, +} + +#[cfg(target_arch = "x86_64")] +#[repr(C)] +pub struct CONTEXT { + _align_hack: [simd::u64x2; 0], // FIXME align on 16-byte + pub P1Home: DWORDLONG, + pub P2Home: DWORDLONG, + pub P3Home: DWORDLONG, + pub P4Home: DWORDLONG, + pub P5Home: DWORDLONG, + pub P6Home: DWORDLONG, + + pub ContextFlags: DWORD, + pub MxCsr: DWORD, + + pub SegCs: WORD, + pub SegDs: WORD, + pub SegEs: WORD, + pub SegFs: WORD, + pub SegGs: WORD, + pub SegSs: WORD, + pub EFlags: DWORD, + + pub Dr0: DWORDLONG, + pub Dr1: DWORDLONG, + pub Dr2: DWORDLONG, + pub Dr3: DWORDLONG, + pub Dr6: DWORDLONG, + pub Dr7: DWORDLONG, + + pub Rax: DWORDLONG, + pub Rcx: DWORDLONG, + pub Rdx: DWORDLONG, + pub Rbx: DWORDLONG, + pub Rsp: DWORDLONG, + pub Rbp: DWORDLONG, + pub Rsi: DWORDLONG, + pub Rdi: DWORDLONG, + pub R8: DWORDLONG, + pub R9: DWORDLONG, + pub R10: DWORDLONG, + pub R11: DWORDLONG, + pub R12: DWORDLONG, + pub R13: DWORDLONG, + pub R14: DWORDLONG, + pub R15: DWORDLONG, + + pub Rip: DWORDLONG, + + pub FltSave: FLOATING_SAVE_AREA, + + pub VectorRegister: [M128A; 26], + pub VectorControl: DWORDLONG, + + pub DebugControl: DWORDLONG, + pub LastBranchToRip: DWORDLONG, + pub LastBranchFromRip: DWORDLONG, + pub LastExceptionToRip: DWORDLONG, + pub LastExceptionFromRip: DWORDLONG, +} + +#[cfg(target_arch = "x86_64")] +#[repr(C)] +pub struct M128A { + _align_hack: [simd::u64x2; 0], // FIXME align on 16-byte + pub Low: c_ulonglong, + pub High: c_longlong +} + +#[cfg(target_arch = "x86_64")] +#[repr(C)] +pub struct FLOATING_SAVE_AREA { + _align_hack: [simd::u64x2; 0], // FIXME align on 16-byte + _Dummy: [u8; 512] // FIXME: Fill this out +} + +#[repr(C)] +pub struct SOCKADDR_STORAGE_LH { + pub ss_family: ADDRESS_FAMILY, + pub __ss_pad1: [CHAR; 6], + pub __ss_align: i64, + pub __ss_pad2: [CHAR; 112], +} + +#[repr(C)] +pub struct ADDRINFOA { + pub ai_flags: c_int, + pub ai_family: c_int, + pub ai_socktype: c_int, + pub ai_protocol: c_int, + pub ai_addrlen: size_t, + pub ai_canonname: *mut c_char, + pub ai_addr: *mut SOCKADDR, + pub ai_next: *mut ADDRINFOA, +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct sockaddr_in { + pub sin_family: ADDRESS_FAMILY, + pub sin_port: USHORT, + pub sin_addr: in_addr, + pub sin_zero: [CHAR; 8], +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct sockaddr_in6 { + pub sin6_family: ADDRESS_FAMILY, + pub sin6_port: USHORT, + pub sin6_flowinfo: c_ulong, + pub sin6_addr: in6_addr, + pub sin6_scope_id: c_ulong, +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct in_addr { + pub s_addr: u32, +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct in6_addr { + pub s6_addr: [u8; 16], +} + +pub enum UNWIND_HISTORY_TABLE {} + +#[repr(C)] +pub struct RUNTIME_FUNCTION { + pub BeginAddress: DWORD, + pub EndAddress: DWORD, + pub UnwindData: DWORD, +} + +#[repr(C)] +pub struct DISPATCHER_CONTEXT { + pub ControlPc: LPVOID, + pub ImageBase: LPVOID, + pub FunctionEntry: *const RUNTIME_FUNCTION, + pub EstablisherFrame: LPVOID, + pub TargetIp: LPVOID, + pub ContextRecord: *const CONTEXT, + pub LanguageHandler: LPVOID, + pub HandlerData: *const u8, + pub HistoryTable: *const UNWIND_HISTORY_TABLE, +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub enum EXCEPTION_DISPOSITION { + ExceptionContinueExecution, + ExceptionContinueSearch, + ExceptionNestedException, + ExceptionCollidedUnwind +} + #[link(name = "ws2_32")] #[link(name = "userenv")] #[link(name = "shell32")] +#[link(name = "advapi32")] extern "system" { - pub fn WSAStartup(wVersionRequested: libc::WORD, - lpWSAData: LPWSADATA) -> libc::c_int; - pub fn WSACleanup() -> libc::c_int; - pub fn WSAGetLastError() -> libc::c_int; - pub fn WSACloseEvent(hEvent: WSAEVENT) -> libc::BOOL; - pub fn WSACreateEvent() -> WSAEVENT; - pub fn WSAEventSelect(s: libc::SOCKET, - hEventObject: WSAEVENT, - lNetworkEvents: libc::c_long) -> libc::c_int; - pub fn WSASetEvent(hEvent: WSAEVENT) -> libc::BOOL; - pub fn WSAWaitForMultipleEvents(cEvents: libc::DWORD, - lphEvents: *const WSAEVENT, - fWaitAll: libc::BOOL, - dwTimeout: libc::DWORD, - fAltertable: libc::BOOL) -> libc::DWORD; - pub fn WSAEnumNetworkEvents(s: libc::SOCKET, - hEventObject: WSAEVENT, - lpNetworkEvents: LPWSANETWORKEVENTS) - -> libc::c_int; - pub fn WSADuplicateSocketW(s: libc::SOCKET, - dwProcessId: libc::DWORD, + pub fn WSAStartup(wVersionRequested: WORD, + lpWSAData: LPWSADATA) -> c_int; + pub fn WSACleanup() -> c_int; + pub fn WSAGetLastError() -> c_int; + pub fn WSADuplicateSocketW(s: SOCKET, + dwProcessId: DWORD, lpProtocolInfo: LPWSAPROTOCOL_INFO) - -> libc::c_int; - pub fn GetCurrentProcessId() -> libc::DWORD; - pub fn WSASocketW(af: libc::c_int, - kind: libc::c_int, - protocol: libc::c_int, + -> c_int; + pub fn GetCurrentProcessId() -> DWORD; + pub fn WSASocketW(af: c_int, + kind: c_int, + protocol: c_int, lpProtocolInfo: LPWSAPROTOCOL_INFO, g: GROUP, - dwFlags: libc::DWORD) -> libc::SOCKET; - - pub fn ioctlsocket(s: libc::SOCKET, cmd: libc::c_long, - argp: *mut libc::c_ulong) -> libc::c_int; - pub fn select(nfds: libc::c_int, - readfds: *mut fd_set, - writefds: *mut fd_set, - exceptfds: *mut fd_set, - timeout: *mut libc::timeval) -> libc::c_int; - pub fn getsockopt(sockfd: libc::SOCKET, - level: libc::c_int, - optname: libc::c_int, - optval: *mut libc::c_char, - optlen: *mut libc::c_int) -> libc::c_int; - - pub fn SetEvent(hEvent: libc::HANDLE) -> libc::BOOL; - pub fn WaitForMultipleObjects(nCount: libc::DWORD, - lpHandles: *const libc::HANDLE, - bWaitAll: libc::BOOL, - dwMilliseconds: libc::DWORD) -> libc::DWORD; - - pub fn CancelIo(hFile: libc::HANDLE) -> libc::BOOL; - pub fn CancelIoEx(hFile: libc::HANDLE, - lpOverlapped: libc::LPOVERLAPPED) -> libc::BOOL; - + dwFlags: DWORD) -> SOCKET; pub fn InitializeCriticalSection(CriticalSection: *mut CRITICAL_SECTION); pub fn EnterCriticalSection(CriticalSection: *mut CRITICAL_SECTION); pub fn TryEnterCriticalSection(CriticalSection: *mut CRITICAL_SECTION) -> BOOLEAN; @@ -420,104 +963,274 @@ extern "system" { pub fn DeleteCriticalSection(CriticalSection: *mut CRITICAL_SECTION); // FIXME - pInputControl should be PCONSOLE_READCONSOLE_CONTROL - pub fn ReadConsoleW(hConsoleInput: libc::HANDLE, - lpBuffer: libc::LPVOID, - nNumberOfCharsToRead: libc::DWORD, - lpNumberOfCharsRead: libc::LPDWORD, - pInputControl: libc::LPVOID) -> libc::BOOL; - - pub fn WriteConsoleW(hConsoleOutput: libc::HANDLE, - lpBuffer: libc::types::os::arch::extra::LPCVOID, - nNumberOfCharsToWrite: libc::DWORD, - lpNumberOfCharsWritten: libc::LPDWORD, - lpReserved: libc::LPVOID) -> libc::BOOL; - - pub fn GetConsoleMode(hConsoleHandle: libc::HANDLE, - lpMode: libc::LPDWORD) -> libc::BOOL; - - pub fn SetConsoleMode(hConsoleHandle: libc::HANDLE, - lpMode: libc::DWORD) -> libc::BOOL; - pub fn GetConsoleScreenBufferInfo( - hConsoleOutput: libc::HANDLE, - lpConsoleScreenBufferInfo: PCONSOLE_SCREEN_BUFFER_INFO, - ) -> libc::BOOL; - - pub fn GetFileAttributesExW(lpFileName: libc::LPCWSTR, + pub fn ReadConsoleW(hConsoleInput: HANDLE, + lpBuffer: LPVOID, + nNumberOfCharsToRead: DWORD, + lpNumberOfCharsRead: LPDWORD, + pInputControl: LPVOID) -> BOOL; + + pub fn WriteConsoleW(hConsoleOutput: HANDLE, + lpBuffer: LPCVOID, + nNumberOfCharsToWrite: DWORD, + lpNumberOfCharsWritten: LPDWORD, + lpReserved: LPVOID) -> BOOL; + + pub fn GetConsoleMode(hConsoleHandle: HANDLE, + lpMode: LPDWORD) -> BOOL; + pub fn GetFileAttributesExW(lpFileName: LPCWSTR, fInfoLevelId: GET_FILEEX_INFO_LEVELS, - lpFileInformation: libc::LPVOID) -> libc::BOOL; - pub fn RemoveDirectoryW(lpPathName: libc::LPCWSTR) -> libc::BOOL; - pub fn SetFileAttributesW(lpFileName: libc::LPCWSTR, - dwFileAttributes: libc::DWORD) -> libc::BOOL; - pub fn GetFileAttributesW(lpFileName: libc::LPCWSTR) -> libc::DWORD; - pub fn GetFileInformationByHandle(hFile: libc::HANDLE, + lpFileInformation: LPVOID) -> BOOL; + pub fn RemoveDirectoryW(lpPathName: LPCWSTR) -> BOOL; + pub fn SetFileAttributesW(lpFileName: LPCWSTR, + dwFileAttributes: DWORD) -> BOOL; + pub fn GetFileInformationByHandle(hFile: HANDLE, lpFileInformation: LPBY_HANDLE_FILE_INFORMATION) - -> libc::BOOL; - - pub fn SetLastError(dwErrCode: libc::DWORD); - pub fn GetCommandLineW() -> *mut libc::LPCWSTR; - pub fn LocalFree(ptr: *mut libc::c_void); - pub fn CommandLineToArgvW(lpCmdLine: *mut libc::LPCWSTR, - pNumArgs: *mut libc::c_int) -> *mut *mut u16; - pub fn SetFileTime(hFile: libc::HANDLE, - lpCreationTime: *const libc::FILETIME, - lpLastAccessTime: *const libc::FILETIME, - lpLastWriteTime: *const libc::FILETIME) -> libc::BOOL; - pub fn GetTempPathW(nBufferLength: libc::DWORD, - lpBuffer: libc::LPCWSTR) -> libc::DWORD; - pub fn OpenProcessToken(ProcessHandle: libc::HANDLE, - DesiredAccess: libc::DWORD, - TokenHandle: *mut libc::HANDLE) -> libc::BOOL; - pub fn GetCurrentProcess() -> libc::HANDLE; - pub fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE; - pub fn ExitProcess(uExitCode: libc::c_uint) -> !; - pub fn DeviceIoControl(hDevice: libc::HANDLE, - dwIoControlCode: libc::DWORD, - lpInBuffer: libc::LPVOID, - nInBufferSize: libc::DWORD, - lpOutBuffer: libc::LPVOID, - nOutBufferSize: libc::DWORD, - lpBytesReturned: libc::LPDWORD, - lpOverlapped: libc::LPOVERLAPPED) -> libc::BOOL; - pub fn CreatePipe(hReadPipe: libc::LPHANDLE, - hWritePipe: libc::LPHANDLE, - lpPipeAttributes: libc::LPSECURITY_ATTRIBUTES, - nSize: libc::DWORD) -> libc::BOOL; - pub fn CreateThread(lpThreadAttributes: libc::LPSECURITY_ATTRIBUTES, - dwStackSize: libc::SIZE_T, - lpStartAddress: extern "system" fn(*mut libc::c_void) - -> libc::DWORD, - lpParameter: libc::LPVOID, - dwCreationFlags: libc::DWORD, - lpThreadId: libc::LPDWORD) -> libc::HANDLE; - pub fn WaitForSingleObject(hHandle: libc::HANDLE, - dwMilliseconds: libc::DWORD) -> libc::DWORD; - pub fn SwitchToThread() -> libc::BOOL; - pub fn Sleep(dwMilliseconds: libc::DWORD); - pub fn GetProcessId(handle: libc::HANDLE) -> libc::DWORD; - pub fn GetUserProfileDirectoryW(hToken: libc::HANDLE, - lpProfileDir: libc::LPCWSTR, - lpcchSize: *mut libc::DWORD) -> libc::BOOL; - pub fn SetHandleInformation(hObject: libc::HANDLE, - dwMask: libc::DWORD, - dwFlags: libc::DWORD) -> libc::BOOL; - pub fn CopyFileExW(lpExistingFileName: libc::LPCWSTR, - lpNewFileName: libc::LPCWSTR, + -> BOOL; + + pub fn SetLastError(dwErrCode: DWORD); + pub fn GetCommandLineW() -> *mut LPCWSTR; + pub fn LocalFree(ptr: *mut c_void); + pub fn CommandLineToArgvW(lpCmdLine: *mut LPCWSTR, + pNumArgs: *mut c_int) -> *mut *mut u16; + pub fn GetTempPathW(nBufferLength: DWORD, + lpBuffer: LPCWSTR) -> DWORD; + pub fn OpenProcessToken(ProcessHandle: HANDLE, + DesiredAccess: DWORD, + TokenHandle: *mut HANDLE) -> BOOL; + pub fn GetCurrentProcess() -> HANDLE; + pub fn GetCurrentThread() -> HANDLE; + pub fn GetStdHandle(which: DWORD) -> HANDLE; + pub fn ExitProcess(uExitCode: c_uint) -> !; + pub fn DeviceIoControl(hDevice: HANDLE, + dwIoControlCode: DWORD, + lpInBuffer: LPVOID, + nInBufferSize: DWORD, + lpOutBuffer: LPVOID, + nOutBufferSize: DWORD, + lpBytesReturned: LPDWORD, + lpOverlapped: LPOVERLAPPED) -> BOOL; + pub fn CreatePipe(hReadPipe: LPHANDLE, + hWritePipe: LPHANDLE, + lpPipeAttributes: LPSECURITY_ATTRIBUTES, + nSize: DWORD) -> BOOL; + pub fn CreateThread(lpThreadAttributes: LPSECURITY_ATTRIBUTES, + dwStackSize: SIZE_T, + lpStartAddress: extern "system" fn(*mut c_void) + -> DWORD, + lpParameter: LPVOID, + dwCreationFlags: DWORD, + lpThreadId: LPDWORD) -> HANDLE; + pub fn WaitForSingleObject(hHandle: HANDLE, + dwMilliseconds: DWORD) -> DWORD; + pub fn SwitchToThread() -> BOOL; + pub fn Sleep(dwMilliseconds: DWORD); + pub fn GetProcessId(handle: HANDLE) -> DWORD; + pub fn GetUserProfileDirectoryW(hToken: HANDLE, + lpProfileDir: LPCWSTR, + lpcchSize: *mut DWORD) -> BOOL; + pub fn SetHandleInformation(hObject: HANDLE, + dwMask: DWORD, + dwFlags: DWORD) -> BOOL; + pub fn CopyFileExW(lpExistingFileName: LPCWSTR, + lpNewFileName: LPCWSTR, lpProgressRoutine: LPPROGRESS_ROUTINE, - lpData: libc::LPVOID, + lpData: LPVOID, pbCancel: LPBOOL, - dwCopyFlags: libc::DWORD) -> libc::BOOL; - pub fn LookupPrivilegeValueW(lpSystemName: libc::LPCWSTR, - lpName: libc::LPCWSTR, - lpLuid: PLUID) -> libc::BOOL; - pub fn AdjustTokenPrivileges(TokenHandle: libc::HANDLE, - DisableAllPrivileges: libc::BOOL, + dwCopyFlags: DWORD) -> BOOL; + pub fn LookupPrivilegeValueW(lpSystemName: LPCWSTR, + lpName: LPCWSTR, + lpLuid: PLUID) -> BOOL; + pub fn AdjustTokenPrivileges(TokenHandle: HANDLE, + DisableAllPrivileges: BOOL, NewState: PTOKEN_PRIVILEGES, - BufferLength: libc::DWORD, + BufferLength: DWORD, PreviousState: PTOKEN_PRIVILEGES, - ReturnLength: *mut libc::DWORD) -> libc::BOOL; + ReturnLength: *mut DWORD) -> BOOL; pub fn AddVectoredExceptionHandler(FirstHandler: ULONG, VectoredHandler: PVECTORED_EXCEPTION_HANDLER) -> LPVOID; + pub fn FormatMessageW(flags: DWORD, + lpSrc: LPVOID, + msgId: DWORD, + langId: DWORD, + buf: LPWSTR, + nsize: DWORD, + args: *const c_void) + -> DWORD; + pub fn TlsAlloc() -> DWORD; + pub fn TlsFree(dwTlsIndex: DWORD) -> BOOL; + pub fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID; + pub fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL; + pub fn GetLastError() -> DWORD; + pub fn QueryPerformanceFrequency(lpFrequency: *mut LARGE_INTEGER) -> BOOL; + pub fn QueryPerformanceCounter(lpPerformanceCount: *mut LARGE_INTEGER) + -> BOOL; + pub fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: LPDWORD) -> BOOL; + pub fn TerminateProcess(hProcess: HANDLE, uExitCode: UINT) -> BOOL; + pub fn CreateProcessW(lpApplicationName: LPCWSTR, + lpCommandLine: LPWSTR, + lpProcessAttributes: LPSECURITY_ATTRIBUTES, + lpThreadAttributes: LPSECURITY_ATTRIBUTES, + bInheritHandles: BOOL, + dwCreationFlags: DWORD, + lpEnvironment: LPVOID, + lpCurrentDirectory: LPCWSTR, + lpStartupInfo: LPSTARTUPINFO, + lpProcessInformation: LPPROCESS_INFORMATION) + -> BOOL; + pub fn GetEnvironmentVariableW(n: LPCWSTR, v: LPWSTR, nsize: DWORD) -> DWORD; + pub fn SetEnvironmentVariableW(n: LPCWSTR, v: LPCWSTR) -> BOOL; + pub fn GetEnvironmentStringsW() -> LPWCH; + pub fn FreeEnvironmentStringsW(env_ptr: LPWCH) -> BOOL; + pub fn GetModuleFileNameW(hModule: HMODULE, + lpFilename: LPWSTR, + nSize: DWORD) + -> DWORD; + pub fn CreateDirectoryW(lpPathName: LPCWSTR, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES) + -> BOOL; + pub fn DeleteFileW(lpPathName: LPCWSTR) -> BOOL; + pub fn GetCurrentDirectoryW(nBufferLength: DWORD, lpBuffer: LPWSTR) -> DWORD; + pub fn SetCurrentDirectoryW(lpPathName: LPCWSTR) -> BOOL; + + pub fn closesocket(socket: SOCKET) -> c_int; + pub fn recv(socket: SOCKET, buf: *mut c_void, len: c_int, + flags: c_int) -> c_int; + pub fn send(socket: SOCKET, buf: *const c_void, len: c_int, + flags: c_int) -> c_int; + pub fn recvfrom(socket: SOCKET, + buf: *mut c_void, + len: c_int, + flags: c_int, + addr: *mut SOCKADDR, + addrlen: *mut c_int) + -> c_int; + pub fn sendto(socket: SOCKET, + buf: *const c_void, + len: c_int, + flags: c_int, + addr: *const SOCKADDR, + addrlen: c_int) + -> c_int; + pub fn shutdown(socket: SOCKET, how: c_int) -> c_int; + pub fn accept(socket: SOCKET, + address: *mut SOCKADDR, + address_len: *mut c_int) + -> SOCKET; + pub fn DuplicateHandle(hSourceProcessHandle: HANDLE, + hSourceHandle: HANDLE, + hTargetProcessHandle: HANDLE, + lpTargetHandle: LPHANDLE, + dwDesiredAccess: DWORD, + bInheritHandle: BOOL, + dwOptions: DWORD) + -> BOOL; + pub fn ReadFile(hFile: HANDLE, + lpBuffer: LPVOID, + nNumberOfBytesToRead: DWORD, + lpNumberOfBytesRead: LPDWORD, + lpOverlapped: LPOVERLAPPED) + -> BOOL; + pub fn WriteFile(hFile: HANDLE, + lpBuffer: LPVOID, + nNumberOfBytesToWrite: DWORD, + lpNumberOfBytesWritten: LPDWORD, + lpOverlapped: LPOVERLAPPED) + -> BOOL; + pub fn CloseHandle(hObject: HANDLE) -> BOOL; + pub fn CreateHardLinkW(lpSymlinkFileName: LPCWSTR, + lpTargetFileName: LPCWSTR, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES) + -> BOOL; + pub fn MoveFileExW(lpExistingFileName: LPCWSTR, + lpNewFileName: LPCWSTR, + dwFlags: DWORD) + -> BOOL; + pub fn SetFilePointerEx(hFile: HANDLE, + liDistanceToMove: LARGE_INTEGER, + lpNewFilePointer: PLARGE_INTEGER, + dwMoveMethod: DWORD) + -> BOOL; + pub fn FlushFileBuffers(hFile: HANDLE) -> BOOL; + pub fn CreateFileW(lpFileName: LPCWSTR, + dwDesiredAccess: DWORD, + dwShareMode: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + dwCreationDisposition: DWORD, + dwFlagsAndAttributes: DWORD, + hTemplateFile: HANDLE) + -> HANDLE; + + pub fn FindFirstFileW(fileName: LPCWSTR, + findFileData: LPWIN32_FIND_DATAW) + -> HANDLE; + pub fn FindNextFileW(findFile: HANDLE, findFileData: LPWIN32_FIND_DATAW) + -> BOOL; + pub fn FindClose(findFile: HANDLE) -> BOOL; + pub fn RtlCaptureContext(ctx: *mut CONTEXT); + pub fn getsockopt(s: SOCKET, + level: c_int, + optname: c_int, + optval: *mut c_char, + optlen: *mut c_int) + -> c_int; + pub fn setsockopt(s: SOCKET, + level: c_int, + optname: c_int, + optval: *const c_void, + optlen: c_int) + -> c_int; + pub fn getsockname(socket: SOCKET, + address: *mut SOCKADDR, + address_len: *mut c_int) + -> c_int; + pub fn getpeername(socket: SOCKET, + address: *mut SOCKADDR, + address_len: *mut c_int) + -> c_int; + pub fn bind(socket: SOCKET, address: *const SOCKADDR, + address_len: socklen_t) -> c_int; + pub fn listen(socket: SOCKET, backlog: c_int) -> c_int; + pub fn connect(socket: SOCKET, address: *const SOCKADDR, len: c_int) + -> c_int; + pub fn getaddrinfo(node: *const c_char, service: *const c_char, + hints: *const ADDRINFOA, + res: *mut *mut ADDRINFOA) -> c_int; + pub fn freeaddrinfo(res: *mut ADDRINFOA); + pub fn getnameinfo(sa: *const SOCKADDR, salen: c_int, + host: *mut c_char, hostlen: DWORD, + serv: *mut c_char, servlen: DWORD, + flags: c_int) -> c_int; + + pub fn LoadLibraryW(name: LPCWSTR) -> HMODULE; + pub fn GetModuleHandleExW(dwFlags: DWORD, name: LPCWSTR, + handle: *mut HMODULE) -> BOOL; + pub fn GetProcAddress(handle: HMODULE, + name: LPCSTR) -> *mut c_void; + pub fn FreeLibrary(handle: HMODULE) -> BOOL; + pub fn SetErrorMode(uMode: c_uint) -> c_uint; + pub fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE; + pub fn CryptAcquireContextA(phProv: *mut HCRYPTPROV, + pszContainer: LPCSTR, + pszProvider: LPCSTR, + dwProvType: DWORD, + dwFlags: DWORD) -> BOOL; + pub fn CryptGenRandom(hProv: HCRYPTPROV, + dwLen: DWORD, + pbBuffer: *mut BYTE) -> BOOL; + pub fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL; + + #[unwind] + pub fn RaiseException(dwExceptionCode: DWORD, + dwExceptionFlags: DWORD, + nNumberOfArguments: DWORD, + lpArguments: *const ULONG_PTR); + pub fn RtlUnwindEx(TargetFrame: LPVOID, + TargetIp: LPVOID, + ExceptionRecord: *const EXCEPTION_RECORD, + ReturnValue: LPVOID, + OriginalContext: *const CONTEXT, + HistoryTable: *const UNWIND_HISTORY_TABLE); } // Functions that aren't available on Windows XP, but we still use them and just diff --git a/src/libstd/sys/windows/compat.rs b/src/libstd/sys/windows/compat.rs index 3a03b91f24e..780a0d9427d 100644 --- a/src/libstd/sys/windows/compat.rs +++ b/src/libstd/sys/windows/compat.rs @@ -24,21 +24,16 @@ use prelude::v1::*; use ffi::CString; -use libc::{LPVOID, LPCWSTR, HMODULE, LPCSTR}; use sync::atomic::{AtomicUsize, Ordering}; - -extern "system" { - fn GetModuleHandleW(lpModuleName: LPCWSTR) -> HMODULE; - fn GetProcAddress(hModule: HMODULE, lpProcName: LPCSTR) -> LPVOID; -} +use sys::c; pub fn lookup(module: &str, symbol: &str) -> Option<usize> { let mut module: Vec<u16> = module.utf16_units().collect(); module.push(0); let symbol = CString::new(symbol).unwrap(); unsafe { - let handle = GetModuleHandleW(module.as_ptr()); - match GetProcAddress(handle, symbol.as_ptr()) as usize { + let handle = c::GetModuleHandleW(module.as_ptr()); + match c::GetProcAddress(handle, symbol.as_ptr()) as usize { 0 => None, n => Some(n), } diff --git a/src/libstd/sys/windows/condvar.rs b/src/libstd/sys/windows/condvar.rs index ac76479d7db..8075374d42b 100644 --- a/src/libstd/sys/windows/condvar.rs +++ b/src/libstd/sys/windows/condvar.rs @@ -9,7 +9,6 @@ // except according to those terms. use cell::UnsafeCell; -use libc::{self, DWORD}; use sys::c; use sys::mutex::{self, Mutex}; use sys::os; @@ -29,7 +28,7 @@ impl Condvar { pub unsafe fn wait(&self, mutex: &Mutex) { let r = c::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), - libc::INFINITE, + c::INFINITE, 0); debug_assert!(r != 0); } @@ -40,8 +39,7 @@ impl Condvar { super::dur2timeout(dur), 0); if r == 0 { - const ERROR_TIMEOUT: DWORD = 0x5B4; - debug_assert_eq!(os::errno() as usize, ERROR_TIMEOUT as usize); + debug_assert_eq!(os::errno() as usize, c::ERROR_TIMEOUT as usize); false } else { true diff --git a/src/libstd/sys/windows/ext/io.rs b/src/libstd/sys/windows/ext/io.rs index 9f10b0e8563..2ddb6c65fd3 100644 --- a/src/libstd/sys/windows/ext/io.rs +++ b/src/libstd/sys/windows/ext/io.rs @@ -15,6 +15,7 @@ use os::windows::raw; use net; use sys_common::{self, AsInner, FromInner, IntoInner}; use sys; +use sys::c; /// Raw HANDLEs. #[stable(feature = "rust1", since = "1.0.0")] @@ -73,7 +74,7 @@ impl AsRawHandle for fs::File { #[stable(feature = "from_raw_os", since = "1.1.0")] impl FromRawHandle for fs::File { unsafe fn from_raw_handle(handle: RawHandle) -> fs::File { - let handle = handle as ::libc::HANDLE; + let handle = handle as c::HANDLE; fs::File::from_inner(sys::fs::File::from_inner(handle)) } } diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index fb2456564eb..0b0e1a1ece7 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -14,7 +14,6 @@ use os::windows::prelude::*; use ffi::OsString; use fmt; use io::{self, Error, SeekFrom}; -use libc::{self, HANDLE}; use mem; use path::{Path, PathBuf}; use ptr; @@ -30,7 +29,7 @@ pub struct File { handle: Handle } #[derive(Clone)] pub struct FileAttr { data: c::WIN32_FILE_ATTRIBUTE_DATA, - reparse_tag: libc::DWORD, + reparse_tag: c::DWORD, } #[derive(Copy, Clone, PartialEq, Eq, Hash)] @@ -41,17 +40,17 @@ pub enum FileType { pub struct ReadDir { handle: FindNextFileHandle, root: Arc<PathBuf>, - first: Option<libc::WIN32_FIND_DATAW>, + first: Option<c::WIN32_FIND_DATAW>, } -struct FindNextFileHandle(libc::HANDLE); +struct FindNextFileHandle(c::HANDLE); unsafe impl Send for FindNextFileHandle {} unsafe impl Sync for FindNextFileHandle {} pub struct DirEntry { root: Arc<PathBuf>, - data: libc::WIN32_FIND_DATAW, + data: c::WIN32_FIND_DATAW, } #[derive(Clone, Default)] @@ -61,15 +60,15 @@ pub struct OpenOptions { read: bool, write: bool, truncate: bool, - desired_access: Option<libc::DWORD>, - share_mode: Option<libc::DWORD>, - creation_disposition: Option<libc::DWORD>, - flags_and_attributes: Option<libc::DWORD>, + desired_access: Option<c::DWORD>, + share_mode: Option<c::DWORD>, + creation_disposition: Option<c::DWORD>, + flags_and_attributes: Option<c::DWORD>, security_attributes: usize, // *mut T doesn't have a Default impl } #[derive(Clone, PartialEq, Eq, Debug)] -pub struct FilePermissions { attrs: libc::DWORD } +pub struct FilePermissions { attrs: c::DWORD } pub struct DirBuilder; @@ -84,9 +83,8 @@ impl Iterator for ReadDir { unsafe { let mut wfd = mem::zeroed(); loop { - if libc::FindNextFileW(self.handle.0, &mut wfd) == 0 { - if libc::GetLastError() == - c::ERROR_NO_MORE_FILES as libc::DWORD { + if c::FindNextFileW(self.handle.0, &mut wfd) == 0 { + if c::GetLastError() == c::ERROR_NO_MORE_FILES { return None } else { return Some(Err(Error::last_os_error())) @@ -102,13 +100,13 @@ impl Iterator for ReadDir { impl Drop for FindNextFileHandle { fn drop(&mut self) { - let r = unsafe { libc::FindClose(self.0) }; + let r = unsafe { c::FindClose(self.0) }; debug_assert!(r != 0); } } impl DirEntry { - fn new(root: &Arc<PathBuf>, wfd: &libc::WIN32_FIND_DATAW) -> Option<DirEntry> { + fn new(root: &Arc<PathBuf>, wfd: &c::WIN32_FIND_DATAW) -> Option<DirEntry> { match &wfd.cFileName[0..3] { // check for '.' and '..' [46, 0, ..] | @@ -170,50 +168,50 @@ impl OpenOptions { pub fn share_mode(&mut self, val: u32) { self.share_mode = Some(val); } - pub fn security_attributes(&mut self, attrs: libc::LPSECURITY_ATTRIBUTES) { + pub fn security_attributes(&mut self, attrs: c::LPSECURITY_ATTRIBUTES) { self.security_attributes = attrs as usize; } - fn get_desired_access(&self) -> libc::DWORD { + fn get_desired_access(&self) -> c::DWORD { self.desired_access.unwrap_or({ - let mut base = if self.read {libc::FILE_GENERIC_READ} else {0} | - if self.write {libc::FILE_GENERIC_WRITE} else {0}; + let mut base = if self.read {c::FILE_GENERIC_READ} else {0} | + if self.write {c::FILE_GENERIC_WRITE} else {0}; if self.append { - base &= !libc::FILE_WRITE_DATA; - base |= libc::FILE_APPEND_DATA; + base &= !c::FILE_WRITE_DATA; + base |= c::FILE_APPEND_DATA; } base }) } - fn get_share_mode(&self) -> libc::DWORD { + fn get_share_mode(&self) -> c::DWORD { // libuv has a good comment about this, but the basic idea is that // we try to emulate unix semantics by enabling all sharing by // allowing things such as deleting a file while it's still open. - self.share_mode.unwrap_or(libc::FILE_SHARE_READ | - libc::FILE_SHARE_WRITE | - libc::FILE_SHARE_DELETE) + self.share_mode.unwrap_or(c::FILE_SHARE_READ | + c::FILE_SHARE_WRITE | + c::FILE_SHARE_DELETE) } - fn get_creation_disposition(&self) -> libc::DWORD { + fn get_creation_disposition(&self) -> c::DWORD { self.creation_disposition.unwrap_or({ match (self.create, self.truncate) { - (true, true) => libc::CREATE_ALWAYS, - (true, false) => libc::OPEN_ALWAYS, - (false, false) => libc::OPEN_EXISTING, + (true, true) => c::CREATE_ALWAYS, + (true, false) => c::OPEN_ALWAYS, + (false, false) => c::OPEN_EXISTING, (false, true) => { if self.write && !self.append { - libc::CREATE_ALWAYS + c::CREATE_ALWAYS } else { - libc::TRUNCATE_EXISTING + c::TRUNCATE_EXISTING } } } }) } - fn get_flags_and_attributes(&self) -> libc::DWORD { - self.flags_and_attributes.unwrap_or(libc::FILE_ATTRIBUTE_NORMAL) + fn get_flags_and_attributes(&self) -> c::DWORD { + self.flags_and_attributes.unwrap_or(c::FILE_ATTRIBUTE_NORMAL) } } @@ -230,15 +228,15 @@ impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let path = to_utf16(path); let handle = unsafe { - libc::CreateFileW(path.as_ptr(), - opts.get_desired_access(), - opts.get_share_mode(), - opts.security_attributes as *mut _, - opts.get_creation_disposition(), - opts.get_flags_and_attributes(), - ptr::null_mut()) + c::CreateFileW(path.as_ptr(), + opts.get_desired_access(), + opts.get_share_mode(), + opts.security_attributes as *mut _, + opts.get_creation_disposition(), + opts.get_flags_and_attributes(), + ptr::null_mut()) }; - if handle == libc::INVALID_HANDLE_VALUE { + if handle == c::INVALID_HANDLE_VALUE { Err(Error::last_os_error()) } else { Ok(File { handle: Handle::new(handle) }) @@ -246,7 +244,7 @@ impl File { } pub fn fsync(&self) -> io::Result<()> { - try!(cvt(unsafe { libc::FlushFileBuffers(self.handle.raw()) })); + try!(cvt(unsafe { c::FlushFileBuffers(self.handle.raw()) })); Ok(()) } @@ -254,14 +252,14 @@ impl File { pub fn truncate(&self, size: u64) -> io::Result<()> { let mut info = c::FILE_END_OF_FILE_INFO { - EndOfFile: size as libc::LARGE_INTEGER, + EndOfFile: size as c::LARGE_INTEGER, }; let size = mem::size_of_val(&info); try!(cvt(unsafe { c::SetFileInformationByHandle(self.handle.raw(), c::FileEndOfFileInfo, &mut info as *mut _ as *mut _, - size as libc::DWORD) + size as c::DWORD) })); Ok(()) } @@ -304,15 +302,15 @@ impl File { pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> { let (whence, pos) = match pos { - SeekFrom::Start(n) => (libc::FILE_BEGIN, n as i64), - SeekFrom::End(n) => (libc::FILE_END, n), - SeekFrom::Current(n) => (libc::FILE_CURRENT, n), + SeekFrom::Start(n) => (c::FILE_BEGIN, n as i64), + SeekFrom::End(n) => (c::FILE_END, n), + SeekFrom::Current(n) => (c::FILE_CURRENT, n), }; - let pos = pos as libc::LARGE_INTEGER; + let pos = pos as c::LARGE_INTEGER; let mut newpos = 0; try!(cvt(unsafe { - libc::SetFilePointerEx(self.handle.raw(), pos, - &mut newpos, whence) + c::SetFilePointerEx(self.handle.raw(), pos, + &mut newpos, whence) })); Ok(newpos as u64) } @@ -323,7 +321,7 @@ impl File { fn reparse_point<'a>(&self, space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE]) - -> io::Result<(libc::DWORD, &'a c::REPARSE_DATA_BUFFER)> { + -> io::Result<(c::DWORD, &'a c::REPARSE_DATA_BUFFER)> { unsafe { let mut bytes = 0; try!(cvt({ @@ -332,7 +330,7 @@ impl File { ptr::null_mut(), 0, space.as_mut_ptr() as *mut _, - space.len() as libc::DWORD, + space.len() as c::DWORD, &mut bytes, ptr::null_mut()) })); @@ -361,8 +359,8 @@ impl File { } } -impl FromInner<libc::HANDLE> for File { - fn from_inner(handle: libc::HANDLE) -> File { +impl FromInner<c::HANDLE> for File { + fn from_inner(handle: c::HANDLE) -> File { File { handle: Handle::new(handle) } } } @@ -402,12 +400,12 @@ impl FileAttr { pub fn accessed(&self) -> u64 { self.to_u64(&self.data.ftLastAccessTime) } pub fn modified(&self) -> u64 { self.to_u64(&self.data.ftLastWriteTime) } - fn to_u64(&self, ft: &libc::FILETIME) -> u64 { + fn to_u64(&self, ft: &c::FILETIME) -> u64 { (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32) } fn is_reparse_point(&self) -> bool { - self.data.dwFileAttributes & libc::FILE_ATTRIBUTE_REPARSE_POINT != 0 + self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 } } @@ -426,8 +424,8 @@ impl FilePermissions { } impl FileType { - fn new(attrs: libc::DWORD, reparse_tag: libc::DWORD) -> FileType { - if attrs & libc::FILE_ATTRIBUTE_REPARSE_POINT != 0 { + fn new(attrs: c::DWORD, reparse_tag: c::DWORD) -> FileType { + if attrs & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 { match reparse_tag { c::IO_REPARSE_TAG_SYMLINK => FileType::Symlink, c::IO_REPARSE_TAG_MOUNT_POINT => FileType::MountPoint, @@ -453,7 +451,7 @@ impl DirBuilder { pub fn mkdir(&self, p: &Path) -> io::Result<()> { let p = to_utf16(p); try!(cvt(unsafe { - libc::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) + c::CreateDirectoryW(p.as_ptr(), ptr::null_mut()) })); Ok(()) } @@ -466,8 +464,8 @@ pub fn readdir(p: &Path) -> io::Result<ReadDir> { unsafe { let mut wfd = mem::zeroed(); - let find_handle = libc::FindFirstFileW(path.as_ptr(), &mut wfd); - if find_handle != libc::INVALID_HANDLE_VALUE { + let find_handle = c::FindFirstFileW(path.as_ptr(), &mut wfd); + if find_handle != c::INVALID_HANDLE_VALUE { Ok(ReadDir { handle: FindNextFileHandle(find_handle), root: Arc::new(root), @@ -481,7 +479,7 @@ pub fn readdir(p: &Path) -> io::Result<ReadDir> { pub fn unlink(p: &Path) -> io::Result<()> { let p_utf16 = to_utf16(p); - try!(cvt(unsafe { libc::DeleteFileW(p_utf16.as_ptr()) })); + try!(cvt(unsafe { c::DeleteFileW(p_utf16.as_ptr()) })); Ok(()) } @@ -489,8 +487,7 @@ pub fn rename(old: &Path, new: &Path) -> io::Result<()> { let old = to_utf16(old); let new = to_utf16(new); try!(cvt(unsafe { - libc::MoveFileExW(old.as_ptr(), new.as_ptr(), - libc::MOVEFILE_REPLACE_EXISTING) + c::MoveFileExW(old.as_ptr(), new.as_ptr(), c::MOVEFILE_REPLACE_EXISTING) })); Ok(()) } @@ -515,7 +512,7 @@ pub fn symlink_inner(src: &Path, dst: &Path, dir: bool) -> io::Result<()> { let dst = to_utf16(dst); let flags = if dir { c::SYMBOLIC_LINK_FLAG_DIRECTORY } else { 0 }; try!(cvt(unsafe { - c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as libc::BOOL + c::CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), flags) as c::BOOL })); Ok(()) } @@ -524,7 +521,7 @@ pub fn link(src: &Path, dst: &Path) -> io::Result<()> { let src = to_utf16(src); let dst = to_utf16(dst); try!(cvt(unsafe { - libc::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut()) + c::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut()) })); Ok(()) } @@ -575,7 +572,7 @@ pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> { fn get_path(f: &File) -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { c::GetFinalPathNameByHandleW(f.handle.raw(), buf, sz, - libc::VOLUME_NAME_DOS) + c::VOLUME_NAME_DOS) }, |buf| { PathBuf::from(OsString::from_wide(buf)) }) @@ -592,16 +589,16 @@ pub fn canonicalize(p: &Path) -> io::Result<PathBuf> { pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { unsafe extern "system" fn callback( - _TotalFileSize: libc::LARGE_INTEGER, - TotalBytesTransferred: libc::LARGE_INTEGER, - _StreamSize: libc::LARGE_INTEGER, - _StreamBytesTransferred: libc::LARGE_INTEGER, - _dwStreamNumber: libc::DWORD, - _dwCallbackReason: libc::DWORD, - _hSourceFile: HANDLE, - _hDestinationFile: HANDLE, - lpData: libc::LPVOID, - ) -> libc::DWORD { + _TotalFileSize: c::LARGE_INTEGER, + TotalBytesTransferred: c::LARGE_INTEGER, + _StreamSize: c::LARGE_INTEGER, + _StreamBytesTransferred: c::LARGE_INTEGER, + _dwStreamNumber: c::DWORD, + _dwCallbackReason: c::DWORD, + _hSourceFile: c::HANDLE, + _hDestinationFile: c::HANDLE, + lpData: c::LPVOID, + ) -> c::DWORD { *(lpData as *mut i64) = TotalBytesTransferred; c::PROGRESS_CONTINUE } @@ -673,10 +670,10 @@ fn directory_junctions_are_directories() { *buf.offset(i) = 0; i += 1; (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT; - (*db).ReparseTargetMaximumLength = (i * 2) as libc::WORD; - (*db).ReparseTargetLength = ((i - 1) * 2) as libc::WORD; + (*db).ReparseTargetMaximumLength = (i * 2) as c::WORD; + (*db).ReparseTargetLength = ((i - 1) * 2) as c::WORD; (*db).ReparseDataLength = - (*db).ReparseTargetLength as libc::DWORD + 12; + (*db).ReparseTargetLength as c::DWORD + 12; let mut ret = 0; cvt(c::DeviceIoControl(h as *mut _, @@ -707,10 +704,10 @@ fn directory_junctions_are_directories() { &mut tp.Privileges[0].Luid))); tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = c::SE_PRIVILEGE_ENABLED; - let size = mem::size_of::<c::TOKEN_PRIVILEGES>() as libc::DWORD; - try!(cvt(c::AdjustTokenPrivileges(token, libc::FALSE, &mut tp, size, + let size = mem::size_of::<c::TOKEN_PRIVILEGES>() as c::DWORD; + try!(cvt(c::AdjustTokenPrivileges(token, c::FALSE, &mut tp, size, ptr::null_mut(), ptr::null_mut()))); - try!(cvt(libc::CloseHandle(token))); + try!(cvt(c::CloseHandle(token))); File::open_reparse_point(p, write) } diff --git a/src/libstd/sys/windows/handle.rs b/src/libstd/sys/windows/handle.rs index a9e9b0e2520..cb41b05daae 100644 --- a/src/libstd/sys/windows/handle.rs +++ b/src/libstd/sys/windows/handle.rs @@ -10,11 +10,10 @@ use io::ErrorKind; use io; -use libc::funcs::extra::kernel32::{GetCurrentProcess, DuplicateHandle}; -use libc::{self, HANDLE}; use mem; use ops::Deref; use ptr; +use sys::c; use sys::cvt; /// An owned container for `HANDLE` object, closing them on Drop. @@ -28,17 +27,17 @@ pub struct Handle(RawHandle); /// This does **not** drop the handle when it goes out of scope, use `Handle` /// instead for that. #[derive(Copy, Clone)] -pub struct RawHandle(HANDLE); +pub struct RawHandle(c::HANDLE); unsafe impl Send for RawHandle {} unsafe impl Sync for RawHandle {} impl Handle { - pub fn new(handle: HANDLE) -> Handle { + pub fn new(handle: c::HANDLE) -> Handle { Handle(RawHandle::new(handle)) } - pub fn into_raw(self) -> HANDLE { + pub fn into_raw(self) -> c::HANDLE { let ret = self.raw(); mem::forget(self); return ret; @@ -52,22 +51,22 @@ impl Deref for Handle { impl Drop for Handle { fn drop(&mut self) { - unsafe { let _ = libc::CloseHandle(self.raw()); } + unsafe { let _ = c::CloseHandle(self.raw()); } } } impl RawHandle { - pub fn new(handle: HANDLE) -> RawHandle { + pub fn new(handle: c::HANDLE) -> RawHandle { RawHandle(handle) } - pub fn raw(&self) -> HANDLE { self.0 } + pub fn raw(&self) -> c::HANDLE { self.0 } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { let mut read = 0; let res = cvt(unsafe { - libc::ReadFile(self.0, buf.as_ptr() as libc::LPVOID, - buf.len() as libc::DWORD, &mut read, + c::ReadFile(self.0, buf.as_ptr() as c::LPVOID, + buf.len() as c::DWORD, &mut read, ptr::null_mut()) }); @@ -87,20 +86,20 @@ impl RawHandle { pub fn write(&self, buf: &[u8]) -> io::Result<usize> { let mut amt = 0; try!(cvt(unsafe { - libc::WriteFile(self.0, buf.as_ptr() as libc::LPVOID, - buf.len() as libc::DWORD, &mut amt, + c::WriteFile(self.0, buf.as_ptr() as c::LPVOID, + buf.len() as c::DWORD, &mut amt, ptr::null_mut()) })); Ok(amt as usize) } - pub fn duplicate(&self, access: libc::DWORD, inherit: bool, - options: libc::DWORD) -> io::Result<Handle> { - let mut ret = 0 as libc::HANDLE; + pub fn duplicate(&self, access: c::DWORD, inherit: bool, + options: c::DWORD) -> io::Result<Handle> { + let mut ret = 0 as c::HANDLE; try!(cvt(unsafe { - let cur_proc = GetCurrentProcess(); - DuplicateHandle(cur_proc, self.0, cur_proc, &mut ret, - access, inherit as libc::BOOL, + let cur_proc = c::GetCurrentProcess(); + c::DuplicateHandle(cur_proc, self.0, cur_proc, &mut ret, + access, inherit as c::BOOL, options) })); Ok(Handle::new(ret)) diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index 4df3c561ab1..3f76218eafe 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -16,7 +16,6 @@ use prelude::v1::*; use ffi::{OsStr, OsString}; use io::{self, ErrorKind}; -use libc; use num::Zero; use os::windows::ffi::{OsStrExt, OsStringExt}; use path::PathBuf; @@ -46,25 +45,28 @@ pub mod stdio; pub fn init() {} pub fn decode_error_kind(errno: i32) -> ErrorKind { - match errno as libc::c_int { - libc::ERROR_ACCESS_DENIED => ErrorKind::PermissionDenied, - libc::ERROR_ALREADY_EXISTS => ErrorKind::AlreadyExists, - libc::ERROR_BROKEN_PIPE => ErrorKind::BrokenPipe, - libc::ERROR_FILE_NOT_FOUND => ErrorKind::NotFound, - c::ERROR_PATH_NOT_FOUND => ErrorKind::NotFound, - libc::ERROR_NO_DATA => ErrorKind::BrokenPipe, - libc::ERROR_OPERATION_ABORTED => ErrorKind::TimedOut, - - libc::WSAEACCES => ErrorKind::PermissionDenied, - libc::WSAEADDRINUSE => ErrorKind::AddrInUse, - libc::WSAEADDRNOTAVAIL => ErrorKind::AddrNotAvailable, - libc::WSAECONNABORTED => ErrorKind::ConnectionAborted, - libc::WSAECONNREFUSED => ErrorKind::ConnectionRefused, - libc::WSAECONNRESET => ErrorKind::ConnectionReset, - libc::WSAEINVAL => ErrorKind::InvalidInput, - libc::WSAENOTCONN => ErrorKind::NotConnected, - libc::WSAEWOULDBLOCK => ErrorKind::WouldBlock, - libc::WSAETIMEDOUT => ErrorKind::TimedOut, + match errno as c::DWORD { + c::ERROR_ACCESS_DENIED => return ErrorKind::PermissionDenied, + c::ERROR_ALREADY_EXISTS => return ErrorKind::AlreadyExists, + c::ERROR_BROKEN_PIPE => return ErrorKind::BrokenPipe, + c::ERROR_FILE_NOT_FOUND => return ErrorKind::NotFound, + c::ERROR_PATH_NOT_FOUND => return ErrorKind::NotFound, + c::ERROR_NO_DATA => return ErrorKind::BrokenPipe, + c::ERROR_OPERATION_ABORTED => return ErrorKind::TimedOut, + _ => {} + } + + match errno { + c::WSAEACCES => ErrorKind::PermissionDenied, + c::WSAEADDRINUSE => ErrorKind::AddrInUse, + c::WSAEADDRNOTAVAIL => ErrorKind::AddrNotAvailable, + c::WSAECONNABORTED => ErrorKind::ConnectionAborted, + c::WSAECONNREFUSED => ErrorKind::ConnectionRefused, + c::WSAECONNRESET => ErrorKind::ConnectionReset, + c::WSAEINVAL => ErrorKind::InvalidInput, + c::WSAENOTCONN => ErrorKind::NotConnected, + c::WSAEWOULDBLOCK => ErrorKind::WouldBlock, + c::WSAETIMEDOUT => ErrorKind::TimedOut, _ => ErrorKind::Other, } @@ -91,7 +93,7 @@ fn to_utf16_os(s: &OsStr) -> Vec<u16> { // yielded the data which has been read from the syscall. The return value // from this closure is then the return value of the function. fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> io::Result<T> - where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD, + where F1: FnMut(*mut u16, c::DWORD) -> c::DWORD, F2: FnOnce(&[u16]) -> T { // Start off with a stack buf but then spill over to the heap if we end up @@ -120,13 +122,12 @@ fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> io::Result<T> // error" is still 0 then we interpret it as a 0 length buffer and // not an actual error. c::SetLastError(0); - let k = match f1(buf.as_mut_ptr(), n as libc::DWORD) { - 0 if libc::GetLastError() == 0 => 0, + let k = match f1(buf.as_mut_ptr(), n as c::DWORD) { + 0 if c::GetLastError() == 0 => 0, 0 => return Err(io::Error::last_os_error()), n => n, } as usize; - if k == n && libc::GetLastError() == - libc::ERROR_INSUFFICIENT_BUFFER as libc::DWORD { + if k == n && c::GetLastError() == c::ERROR_INSUFFICIENT_BUFFER { n *= 2; } else if k >= n { n = k; @@ -157,7 +158,7 @@ fn cvt<I: PartialEq + Zero>(i: I) -> io::Result<I> { } } -fn dur2timeout(dur: Duration) -> libc::DWORD { +fn dur2timeout(dur: Duration) -> c::DWORD { // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the // timeouts in windows APIs are typically u32 milliseconds. To translate, we // have two pieces to take care of: @@ -170,10 +171,10 @@ fn dur2timeout(dur: Duration) -> libc::DWORD { }).and_then(|ms| { ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 {1} else {0}) }).map(|ms| { - if ms > <libc::DWORD>::max_value() as u64 { - libc::INFINITE + if ms > <c::DWORD>::max_value() as u64 { + c::INFINITE } else { - ms as libc::DWORD + ms as c::DWORD } - }).unwrap_or(libc::INFINITE) + }).unwrap_or(c::INFINITE) } diff --git a/src/libstd/sys/windows/net.rs b/src/libstd/sys/windows/net.rs index 998b4fcb1a1..3e69902dcb6 100644 --- a/src/libstd/sys/windows/net.rs +++ b/src/libstd/sys/windows/net.rs @@ -9,23 +9,30 @@ // except according to those terms. use io; -use libc::consts::os::extra::INVALID_SOCKET; -use libc::{self, c_int, c_void}; +use libc::{c_int, c_void}; use mem; -use net::SocketAddr; +use net::{SocketAddr, Shutdown}; use num::One; use ops::Neg; use ptr; use sync::Once; -use sys; use sys::c; +use sys; use sys_common::{self, AsInner, FromInner, IntoInner}; -use sys_common::net::{setsockopt, getsockopt}; +use sys_common::net; use time::Duration; pub type wrlen_t = i32; -pub struct Socket(libc::SOCKET); +pub mod netc { + pub use sys::c::*; + pub use sys::c::SOCKADDR as sockaddr; + pub use sys::c::SOCKADDR_STORAGE_LH as sockaddr_storage; + pub use sys::c::ADDRINFOA as addrinfo; + pub use sys::c::ADDRESS_FAMILY as sa_family_t; +} + +pub struct Socket(c::SOCKET); /// Checks whether the Windows socket interface has been started already, and /// if not, starts it. @@ -76,13 +83,13 @@ pub fn cvt_r<T, F>(mut f: F) -> io::Result<T> impl Socket { pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> { let fam = match *addr { - SocketAddr::V4(..) => libc::AF_INET, - SocketAddr::V6(..) => libc::AF_INET6, + SocketAddr::V4(..) => c::AF_INET, + SocketAddr::V6(..) => c::AF_INET6, }; let socket = try!(unsafe { match c::WSASocketW(fam, ty, 0, ptr::null_mut(), 0, c::WSA_FLAG_OVERLAPPED) { - INVALID_SOCKET => Err(last_error()), + c::INVALID_SOCKET => Err(last_error()), n => Ok(Socket(n)), } }); @@ -90,11 +97,11 @@ impl Socket { Ok(socket) } - pub fn accept(&self, storage: *mut libc::sockaddr, - len: *mut libc::socklen_t) -> io::Result<Socket> { + pub fn accept(&self, storage: *mut c::SOCKADDR, + len: *mut c_int) -> io::Result<Socket> { let socket = try!(unsafe { - match libc::accept(self.0, storage, len) { - INVALID_SOCKET => Err(last_error()), + match c::accept(self.0, storage, len) { + c::INVALID_SOCKET => Err(last_error()), n => Ok(Socket(n)), } }); @@ -113,7 +120,7 @@ impl Socket { info.iProtocol, &mut info, 0, c::WSA_FLAG_OVERLAPPED) { - INVALID_SOCKET => Err(last_error()), + c::INVALID_SOCKET => Err(last_error()), n => Ok(Socket(n)), } }); @@ -125,7 +132,7 @@ impl Socket { // On unix when a socket is shut down all further reads return 0, so we // do the same on windows to map a shut down socket to returning EOF. unsafe { - match libc::recv(self.0, buf.as_mut_ptr() as *mut c_void, + match c::recv(self.0, buf.as_mut_ptr() as *mut c_void, buf.len() as i32, 0) { -1 if c::WSAGetLastError() == c::WSAESHUTDOWN => Ok(0), -1 => Err(last_error()), @@ -134,7 +141,8 @@ impl Socket { } } - pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> { + pub fn set_timeout(&self, dur: Option<Duration>, + kind: c_int) -> io::Result<()> { let timeout = match dur { Some(dur) => { let timeout = sys::dur2timeout(dur); @@ -146,11 +154,11 @@ impl Socket { } None => 0 }; - setsockopt(self, libc::SOL_SOCKET, kind, timeout) + net::setsockopt(self, c::SOL_SOCKET, kind, timeout) } - pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> { - let raw: libc::DWORD = try!(getsockopt(self, libc::SOL_SOCKET, kind)); + pub fn timeout(&self, kind: c_int) -> io::Result<Option<Duration>> { + let raw: c::DWORD = try!(net::getsockopt(self, c::SOL_SOCKET, kind)); if raw == 0 { Ok(None) } else { @@ -162,28 +170,38 @@ impl Socket { fn set_no_inherit(&self) -> io::Result<()> { sys::cvt(unsafe { - c::SetHandleInformation(self.0 as libc::HANDLE, + c::SetHandleInformation(self.0 as c::HANDLE, c::HANDLE_FLAG_INHERIT, 0) }).map(|_| ()) } + + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + let how = match how { + Shutdown::Write => c::SD_SEND, + Shutdown::Read => c::SD_RECEIVE, + Shutdown::Both => c::SD_BOTH, + }; + try!(cvt(unsafe { c::shutdown(self.0, how) })); + Ok(()) + } } impl Drop for Socket { fn drop(&mut self) { - let _ = unsafe { libc::closesocket(self.0) }; + let _ = unsafe { c::closesocket(self.0) }; } } -impl AsInner<libc::SOCKET> for Socket { - fn as_inner(&self) -> &libc::SOCKET { &self.0 } +impl AsInner<c::SOCKET> for Socket { + fn as_inner(&self) -> &c::SOCKET { &self.0 } } -impl FromInner<libc::SOCKET> for Socket { - fn from_inner(sock: libc::SOCKET) -> Socket { Socket(sock) } +impl FromInner<c::SOCKET> for Socket { + fn from_inner(sock: c::SOCKET) -> Socket { Socket(sock) } } -impl IntoInner<libc::SOCKET> for Socket { - fn into_inner(self) -> libc::SOCKET { +impl IntoInner<c::SOCKET> for Socket { + fn into_inner(self) -> c::SOCKET { let ret = self.0; mem::forget(self); ret diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index ba4bce38014..52740b2cad4 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -19,8 +19,7 @@ use error::Error as StdError; use ffi::{OsString, OsStr}; use fmt; use io; -use libc::types::os::arch::extra::LPWCH; -use libc::{self, c_int, c_void}; +use libc::{c_int, c_void}; use ops::Range; use os::windows::ffi::EncodeWide; use path::{self, PathBuf}; @@ -29,52 +28,27 @@ use slice; use sys::{c, cvt}; use sys::handle::Handle; -use libc::funcs::extra::kernel32::{ - GetEnvironmentStringsW, - FreeEnvironmentStringsW -}; - pub fn errno() -> i32 { - unsafe { libc::GetLastError() as i32 } + unsafe { c::GetLastError() as i32 } } /// Gets a detailed string description for the given error number. pub fn error_string(errnum: i32) -> String { - use libc::types::os::arch::extra::DWORD; - use libc::types::os::arch::extra::LPWSTR; - use libc::types::os::arch::extra::LPVOID; - use libc::types::os::arch::extra::WCHAR; - - #[link_name = "kernel32"] - extern "system" { - fn FormatMessageW(flags: DWORD, - lpSrc: LPVOID, - msgId: DWORD, - langId: DWORD, - buf: LPWSTR, - nsize: DWORD, - args: *const c_void) - -> DWORD; - } - - const FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000; - const FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200; - // This value is calculated from the macro // MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT) - let langId = 0x0800 as DWORD; + let langId = 0x0800 as c::DWORD; - let mut buf = [0 as WCHAR; 2048]; + let mut buf = [0 as c::WCHAR; 2048]; unsafe { - let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - ptr::null_mut(), - errnum as DWORD, - langId, - buf.as_mut_ptr(), - buf.len() as DWORD, - ptr::null()) as usize; + let res = c::FormatMessageW(c::FORMAT_MESSAGE_FROM_SYSTEM | + c::FORMAT_MESSAGE_IGNORE_INSERTS, + ptr::null_mut(), + errnum as c::DWORD, + langId, + buf.as_mut_ptr(), + buf.len() as c::DWORD, + ptr::null()) as usize; if res == 0 { // Sometimes FormatMessageW can fail e.g. system doesn't like langId, let fm_err = errno(); @@ -96,8 +70,8 @@ pub fn error_string(errnum: i32) -> String { } pub struct Env { - base: LPWCH, - cur: LPWCH, + base: c::LPWCH, + cur: c::LPWCH, } impl Iterator for Env { @@ -126,13 +100,13 @@ impl Iterator for Env { impl Drop for Env { fn drop(&mut self) { - unsafe { FreeEnvironmentStringsW(self.base); } + unsafe { c::FreeEnvironmentStringsW(self.base); } } } pub fn env() -> Env { unsafe { - let ch = GetEnvironmentStringsW(); + let ch = c::GetEnvironmentStringsW(); if ch as usize == 0 { panic!("failure getting env string from OS: {}", io::Error::last_os_error()); @@ -233,13 +207,13 @@ impl StdError for JoinPathsError { pub fn current_exe() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { - libc::GetModuleFileNameW(ptr::null_mut(), buf, sz) + c::GetModuleFileNameW(ptr::null_mut(), buf, sz) }, super::os2path) } pub fn getcwd() -> io::Result<PathBuf> { super::fill_utf16_buf(|buf, sz| unsafe { - libc::GetCurrentDirectoryW(sz, buf) + c::GetCurrentDirectoryW(sz, buf) }, super::os2path) } @@ -249,23 +223,26 @@ pub fn chdir(p: &path::Path) -> io::Result<()> { p.push(0); cvt(unsafe { - libc::SetCurrentDirectoryW(p.as_ptr()) + c::SetCurrentDirectoryW(p.as_ptr()) }).map(|_| ()) } pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> { let k = super::to_utf16_os(k); let res = super::fill_utf16_buf(|buf, sz| unsafe { - libc::GetEnvironmentVariableW(k.as_ptr(), buf, sz) + c::GetEnvironmentVariableW(k.as_ptr(), buf, sz) }, |buf| { OsStringExt::from_wide(buf) }); match res { Ok(value) => Ok(Some(value)), - Err(ref e) if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND) => { - Ok(None) + Err(e) => { + if e.raw_os_error() == Some(c::ERROR_ENVVAR_NOT_FOUND as i32) { + Ok(None) + } else { + Err(e) + } } - Err(e) => Err(e) } } @@ -274,14 +251,14 @@ pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let v = super::to_utf16_os(v); cvt(unsafe { - libc::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) + c::SetEnvironmentVariableW(k.as_ptr(), v.as_ptr()) }).map(|_| ()) } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let v = super::to_utf16_os(n); cvt(unsafe { - libc::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) + c::SetEnvironmentVariableW(v.as_ptr(), ptr::null()) }).map(|_| ()) } @@ -350,14 +327,14 @@ pub fn home_dir() -> Option<PathBuf> { let _handle = Handle::new(token); super::fill_utf16_buf(|buf, mut sz| { match c::GetUserProfileDirectoryW(token, buf, &mut sz) { - 0 if libc::GetLastError() != 0 => 0, + 0 if c::GetLastError() != 0 => 0, 0 => sz, - n => n as libc::DWORD, + n => n as c::DWORD, } }, super::os2path).ok() }) } pub fn exit(code: i32) -> ! { - unsafe { c::ExitProcess(code as libc::c_uint) } + unsafe { c::ExitProcess(code as c::UINT) } } diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs index 3e2f442f073..a6e69c789d0 100644 --- a/src/libstd/sys/windows/pipe.rs +++ b/src/libstd/sys/windows/pipe.rs @@ -9,7 +9,6 @@ // except according to those terms. use io; -use libc; use ptr; use sys::cvt; use sys::c; @@ -24,8 +23,8 @@ pub struct AnonPipe { } pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { - let mut reader = libc::INVALID_HANDLE_VALUE; - let mut writer = libc::INVALID_HANDLE_VALUE; + let mut reader = c::INVALID_HANDLE_VALUE; + let mut writer = c::INVALID_HANDLE_VALUE; try!(cvt(unsafe { c::CreatePipe(&mut reader, &mut writer, ptr::null_mut(), 0) })); @@ -38,7 +37,7 @@ impl AnonPipe { pub fn handle(&self) -> &Handle { &self.inner } pub fn into_handle(self) -> Handle { self.inner } - pub fn raw(&self) -> libc::HANDLE { self.inner.raw() } + pub fn raw(&self) -> c::HANDLE { self.inner.raw() } pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { self.inner.read(buf) diff --git a/src/libstd/sys/windows/printing/gnu.rs b/src/libstd/sys/windows/printing/gnu.rs index e27bef0b1e9..c1367d5381d 100644 --- a/src/libstd/sys/windows/printing/gnu.rs +++ b/src/libstd/sys/windows/printing/gnu.rs @@ -11,14 +11,15 @@ #![allow(deprecated)] use dynamic_lib::DynamicLibrary; -use io; use io::prelude::*; -use libc; +use io; +use sys::c; +use libc::c_void; use sys_common::gnu::libbacktrace; -pub fn print(w: &mut Write, i: isize, addr: u64, _: &DynamicLibrary, _: libc::HANDLE) +pub fn print(w: &mut Write, i: isize, addr: u64, _: &DynamicLibrary, _: c::HANDLE) -> io::Result<()> { - let addr = addr as usize as *mut libc::c_void; + let addr = addr as usize as *mut c_void; libbacktrace::print(w, i, addr, addr) } diff --git a/src/libstd/sys/windows/printing/msvc.rs b/src/libstd/sys/windows/printing/msvc.rs index 6f1db5df7db..d04691a6a47 100644 --- a/src/libstd/sys/windows/printing/msvc.rs +++ b/src/libstd/sys/windows/printing/msvc.rs @@ -10,22 +10,23 @@ #![allow(deprecated)] -use sys_common::backtrace::{output, output_fileline}; -use ffi::CStr; use dynamic_lib::DynamicLibrary; -use super::{SymFromAddrFn, SymGetLineFromAddr64Fn, SYMBOL_INFO, MAX_SYM_NAME, IMAGEHLP_LINE64}; -use io; +use ffi::CStr; use io::prelude::*; -use intrinsics; -use libc; +use io; +use libc::{c_ulong, c_int, c_char, c_void}; +use mem; +use super::{SymFromAddrFn, SymGetLineFromAddr64Fn}; +use sys::c; +use sys_common::backtrace::{output, output_fileline}; -pub fn print(w: &mut Write, i: isize, addr: u64, dbghelp: &DynamicLibrary, process: libc::HANDLE) - -> io::Result<()> { +pub fn print(w: &mut Write, i: isize, addr: u64, dbghelp: &DynamicLibrary, + process: c::HANDLE) -> io::Result<()> { let SymFromAddr = sym!(dbghelp, "SymFromAddr", SymFromAddrFn); let SymGetLineFromAddr64 = sym!(dbghelp, "SymGetLineFromAddr64", SymGetLineFromAddr64Fn); - let mut info: SYMBOL_INFO = unsafe { intrinsics::init() }; - info.MaxNameLen = MAX_SYM_NAME as libc::c_ulong; + let mut info: c::SYMBOL_INFO = unsafe { mem::zeroed() }; + info.MaxNameLen = c::MAX_SYM_NAME as c_ulong; // the struct size in C. the value is different to // `size_of::<SYMBOL_INFO>() - MAX_SYM_NAME + 1` (== 81) // due to struct alignment. @@ -34,25 +35,25 @@ pub fn print(w: &mut Write, i: isize, addr: u64, dbghelp: &DynamicLibrary, proce let mut displacement = 0u64; let ret = SymFromAddr(process, addr, &mut displacement, &mut info); - let name = if ret == libc::TRUE { - let ptr = info.Name.as_ptr() as *const libc::c_char; + let name = if ret == c::TRUE { + let ptr = info.Name.as_ptr() as *const c_char; Some(unsafe { CStr::from_ptr(ptr).to_bytes() }) } else { None }; - try!(output(w, i, addr as usize as *mut libc::c_void, name)); + try!(output(w, i, addr as usize as *mut c_void, name)); // Now find out the filename and line number - let mut line: IMAGEHLP_LINE64 = unsafe { intrinsics::init() }; - line.SizeOfStruct = ::mem::size_of::<IMAGEHLP_LINE64>() as u32; + let mut line: c::IMAGEHLP_LINE64 = unsafe { mem::zeroed() }; + line.SizeOfStruct = ::mem::size_of::<c::IMAGEHLP_LINE64>() as u32; let mut displacement = 0u32; let ret = SymGetLineFromAddr64(process, addr, &mut displacement, &mut line); - if ret == libc::TRUE { + if ret == c::TRUE { output_fileline(w, unsafe { CStr::from_ptr(line.Filename).to_bytes() }, - line.LineNumber as libc::c_int, + line.LineNumber as c_int, false) } else { Ok(()) diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs index e8cc160fde7..e0f8d6f9df9 100644 --- a/src/libstd/sys/windows/process.rs +++ b/src/libstd/sys/windows/process.rs @@ -19,13 +19,14 @@ use ffi::{OsString, OsStr}; use fmt; use fs; use io::{self, Error}; -use libc::{self, c_void}; +use libc::c_void; use mem; use os::windows::ffi::OsStrExt; use path::Path; use ptr; use sync::StaticMutex; use sys::c; + use sys::fs::{OpenOptions, File}; use sys::handle::{Handle, RawHandle}; use sys::stdio; @@ -107,7 +108,7 @@ pub struct Process { pub enum Stdio { Inherit, None, - Raw(libc::HANDLE), + Raw(c::HANDLE), } pub type RawStdio = Handle; @@ -118,9 +119,6 @@ impl Process { out_handle: Stdio, err_handle: Stdio) -> io::Result<Process> { - use libc::{TRUE, STARTF_USESTDHANDLES}; - use libc::{DWORD, STARTUPINFO, CreateProcessW}; - // To have the spawning semantics of unix/windows stay the same, we need // to read the *child's* PATH if one is provided. See #15149 for more // details. @@ -143,8 +141,8 @@ impl Process { }); let mut si = zeroed_startupinfo(); - si.cb = mem::size_of::<STARTUPINFO>() as DWORD; - si.dwFlags = STARTF_USESTDHANDLES; + si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD; + si.dwFlags = c::STARTF_USESTDHANDLES; let stdin = try!(in_handle.to_handle(c::STD_INPUT_HANDLE)); let stdout = try!(out_handle.to_handle(c::STD_OUTPUT_HANDLE)); @@ -159,9 +157,9 @@ impl Process { cmd_str.push(0); // add null terminator // stolen from the libuv code. - let mut flags = libc::CREATE_UNICODE_ENVIRONMENT; + let mut flags = c::CREATE_UNICODE_ENVIRONMENT; if cfg.detach { - flags |= libc::DETACHED_PROCESS | libc::CREATE_NEW_PROCESS_GROUP; + flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP; } let (envp, _data) = make_envp(cfg.env.as_ref()); @@ -173,12 +171,12 @@ impl Process { static CREATE_PROCESS_LOCK: StaticMutex = StaticMutex::new(); let _lock = CREATE_PROCESS_LOCK.lock(); - cvt(CreateProcessW(ptr::null(), - cmd_str.as_mut_ptr(), - ptr::null_mut(), - ptr::null_mut(), - TRUE, flags, envp, dirp, - &mut si, &mut pi)) + cvt(c::CreateProcessW(ptr::null(), + cmd_str.as_mut_ptr(), + ptr::null_mut(), + ptr::null_mut(), + c::TRUE, flags, envp, dirp, + &mut si, &mut pi)) }); // We close the thread handle because we don't care about keeping @@ -190,7 +188,7 @@ impl Process { } pub unsafe fn kill(&self) -> io::Result<()> { - try!(cvt(libc::TerminateProcess(self.handle.raw(), 1))); + try!(cvt(c::TerminateProcess(self.handle.raw(), 1))); Ok(()) } @@ -201,15 +199,13 @@ impl Process { } pub fn wait(&self) -> io::Result<ExitStatus> { - use libc::{INFINITE, WAIT_OBJECT_0}; - use libc::{GetExitCodeProcess, WaitForSingleObject}; - unsafe { - if WaitForSingleObject(self.handle.raw(), INFINITE) != WAIT_OBJECT_0 { + let res = c::WaitForSingleObject(self.handle.raw(), c::INFINITE); + if res != c::WAIT_OBJECT_0 { return Err(Error::last_os_error()) } let mut status = 0; - try!(cvt(GetExitCodeProcess(self.handle.raw(), &mut status))); + try!(cvt(c::GetExitCodeProcess(self.handle.raw(), &mut status))); Ok(ExitStatus(status)) } } @@ -220,7 +216,7 @@ impl Process { } #[derive(PartialEq, Eq, Clone, Copy, Debug)] -pub struct ExitStatus(libc::DWORD); +pub struct ExitStatus(c::DWORD); impl ExitStatus { pub fn success(&self) -> bool { @@ -237,8 +233,8 @@ impl fmt::Display for ExitStatus { } } -fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO { - libc::types::os::arch::extra::STARTUPINFO { +fn zeroed_startupinfo() -> c::STARTUPINFO { + c::STARTUPINFO { cb: 0, lpReserved: ptr::null_mut(), lpDesktop: ptr::null_mut(), @@ -254,14 +250,14 @@ fn zeroed_startupinfo() -> libc::types::os::arch::extra::STARTUPINFO { wShowWindow: 0, cbReserved2: 0, lpReserved2: ptr::null_mut(), - hStdInput: libc::INVALID_HANDLE_VALUE, - hStdOutput: libc::INVALID_HANDLE_VALUE, - hStdError: libc::INVALID_HANDLE_VALUE, + hStdInput: c::INVALID_HANDLE_VALUE, + hStdOutput: c::INVALID_HANDLE_VALUE, + hStdError: c::INVALID_HANDLE_VALUE, } } -fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMATION { - libc::types::os::arch::extra::PROCESS_INFORMATION { +fn zeroed_process_information() -> c::PROCESS_INFORMATION { + c::PROCESS_INFORMATION { hProcess: ptr::null_mut(), hThread: ptr::null_mut(), dwProcessId: 0, @@ -353,17 +349,15 @@ fn make_dirp(d: Option<&OsString>) -> (*const u16, Vec<u16>) { } impl Stdio { - fn to_handle(&self, stdio_id: libc::DWORD) -> io::Result<Handle> { - use libc::DUPLICATE_SAME_ACCESS; - + fn to_handle(&self, stdio_id: c::DWORD) -> io::Result<Handle> { match *self { Stdio::Inherit => { stdio::get(stdio_id).and_then(|io| { - io.handle().duplicate(0, true, DUPLICATE_SAME_ACCESS) + io.handle().duplicate(0, true, c::DUPLICATE_SAME_ACCESS) }) } Stdio::Raw(handle) => { - RawHandle::new(handle).duplicate(0, true, DUPLICATE_SAME_ACCESS) + RawHandle::new(handle).duplicate(0, true, c::DUPLICATE_SAME_ACCESS) } // Similarly to unix, we don't actually leave holes for the @@ -371,9 +365,9 @@ impl Stdio { // equivalents. These equivalents are drawn from libuv's // windows process spawning. Stdio::None => { - let size = mem::size_of::<libc::SECURITY_ATTRIBUTES>(); - let mut sa = libc::SECURITY_ATTRIBUTES { - nLength: size as libc::DWORD, + let size = mem::size_of::<c::SECURITY_ATTRIBUTES>(); + let mut sa = c::SECURITY_ATTRIBUTES { + nLength: size as c::DWORD, lpSecurityDescriptor: ptr::null_mut(), bInheritHandle: 1, }; diff --git a/src/libstd/sys/windows/stack_overflow.rs b/src/libstd/sys/windows/stack_overflow.rs index d1c2144ef0d..01317bec0de 100644 --- a/src/libstd/sys/windows/stack_overflow.rs +++ b/src/libstd/sys/windows/stack_overflow.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use libc::{self, LONG}; use sys_common::util::report_overflow; use sys::c; @@ -19,7 +18,7 @@ impl Handler { // This API isn't available on XP, so don't panic in that case and just // pray it works out ok. if c::SetThreadStackGuarantee(&mut 0x5000) == 0 { - if libc::GetLastError() as u32 != libc::ERROR_CALL_NOT_IMPLEMENTED as u32 { + if c::GetLastError() as u32 != c::ERROR_CALL_NOT_IMPLEMENTED as u32 { panic!("failed to reserve stack space for exception handling"); } } @@ -28,7 +27,7 @@ impl Handler { } extern "system" fn vectored_handler(ExceptionInfo: *mut c::EXCEPTION_POINTERS) - -> LONG { + -> c::LONG { unsafe { let rec = &(*(*ExceptionInfo).ExceptionRecord); let code = rec.ExceptionCode; diff --git a/src/libstd/sys/windows/stdio.rs b/src/libstd/sys/windows/stdio.rs index 356787d5bf0..8f37dc02e87 100644 --- a/src/libstd/sys/windows/stdio.rs +++ b/src/libstd/sys/windows/stdio.rs @@ -12,7 +12,6 @@ use prelude::v1::*; use io::prelude::*; use io::{self, Cursor}; -use libc; use ptr; use str; use sync::Mutex; @@ -34,9 +33,9 @@ pub struct Stdin { pub struct Stdout(Output); pub struct Stderr(Output); -pub fn get(handle: libc::DWORD) -> io::Result<Output> { +pub fn get(handle: c::DWORD) -> io::Result<Output> { let handle = unsafe { c::GetStdHandle(handle) }; - if handle == libc::INVALID_HANDLE_VALUE { + if handle == c::INVALID_HANDLE_VALUE { Err(io::Error::last_os_error()) } else if handle.is_null() { Err(io::Error::new(io::ErrorKind::Other, @@ -63,7 +62,7 @@ fn write(out: &Output, data: &[u8]) -> io::Result<usize> { let mut written = 0; try!(cvt(unsafe { c::WriteConsoleW(handle, - utf16.as_ptr() as libc::LPCVOID, + utf16.as_ptr() as c::LPCVOID, utf16.len() as u32, &mut written, ptr::null_mut()) @@ -97,7 +96,7 @@ impl Stdin { let mut num = 0; try!(cvt(unsafe { c::ReadConsoleW(handle, - utf16.as_mut_ptr() as libc::LPVOID, + utf16.as_mut_ptr() as c::LPVOID, utf16.len() as u32, &mut num, ptr::null_mut()) @@ -147,7 +146,7 @@ impl io::Write for Stderr { } impl NoClose { - fn new(handle: libc::HANDLE) -> NoClose { + fn new(handle: c::HANDLE) -> NoClose { NoClose(Some(Handle::new(handle))) } diff --git a/src/libstd/sys/windows/thread.rs b/src/libstd/sys/windows/thread.rs index cf1b3ebddb9..a6e6cc94b76 100644 --- a/src/libstd/sys/windows/thread.rs +++ b/src/libstd/sys/windows/thread.rs @@ -12,8 +12,8 @@ use prelude::v1::*; use alloc::boxed::FnBox; use io; -use libc::{self, c_void, DWORD}; use mem; +use libc::c_void; use ptr; use sys::c; use sys::handle::Handle; @@ -37,7 +37,7 @@ impl Thread { // Round up to the next 64 kB because that's what the NT kernel does, // might as well make it explicit. let stack_size = (stack + 0xfffe) & (!0xfffe); - let ret = c::CreateThread(ptr::null_mut(), stack_size as libc::size_t, + let ret = c::CreateThread(ptr::null_mut(), stack_size, thread_start, &*p as *const _ as *mut _, 0, ptr::null_mut()); @@ -48,7 +48,7 @@ impl Thread { Ok(Thread { handle: Handle::new(ret) }) }; - extern "system" fn thread_start(main: *mut libc::c_void) -> DWORD { + extern "system" fn thread_start(main: *mut c_void) -> c::DWORD { unsafe { start_thread(main); } 0 } @@ -62,8 +62,7 @@ impl Thread { } pub fn join(self) { - use libc::consts::os::extra::INFINITE; - unsafe { c::WaitForSingleObject(self.handle.raw(), INFINITE); } + unsafe { c::WaitForSingleObject(self.handle.raw(), c::INFINITE); } } pub fn yield_now() { diff --git a/src/libstd/sys/windows/thread_local.rs b/src/libstd/sys/windows/thread_local.rs index c544eec7fce..db2ad1d89c4 100644 --- a/src/libstd/sys/windows/thread_local.rs +++ b/src/libstd/sys/windows/thread_local.rs @@ -10,13 +10,12 @@ use prelude::v1::*; -use libc::types::os::arch::extra::{DWORD, LPVOID, BOOL}; - use ptr; -use sys_common; +use sys::c; use sys_common::mutex::Mutex; +use sys_common; -pub type Key = DWORD; +pub type Key = c::DWORD; pub type Dtor = unsafe extern fn(*mut u8); // Turns out, like pretty much everything, Windows is pretty close the @@ -68,9 +67,8 @@ static mut DTORS: *mut Vec<(Key, Dtor)> = ptr::null_mut(); #[inline] pub unsafe fn create(dtor: Option<Dtor>) -> Key { - const TLS_OUT_OF_INDEXES: DWORD = 0xFFFFFFFF; - let key = TlsAlloc(); - assert!(key != TLS_OUT_OF_INDEXES); + let key = c::TlsAlloc(); + assert!(key != c::TLS_OUT_OF_INDEXES); match dtor { Some(f) => register_dtor(key, f), None => {} @@ -80,13 +78,13 @@ pub unsafe fn create(dtor: Option<Dtor>) -> Key { #[inline] pub unsafe fn set(key: Key, value: *mut u8) { - let r = TlsSetValue(key, value as LPVOID); + let r = c::TlsSetValue(key, value as c::LPVOID); debug_assert!(r != 0); } #[inline] pub unsafe fn get(key: Key) -> *mut u8 { - TlsGetValue(key) as *mut u8 + c::TlsGetValue(key) as *mut u8 } #[inline] @@ -107,18 +105,11 @@ pub unsafe fn destroy(key: Key) { // Note that source [2] above shows precedent for this sort // of strategy. } else { - let r = TlsFree(key); + let r = c::TlsFree(key); debug_assert!(r != 0); } } -extern "system" { - fn TlsAlloc() -> DWORD; - fn TlsFree(dwTlsIndex: DWORD) -> BOOL; - fn TlsGetValue(dwTlsIndex: DWORD) -> LPVOID; - fn TlsSetValue(dwTlsIndex: DWORD, lpTlsvalue: LPVOID) -> BOOL; -} - // ------------------------------------------------------------------------- // Dtor registration // @@ -243,17 +234,15 @@ unsafe fn unregister_dtor(key: Key) -> bool { #[link_section = ".CRT$XLB"] #[linkage = "external"] #[allow(warnings)] -pub static p_thread_callback: unsafe extern "system" fn(LPVOID, DWORD, - LPVOID) = +pub static p_thread_callback: unsafe extern "system" fn(c::LPVOID, c::DWORD, + c::LPVOID) = on_tls_callback; #[allow(warnings)] -unsafe extern "system" fn on_tls_callback(h: LPVOID, - dwReason: DWORD, - pv: LPVOID) { - const DLL_THREAD_DETACH: DWORD = 3; - const DLL_PROCESS_DETACH: DWORD = 0; - if dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH { +unsafe extern "system" fn on_tls_callback(h: c::LPVOID, + dwReason: c::DWORD, + pv: c::LPVOID) { + if dwReason == c::DLL_THREAD_DETACH || dwReason == c::DLL_PROCESS_DETACH { run_dtors(); } @@ -286,9 +275,9 @@ unsafe fn run_dtors() { ret }; for &(key, dtor) in &dtors { - let ptr = TlsGetValue(key); + let ptr = c::TlsGetValue(key); if !ptr.is_null() { - TlsSetValue(key, ptr::null_mut()); + c::TlsSetValue(key, ptr::null_mut()); dtor(ptr as *mut _); any_run = true; } diff --git a/src/libstd/sys/windows/time.rs b/src/libstd/sys/windows/time.rs index f5a70ccc907..4dc7997d22e 100644 --- a/src/libstd/sys/windows/time.rs +++ b/src/libstd/sys/windows/time.rs @@ -7,32 +7,33 @@ // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. -use libc; + use ops::Sub; -use time::Duration; use sync::Once; +use sys::c; +use time::Duration; const NANOS_PER_SEC: u64 = 1_000_000_000; pub struct SteadyTime { - t: libc::LARGE_INTEGER, + t: c::LARGE_INTEGER, } impl SteadyTime { pub fn now() -> SteadyTime { let mut t = SteadyTime { t: 0 }; - unsafe { libc::QueryPerformanceCounter(&mut t.t); } + unsafe { c::QueryPerformanceCounter(&mut t.t); } t } } -fn frequency() -> libc::LARGE_INTEGER { - static mut FREQUENCY: libc::LARGE_INTEGER = 0; +fn frequency() -> c::LARGE_INTEGER { + static mut FREQUENCY: c::LARGE_INTEGER = 0; static ONCE: Once = Once::new(); unsafe { ONCE.call_once(|| { - libc::QueryPerformanceFrequency(&mut FREQUENCY); + c::QueryPerformanceFrequency(&mut FREQUENCY); }); FREQUENCY } |
