about summary refs log tree commit diff
diff options
context:
space:
mode:
authorAndy Russell <arussell123@gmail.com>2020-01-04 16:46:47 -0500
committerAndy Russell <arussell123@gmail.com>2020-01-11 20:56:46 -0500
commit7b564c67deb6f5e9d7102871d63a9ad3d7161278 (patch)
treeb43fded1c4297cb96a2c7825044d66def77f851c
parent1389494ac145a84dba025ff65969f7ab150c3f02 (diff)
downloadrust-7b564c67deb6f5e9d7102871d63a9ad3d7161278.tar.gz
rust-7b564c67deb6f5e9d7102871d63a9ad3d7161278.zip
use winapi for non-stdlib Windows bindings
-rw-r--r--Cargo.lock6
-rw-r--r--src/bootstrap/Cargo.toml4
-rw-r--r--src/bootstrap/job.rs88
-rw-r--r--src/bootstrap/util.rs62
-rw-r--r--src/librustc/lib.rs1
-rw-r--r--src/librustc_data_structures/Cargo.toml3
-rw-r--r--src/librustc_data_structures/flock.rs34
-rw-r--r--src/librustc_data_structures/lib.rs3
-rw-r--r--src/librustc_data_structures/profiling.rs46
-rw-r--r--src/librustc_driver/Cargo.toml3
-rw-r--r--src/librustc_driver/lib.rs18
-rw-r--r--src/librustc_errors/Cargo.toml3
-rw-r--r--src/librustc_errors/lock.rs27
-rw-r--r--src/librustc_interface/Cargo.toml3
-rw-r--r--src/librustc_interface/util.rs14
-rw-r--r--src/librustc_metadata/Cargo.toml3
-rw-r--r--src/librustc_metadata/dynamic_lib.rs33
-rw-r--r--src/tools/compiletest/src/runtest.rs6
18 files changed, 94 insertions, 263 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 54ad60e7150..0e7f91283cf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -201,6 +201,7 @@ dependencies = [
  "serde_json",
  "time",
  "toml",
+ "winapi 0.3.8",
 ]
 
 [[package]]
@@ -3491,6 +3492,7 @@ dependencies = [
  "serialize",
  "smallvec 1.0.0",
  "stable_deref_trait",
+ "winapi 0.3.8",
 ]
 
 [[package]]
@@ -3518,6 +3520,7 @@ dependencies = [
  "rustc_target",
  "serialize",
  "syntax",
+ "winapi 0.3.8",
 ]
 
 [[package]]
@@ -3537,6 +3540,7 @@ dependencies = [
  "term_size",
  "termcolor",
  "unicode-width",
+ "winapi 0.3.8",
 ]
 
 [[package]]
@@ -3647,6 +3651,7 @@ dependencies = [
  "smallvec 1.0.0",
  "syntax",
  "tempfile",
+ "winapi 0.3.8",
 ]
 
 [[package]]
@@ -3715,6 +3720,7 @@ dependencies = [
  "smallvec 1.0.0",
  "stable_deref_trait",
  "syntax",
+ "winapi 0.3.8",
 ]
 
 [[package]]
diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml
index 3ab00a6e147..c09f58cc591 100644
--- a/src/bootstrap/Cargo.toml
+++ b/src/bootstrap/Cargo.toml
@@ -49,5 +49,9 @@ lazy_static = "1.3.0"
 time = "0.1"
 ignore = "0.4.10"
 
+[target.'cfg(windows)'.dependencies.winapi]
+version = "0.3"
+features = ["fileapi", "ioapiset", "jobapi2", "handleapi", "winioctl"]
+
 [dev-dependencies]
 pretty_assertions = "0.5"
diff --git a/src/bootstrap/job.rs b/src/bootstrap/job.rs
index 57153e2ad39..efeb86540b7 100644
--- a/src/bootstrap/job.rs
+++ b/src/bootstrap/job.rs
@@ -35,84 +35,16 @@ use std::io;
 use std::mem;
 use std::ptr;
 
-type HANDLE = *mut u8;
-type BOOL = i32;
-type DWORD = u32;
-type LPHANDLE = *mut HANDLE;
-type LPVOID = *mut u8;
-type JOBOBJECTINFOCLASS = i32;
-type SIZE_T = usize;
-type LARGE_INTEGER = i64;
-type UINT = u32;
-type ULONG_PTR = usize;
-type ULONGLONG = u64;
-
-const FALSE: BOOL = 0;
-const DUPLICATE_SAME_ACCESS: DWORD = 0x2;
-const PROCESS_DUP_HANDLE: DWORD = 0x40;
-const JobObjectExtendedLimitInformation: JOBOBJECTINFOCLASS = 9;
-const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: DWORD = 0x2000;
-const JOB_OBJECT_LIMIT_PRIORITY_CLASS: DWORD = 0x00000020;
-const SEM_FAILCRITICALERRORS: UINT = 0x0001;
-const SEM_NOGPFAULTERRORBOX: UINT = 0x0002;
-const BELOW_NORMAL_PRIORITY_CLASS: DWORD = 0x00004000;
-
-extern "system" {
-    fn CreateJobObjectW(lpJobAttributes: *mut u8, lpName: *const u8) -> HANDLE;
-    fn CloseHandle(hObject: HANDLE) -> BOOL;
-    fn GetCurrentProcess() -> HANDLE;
-    fn OpenProcess(dwDesiredAccess: DWORD, bInheritHandle: BOOL, dwProcessId: DWORD) -> HANDLE;
-    fn DuplicateHandle(
-        hSourceProcessHandle: HANDLE,
-        hSourceHandle: HANDLE,
-        hTargetProcessHandle: HANDLE,
-        lpTargetHandle: LPHANDLE,
-        dwDesiredAccess: DWORD,
-        bInheritHandle: BOOL,
-        dwOptions: DWORD,
-    ) -> BOOL;
-    fn AssignProcessToJobObject(hJob: HANDLE, hProcess: HANDLE) -> BOOL;
-    fn SetInformationJobObject(
-        hJob: HANDLE,
-        JobObjectInformationClass: JOBOBJECTINFOCLASS,
-        lpJobObjectInformation: LPVOID,
-        cbJobObjectInformationLength: DWORD,
-    ) -> BOOL;
-    fn SetErrorMode(mode: UINT) -> UINT;
-}
-
-#[repr(C)]
-struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
-    BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION,
-    IoInfo: IO_COUNTERS,
-    ProcessMemoryLimit: SIZE_T,
-    JobMemoryLimit: SIZE_T,
-    PeakProcessMemoryUsed: SIZE_T,
-    PeakJobMemoryUsed: SIZE_T,
-}
-
-#[repr(C)]
-struct IO_COUNTERS {
-    ReadOperationCount: ULONGLONG,
-    WriteOperationCount: ULONGLONG,
-    OtherOperationCount: ULONGLONG,
-    ReadTransferCount: ULONGLONG,
-    WriteTransferCount: ULONGLONG,
-    OtherTransferCount: ULONGLONG,
-}
-
-#[repr(C)]
-struct JOBOBJECT_BASIC_LIMIT_INFORMATION {
-    PerProcessUserTimeLimit: LARGE_INTEGER,
-    PerJobUserTimeLimit: LARGE_INTEGER,
-    LimitFlags: DWORD,
-    MinimumWorkingsetSize: SIZE_T,
-    MaximumWorkingsetSize: SIZE_T,
-    ActiveProcessLimit: DWORD,
-    Affinity: ULONG_PTR,
-    PriorityClass: DWORD,
-    SchedulingClass: DWORD,
-}
+use winapi::shared::minwindef::{DWORD, FALSE, LPVOID};
+use winapi::um::errhandlingapi::SetErrorMode;
+use winapi::um::handleapi::{CloseHandle, DuplicateHandle};
+use winapi::um::jobapi2::{AssignProcessToJobObject, CreateJobObjectW, SetInformationJobObject};
+use winapi::um::processthreadsapi::{GetCurrentProcess, OpenProcess};
+use winapi::um::winbase::{BELOW_NORMAL_PRIORITY_CLASS, SEM_NOGPFAULTERRORBOX};
+use winapi::um::winnt::{
+    JobObjectExtendedLimitInformation, DUPLICATE_SAME_ACCESS, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
+    JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOB_OBJECT_LIMIT_PRIORITY_CLASS, PROCESS_DUP_HANDLE,
+};
 
 pub unsafe fn setup(build: &mut Build) {
     // Enable the Windows Error Reporting dialog which msys disables,
diff --git a/src/bootstrap/util.rs b/src/bootstrap/util.rs
index 5fd25981851..7d1efe4610f 100644
--- a/src/bootstrap/util.rs
+++ b/src/bootstrap/util.rs
@@ -123,37 +123,24 @@ pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
     // what can be found here:
     //
     // http://www.flexhex.com/docs/articles/hard-links.phtml
-    //
-    // Copied from std
     #[cfg(windows)]
-    #[allow(nonstandard_style)]
     fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> {
         use std::ffi::OsStr;
         use std::os::windows::ffi::OsStrExt;
         use std::ptr;
 
-        const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024;
-        const GENERIC_WRITE: DWORD = 0x40000000;
-        const OPEN_EXISTING: DWORD = 3;
-        const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000;
-        const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000;
-        const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4;
-        const IO_REPARSE_TAG_MOUNT_POINT: DWORD = 0xa0000003;
-        const FILE_SHARE_DELETE: DWORD = 0x4;
-        const FILE_SHARE_READ: DWORD = 0x1;
-        const FILE_SHARE_WRITE: DWORD = 0x2;
-
-        type BOOL = i32;
-        type DWORD = u32;
-        type HANDLE = *mut u8;
-        type LPCWSTR = *const u16;
-        type LPDWORD = *mut DWORD;
-        type LPOVERLAPPED = *mut u8;
-        type LPSECURITY_ATTRIBUTES = *mut u8;
-        type LPVOID = *mut u8;
-        type WCHAR = u16;
-        type WORD = u16;
-
+        use winapi::shared::minwindef::{DWORD, WORD};
+        use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
+        use winapi::um::handleapi::CloseHandle;
+        use winapi::um::ioapiset::DeviceIoControl;
+        use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT};
+        use winapi::um::winioctl::FSCTL_SET_REPARSE_POINT;
+        use winapi::um::winnt::{
+            FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_WRITE,
+            IO_REPARSE_TAG_MOUNT_POINT, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, WCHAR,
+        };
+
+        #[allow(non_snake_case)]
         #[repr(C)]
         struct REPARSE_MOUNTPOINT_DATA_BUFFER {
             ReparseTag: DWORD,
@@ -165,29 +152,6 @@ pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
             ReparseTarget: WCHAR,
         }
 
-        extern "system" {
-            fn CreateFileW(
-                lpFileName: LPCWSTR,
-                dwDesiredAccess: DWORD,
-                dwShareMode: DWORD,
-                lpSecurityAttributes: LPSECURITY_ATTRIBUTES,
-                dwCreationDisposition: DWORD,
-                dwFlagsAndAttributes: DWORD,
-                hTemplateFile: HANDLE,
-            ) -> HANDLE;
-            fn DeviceIoControl(
-                hDevice: HANDLE,
-                dwIoControlCode: DWORD,
-                lpInBuffer: LPVOID,
-                nInBufferSize: DWORD,
-                lpOutBuffer: LPVOID,
-                nOutBufferSize: DWORD,
-                lpBytesReturned: LPDWORD,
-                lpOverlapped: LPOVERLAPPED,
-            ) -> BOOL;
-            fn CloseHandle(hObject: HANDLE) -> BOOL;
-        }
-
         fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
             Ok(s.as_ref().encode_wide().chain(Some(0)).collect())
         }
@@ -212,7 +176,7 @@ pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> {
                 ptr::null_mut(),
             );
 
-            let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+            let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE as usize];
             let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER;
             let buf = &mut (*db).ReparseTarget as *mut u16;
             let mut i = 0;
diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs
index 3c0160a0452..30372e4af50 100644
--- a/src/librustc/lib.rs
+++ b/src/librustc/lib.rs
@@ -34,7 +34,6 @@
 #![feature(const_transmute)]
 #![feature(core_intrinsics)]
 #![feature(drain_filter)]
-#![cfg_attr(windows, feature(libc))]
 #![feature(never_type)]
 #![feature(exhaustive_patterns)]
 #![feature(overlapping_marker_traits)]
diff --git a/src/librustc_data_structures/Cargo.toml b/src/librustc_data_structures/Cargo.toml
index 19db9834fd4..fb4f818c4b2 100644
--- a/src/librustc_data_structures/Cargo.toml
+++ b/src/librustc_data_structures/Cargo.toml
@@ -31,3 +31,6 @@ measureme = "0.7.1"
 [dependencies.parking_lot]
 version = "0.9"
 features = ["nightly"]
+
+[target.'cfg(windows)'.dependencies]
+winapi = { version = "0.3", features = ["fileapi", "psapi"] }
diff --git a/src/librustc_data_structures/flock.rs b/src/librustc_data_structures/flock.rs
index e3282c5d276..2a0139fa90d 100644
--- a/src/librustc_data_structures/flock.rs
+++ b/src/librustc_data_structures/flock.rs
@@ -87,39 +87,11 @@ cfg_if! {
     } else if #[cfg(windows)] {
         use std::mem;
         use std::os::windows::prelude::*;
-        use std::os::windows::raw::HANDLE;
         use std::fs::{File, OpenOptions};
-        use std::os::raw::{c_ulong, c_int};
-
-        type DWORD = c_ulong;
-        type BOOL = c_int;
-        type ULONG_PTR = usize;
-
-        type LPOVERLAPPED = *mut OVERLAPPED;
-        const LOCKFILE_EXCLUSIVE_LOCK: DWORD = 0x0000_0002;
-        const LOCKFILE_FAIL_IMMEDIATELY: DWORD = 0x0000_0001;
-
-        const FILE_SHARE_DELETE: DWORD = 0x4;
-        const FILE_SHARE_READ: DWORD = 0x1;
-        const FILE_SHARE_WRITE: DWORD = 0x2;
-
-        #[repr(C)]
-        struct OVERLAPPED {
-            Internal: ULONG_PTR,
-            InternalHigh: ULONG_PTR,
-            Offset: DWORD,
-            OffsetHigh: DWORD,
-            hEvent: HANDLE,
-        }
 
-        extern "system" {
-            fn LockFileEx(hFile: HANDLE,
-                          dwFlags: DWORD,
-                          dwReserved: DWORD,
-                          nNumberOfBytesToLockLow: DWORD,
-                          nNumberOfBytesToLockHigh: DWORD,
-                          lpOverlapped: LPOVERLAPPED) -> BOOL;
-        }
+        use winapi::um::minwinbase::{OVERLAPPED, LOCKFILE_FAIL_IMMEDIATELY, LOCKFILE_EXCLUSIVE_LOCK};
+        use winapi::um::fileapi::LockFileEx;
+        use winapi::um::winnt::{FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE};
 
         #[derive(Debug)]
         pub struct Lock {
diff --git a/src/librustc_data_structures/lib.rs b/src/librustc_data_structures/lib.rs
index 51a38a7d2ab..6db2910bca4 100644
--- a/src/librustc_data_structures/lib.rs
+++ b/src/librustc_data_structures/lib.rs
@@ -33,9 +33,6 @@ extern crate libc;
 #[macro_use]
 extern crate cfg_if;
 
-#[cfg(windows)]
-extern crate libc;
-
 pub use rustc_serialize::hex::ToHex;
 
 #[inline(never)]
diff --git a/src/librustc_data_structures/profiling.rs b/src/librustc_data_structures/profiling.rs
index 8deb43d50f9..004db0a79a8 100644
--- a/src/librustc_data_structures/profiling.rs
+++ b/src/librustc_data_structures/profiling.rs
@@ -569,39 +569,19 @@ fn get_resident() -> Option<usize> {
 
 #[cfg(windows)]
 fn get_resident() -> Option<usize> {
-    type BOOL = i32;
-    type DWORD = u32;
-    type HANDLE = *mut u8;
-    use libc::size_t;
-    #[repr(C)]
-    #[allow(non_snake_case)]
-    struct PROCESS_MEMORY_COUNTERS {
-        cb: DWORD,
-        PageFaultCount: DWORD,
-        PeakWorkingSetSize: size_t,
-        WorkingSetSize: size_t,
-        QuotaPeakPagedPoolUsage: size_t,
-        QuotaPagedPoolUsage: size_t,
-        QuotaPeakNonPagedPoolUsage: size_t,
-        QuotaNonPagedPoolUsage: size_t,
-        PagefileUsage: size_t,
-        PeakPagefileUsage: size_t,
-    }
-    #[allow(non_camel_case_types)]
-    type PPROCESS_MEMORY_COUNTERS = *mut PROCESS_MEMORY_COUNTERS;
-    #[link(name = "psapi")]
-    extern "system" {
-        fn GetCurrentProcess() -> HANDLE;
-        fn GetProcessMemoryInfo(
-            Process: HANDLE,
-            ppsmemCounters: PPROCESS_MEMORY_COUNTERS,
-            cb: DWORD,
-        ) -> BOOL;
-    }
-    let mut pmc: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() };
-    pmc.cb = std::mem::size_of_val(&pmc) as DWORD;
-    match unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, pmc.cb) } {
+    use std::mem::{self, MaybeUninit};
+    use winapi::shared::minwindef::DWORD;
+    use winapi::um::processthreadsapi::GetCurrentProcess;
+    use winapi::um::psapi::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
+
+    let mut pmc = MaybeUninit::<PROCESS_MEMORY_COUNTERS>::uninit();
+    match unsafe {
+        GetProcessMemoryInfo(GetCurrentProcess(), pmc.as_mut_ptr(), mem::size_of_val(&pmc) as DWORD)
+    } {
         0 => None,
-        _ => Some(pmc.WorkingSetSize as usize),
+        _ => {
+            let pmc = unsafe { pmc.assume_init() };
+            Some(pmc.WorkingSetSize as usize)
+        }
     }
 }
diff --git a/src/librustc_driver/Cargo.toml b/src/librustc_driver/Cargo.toml
index 37449f9402e..b856e5da5a0 100644
--- a/src/librustc_driver/Cargo.toml
+++ b/src/librustc_driver/Cargo.toml
@@ -32,5 +32,8 @@ rustc_serialize = { path = "../libserialize", package = "serialize" }
 syntax = { path = "../libsyntax" }
 rustc_span = { path = "../librustc_span" }
 
+[target.'cfg(windows)'.dependencies]
+winapi = { version = "0.3", features = ["consoleapi", "debugapi", "processenv"] }
+
 [features]
 llvm = ['rustc_interface/llvm']
diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs
index 3d31f240a34..5aba824e32c 100644
--- a/src/librustc_driver/lib.rs
+++ b/src/librustc_driver/lib.rs
@@ -515,15 +515,10 @@ fn stdout_isatty() -> bool {
 
 #[cfg(windows)]
 fn stdout_isatty() -> bool {
-    type DWORD = u32;
-    type BOOL = i32;
-    type HANDLE = *mut u8;
-    type LPDWORD = *mut u32;
-    const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
-    extern "system" {
-        fn GetStdHandle(which: DWORD) -> HANDLE;
-        fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
-    }
+    use winapi::um::consoleapi::GetConsoleMode;
+    use winapi::um::processenv::GetStdHandle;
+    use winapi::um::winbase::STD_OUTPUT_HANDLE;
+
     unsafe {
         let handle = GetStdHandle(STD_OUTPUT_HANDLE);
         let mut out = 0;
@@ -1215,11 +1210,8 @@ pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
     #[cfg(windows)]
     unsafe {
         if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
-            extern "system" {
-                fn DebugBreak();
-            }
             // Trigger a debugger if we crashed during bootstrap
-            DebugBreak();
+            winapi::um::debugapi::DebugBreak();
         }
     }
 }
diff --git a/src/librustc_errors/Cargo.toml b/src/librustc_errors/Cargo.toml
index 0d0989677c5..01ea80659d6 100644
--- a/src/librustc_errors/Cargo.toml
+++ b/src/librustc_errors/Cargo.toml
@@ -19,3 +19,6 @@ atty = "0.2"
 termcolor = "1.0"
 annotate-snippets = "0.6.1"
 term_size = "0.3.1"
+
+[target.'cfg(windows)'.dependencies]
+winapi = { version = "0.3", features = ["handleapi", "synchapi", "winbase"] }
diff --git a/src/librustc_errors/lock.rs b/src/librustc_errors/lock.rs
index 198a9c12406..a73472021d4 100644
--- a/src/librustc_errors/lock.rs
+++ b/src/librustc_errors/lock.rs
@@ -12,31 +12,14 @@
 use std::any::Any;
 
 #[cfg(windows)]
-#[allow(nonstandard_style)]
 pub fn acquire_global_lock(name: &str) -> Box<dyn Any> {
     use std::ffi::CString;
     use std::io;
 
-    type LPSECURITY_ATTRIBUTES = *mut u8;
-    type BOOL = i32;
-    type LPCSTR = *const u8;
-    type HANDLE = *mut u8;
-    type DWORD = u32;
-
-    const INFINITE: DWORD = !0;
-    const WAIT_OBJECT_0: DWORD = 0;
-    const WAIT_ABANDONED: DWORD = 0x00000080;
-
-    extern "system" {
-        fn CreateMutexA(
-            lpMutexAttributes: LPSECURITY_ATTRIBUTES,
-            bInitialOwner: BOOL,
-            lpName: LPCSTR,
-        ) -> HANDLE;
-        fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
-        fn ReleaseMutex(hMutex: HANDLE) -> BOOL;
-        fn CloseHandle(hObject: HANDLE) -> BOOL;
-    }
+    use winapi::shared::ntdef::HANDLE;
+    use winapi::um::handleapi::CloseHandle;
+    use winapi::um::synchapi::{CreateMutexA, ReleaseMutex, WaitForSingleObject};
+    use winapi::um::winbase::{INFINITE, WAIT_ABANDONED, WAIT_OBJECT_0};
 
     struct Handle(HANDLE);
 
@@ -65,7 +48,7 @@ pub fn acquire_global_lock(name: &str) -> Box<dyn Any> {
         //
         // This will silently create one if it doesn't already exist, or it'll
         // open up a handle to one if it already exists.
-        let mutex = CreateMutexA(std::ptr::null_mut(), 0, cname.as_ptr() as *const u8);
+        let mutex = CreateMutexA(std::ptr::null_mut(), 0, cname.as_ptr());
         if mutex.is_null() {
             panic!(
                 "failed to create global mutex named `{}`: {}",
diff --git a/src/librustc_interface/Cargo.toml b/src/librustc_interface/Cargo.toml
index eb0551c6065..548985c4514 100644
--- a/src/librustc_interface/Cargo.toml
+++ b/src/librustc_interface/Cargo.toml
@@ -42,6 +42,9 @@ rustc_resolve = { path = "../librustc_resolve" }
 tempfile = "3.0.5"
 once_cell = "1"
 
+[target.'cfg(windows)'.dependencies]
+winapi = { version = "0.3", features = ["libloaderapi"] }
+
 [dev-dependencies]
 rustc_target = { path = "../librustc_target" }
 
diff --git a/src/librustc_interface/util.rs b/src/librustc_interface/util.rs
index 2fafd3af7a5..21f9fa48165 100644
--- a/src/librustc_interface/util.rs
+++ b/src/librustc_interface/util.rs
@@ -340,19 +340,17 @@ fn sysroot_candidates() -> Vec<PathBuf> {
     fn current_dll_path() -> Option<PathBuf> {
         use std::ffi::OsString;
         use std::os::windows::prelude::*;
+        use std::ptr;
 
-        extern "system" {
-            fn GetModuleHandleExW(dwFlags: u32, lpModuleName: usize, phModule: *mut usize) -> i32;
-            fn GetModuleFileNameW(hModule: usize, lpFilename: *mut u16, nSize: u32) -> u32;
-        }
-
-        const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004;
+        use winapi::um::libloaderapi::{
+            GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
+        };
 
         unsafe {
-            let mut module = 0;
+            let mut module = ptr::null_mut();
             let r = GetModuleHandleExW(
                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
-                current_dll_path as usize,
+                current_dll_path as usize as *mut _,
                 &mut module,
             );
             if r == 0 {
diff --git a/src/librustc_metadata/Cargo.toml b/src/librustc_metadata/Cargo.toml
index 48767c377a9..0a0bcb190be 100644
--- a/src/librustc_metadata/Cargo.toml
+++ b/src/librustc_metadata/Cargo.toml
@@ -27,3 +27,6 @@ rustc_expand = { path = "../librustc_expand" }
 rustc_parse = { path = "../librustc_parse" }
 rustc_span = { path = "../librustc_span" }
 rustc_error_codes = { path = "../librustc_error_codes" }
+
+[target.'cfg(windows)'.dependencies]
+winapi = { version = "0.3", features = ["errhandlingapi", "libloaderapi"] }
diff --git a/src/librustc_metadata/dynamic_lib.rs b/src/librustc_metadata/dynamic_lib.rs
index fa4983d8a81..f04d0239d49 100644
--- a/src/librustc_metadata/dynamic_lib.rs
+++ b/src/librustc_metadata/dynamic_lib.rs
@@ -111,9 +111,9 @@ mod dl {
     ) -> Result<*mut u8, String> {
         check_for_errors_in(|| libc::dlsym(handle as *mut libc::c_void, symbol) as *mut u8)
     }
+
     pub(super) unsafe fn close(handle: *mut u8) {
         libc::dlclose(handle as *mut libc::c_void);
-        ()
     }
 }
 
@@ -124,27 +124,15 @@ mod dl {
     use std::os::windows::prelude::*;
     use std::ptr;
 
-    use libc::{c_char, c_uint, c_void};
-
-    type DWORD = u32;
-    type HMODULE = *mut u8;
-    type BOOL = i32;
-    type LPCWSTR = *const u16;
-    type LPCSTR = *const i8;
-
-    extern "system" {
-        fn SetThreadErrorMode(dwNewMode: DWORD, lpOldMode: *mut DWORD) -> c_uint;
-        fn LoadLibraryW(name: LPCWSTR) -> HMODULE;
-        fn GetModuleHandleExW(dwFlags: DWORD, name: LPCWSTR, handle: *mut HMODULE) -> BOOL;
-        fn GetProcAddress(handle: HMODULE, name: LPCSTR) -> *mut c_void;
-        fn FreeLibrary(handle: HMODULE) -> BOOL;
-    }
+    use winapi::shared::minwindef::HMODULE;
+    use winapi::um::errhandlingapi::SetThreadErrorMode;
+    use winapi::um::libloaderapi::{FreeLibrary, GetModuleHandleExW, GetProcAddress, LoadLibraryW};
+    use winapi::um::winbase::SEM_FAILCRITICALERRORS;
 
     pub(super) fn open(filename: Option<&OsStr>) -> Result<*mut u8, String> {
         // disable "dll load failed" error dialog.
         let prev_error_mode = unsafe {
-            // SEM_FAILCRITICALERRORS 0x01
-            let new_error_mode = 1;
+            let new_error_mode = SEM_FAILCRITICALERRORS;
             let mut prev_error_mode = 0;
             let result = SetThreadErrorMode(new_error_mode, &mut prev_error_mode);
             if result == 0 {
@@ -156,12 +144,12 @@ mod dl {
         let result = match filename {
             Some(filename) => {
                 let filename_str: Vec<_> = filename.encode_wide().chain(Some(0)).collect();
-                let result = unsafe { LoadLibraryW(filename_str.as_ptr()) };
+                let result = unsafe { LoadLibraryW(filename_str.as_ptr()) } as *mut u8;
                 ptr_result(result)
             }
             None => {
                 let mut handle = ptr::null_mut();
-                let succeeded = unsafe { GetModuleHandleExW(0 as DWORD, ptr::null(), &mut handle) };
+                let succeeded = unsafe { GetModuleHandleExW(0, ptr::null(), &mut handle) };
                 if succeeded == 0 {
                     Err(io::Error::last_os_error().to_string())
                 } else {
@@ -177,7 +165,10 @@ mod dl {
         result
     }
 
-    pub(super) unsafe fn symbol(handle: *mut u8, symbol: *const c_char) -> Result<*mut u8, String> {
+    pub(super) unsafe fn symbol(
+        handle: *mut u8,
+        symbol: *const libc::c_char,
+    ) -> Result<*mut u8, String> {
         let ptr = GetProcAddress(handle as HMODULE, symbol) as *mut u8;
         ptr_result(ptr)
     }
diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs
index 1912c9ef5ba..3a114a0b715 100644
--- a/src/tools/compiletest/src/runtest.rs
+++ b/src/tools/compiletest/src/runtest.rs
@@ -42,10 +42,8 @@ mod tests;
 #[cfg(windows)]
 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
     use std::sync::Mutex;
-    const SEM_NOGPFAULTERRORBOX: u32 = 0x0002;
-    extern "system" {
-        fn SetErrorMode(mode: u32) -> u32;
-    }
+    use winapi::um::errhandlingapi::SetErrorMode;
+    use winapi::um::winbase::SEM_NOGPFAULTERRORBOX;
 
     lazy_static! {
         static ref LOCK: Mutex<()> = { Mutex::new(()) };