chore: fix Windows specific clippy errors (#15212)

This commit is contained in:
David Sherret 2022-07-15 12:30:25 -04:00 committed by GitHub
parent ee0c0586b3
commit 635eed9373
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 91 additions and 58 deletions

View file

@ -133,6 +133,7 @@ mod dirs {
use winapi::um::{combaseapi, knownfolders, shlobj, shtypes, winbase, winnt}; use winapi::um::{combaseapi, knownfolders, shlobj, shtypes, winbase, winnt};
fn known_folder(folder_id: shtypes::REFKNOWNFOLDERID) -> Option<PathBuf> { fn known_folder(folder_id: shtypes::REFKNOWNFOLDERID) -> Option<PathBuf> {
// SAFETY: winapi calls
unsafe { unsafe {
let mut path_ptr: winnt::PWSTR = std::ptr::null_mut(); let mut path_ptr: winnt::PWSTR = std::ptr::null_mut();
let result = shlobj::SHGetKnownFolderPath( let result = shlobj::SHGetKnownFolderPath(

View file

@ -39,6 +39,7 @@ fn is_process_active(process_id: u32) -> bool {
use winapi::um::synchapi::WaitForSingleObject; use winapi::um::synchapi::WaitForSingleObject;
use winapi::um::winnt::SYNCHRONIZE; use winapi::um::winnt::SYNCHRONIZE;
// SAFETY: winapi calls
unsafe { unsafe {
let process = OpenProcess(SYNCHRONIZE, FALSE, process_id as DWORD); let process = OpenProcess(SYNCHRONIZE, FALSE, process_id as DWORD);
let result = if process == NULL { let result = if process == NULL {

View file

@ -5,6 +5,7 @@
/// constructed from a stdio handle; if the handle is null this causes a panic. /// constructed from a stdio handle; if the handle is null this causes a panic.
pub fn ensure_stdio_open() { pub fn ensure_stdio_open() {
#[cfg(windows)] #[cfg(windows)]
// SAFETY: winapi calls
unsafe { unsafe {
use std::mem::size_of; use std::mem::size_of;
use winapi::shared::minwindef::DWORD; use winapi::shared::minwindef::DWORD;

View file

@ -1,8 +1,9 @@
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use std::env; #[cfg(not(target_os = "windows"))]
fn build_tcc() { fn build_tcc() {
use std::env;
{ {
// TODO(@littledivy): Windows support for fast call. // TODO(@littledivy): Windows support for fast call.
// let tcc_path = root // let tcc_path = root
@ -58,6 +59,8 @@ fn main() {}
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
fn main() { fn main() {
use std::env;
if let Ok(tcc_path) = env::var("TCC_PATH") { if let Ok(tcc_path) = env::var("TCC_PATH") {
println!("cargo:rustc-link-search=native={}", tcc_path); println!("cargo:rustc-link-search=native={}", tcc_path);
} else { } else {

View file

@ -518,8 +518,10 @@ pub(crate) fn format_error(e: dlopen::Error, path: String) -> String {
let arguments = [path.as_ptr()]; let arguments = [path.as_ptr()];
loop { loop {
unsafe { // SAFETY:
let length = FormatMessageW( // winapi call to format the error message
let length = unsafe {
FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
std::ptr::null_mut(), std::ptr::null_mut(),
err_num as DWORD, err_num as DWORD,
@ -527,22 +529,24 @@ pub(crate) fn format_error(e: dlopen::Error, path: String) -> String {
buf.as_mut_ptr(), buf.as_mut_ptr(),
buf.len() as DWORD, buf.len() as DWORD,
arguments.as_ptr() as _, arguments.as_ptr() as _,
); )
};
if length == 0 { if length == 0 {
let err_num = GetLastError(); // SAFETY:
if err_num == ERROR_INSUFFICIENT_BUFFER { // winapi call to get the last error message
buf.resize(buf.len() * 2, 0); let err_num = unsafe { GetLastError() };
continue; if err_num == ERROR_INSUFFICIENT_BUFFER {
} buf.resize(buf.len() * 2, 0);
continue;
// Something went wrong, just return the original error.
return e.to_string();
} }
let msg = String::from_utf16_lossy(&buf[..length as usize]); // Something went wrong, just return the original error.
return msg; return e.to_string();
} }
let msg = String::from_utf16_lossy(&buf[..length as usize]);
return msg;
} }
} }
_ => e.to_string(), _ => e.to_string(),

View file

@ -318,21 +318,26 @@ pub fn kill(pid: i32, signal: &str) -> Result<(), AnyError> {
} else if pid <= 0 { } else if pid <= 0 {
Err(type_error("Invalid pid")) Err(type_error("Invalid pid"))
} else { } else {
// SAFETY: winapi call
let handle = unsafe { OpenProcess(PROCESS_TERMINATE, FALSE, pid as DWORD) }; let handle = unsafe { OpenProcess(PROCESS_TERMINATE, FALSE, pid as DWORD) };
if handle.is_null() { if handle.is_null() {
// SAFETY: winapi call
let err = match unsafe { GetLastError() } { let err = match unsafe { GetLastError() } {
ERROR_INVALID_PARAMETER => Error::from(NotFound), // Invalid `pid`. ERROR_INVALID_PARAMETER => Error::from(NotFound), // Invalid `pid`.
errno => Error::from_raw_os_error(errno as i32), errno => Error::from_raw_os_error(errno as i32),
}; };
Err(err.into()) Err(err.into())
} else { } else {
let is_terminated = unsafe { TerminateProcess(handle, 1) }; // SAFETY: winapi calls
unsafe { CloseHandle(handle) }; unsafe {
match is_terminated { let is_terminated = TerminateProcess(handle, 1);
FALSE => Err(Error::last_os_error().into()), CloseHandle(handle);
TRUE => Ok(()), match is_terminated {
_ => unreachable!(), FALSE => Err(Error::last_os_error().into()),
TRUE => Ok(()),
_ => unreachable!(),
}
} }
} }
} }

View file

@ -51,6 +51,7 @@ pub fn ppid() -> i64 {
CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32,
TH32CS_SNAPPROCESS, TH32CS_SNAPPROCESS,
}; };
// SAFETY: winapi calls
unsafe { unsafe {
// Take a snapshot of system processes, one of which is ours // Take a snapshot of system processes, one of which is ours
// and contains our parent's pid // and contains our parent's pid

View file

@ -95,6 +95,7 @@ fn op_set_raw(state: &mut OpState, args: SetRawArgs) -> Result<(), AnyError> {
return Err(custom_error("ReferenceError", "null handle")); return Err(custom_error("ReferenceError", "null handle"));
} }
let mut original_mode: DWORD = 0; let mut original_mode: DWORD = 0;
// SAFETY: winapi call
if unsafe { consoleapi::GetConsoleMode(handle, &mut original_mode) } if unsafe { consoleapi::GetConsoleMode(handle, &mut original_mode) }
== FALSE == FALSE
{ {
@ -105,6 +106,7 @@ fn op_set_raw(state: &mut OpState, args: SetRawArgs) -> Result<(), AnyError> {
} else { } else {
original_mode | RAW_MODE_MASK original_mode | RAW_MODE_MASK
}; };
// SAFETY: winapi call
if unsafe { consoleapi::SetConsoleMode(handle, new_mode) } == FALSE { if unsafe { consoleapi::SetConsoleMode(handle, new_mode) } == FALSE {
return Err(Error::last_os_error().into()); return Err(Error::last_os_error().into());
} }
@ -210,6 +212,7 @@ fn op_console_size(
use std::os::windows::io::AsRawHandle; use std::os::windows::io::AsRawHandle;
let handle = std_file.as_raw_handle(); let handle = std_file.as_raw_handle();
// SAFETY: winapi calls
unsafe { unsafe {
let mut bufinfo: winapi::um::wincon::CONSOLE_SCREEN_BUFFER_INFO = let mut bufinfo: winapi::um::wincon::CONSOLE_SCREEN_BUFFER_INFO =
std::mem::zeroed(); std::mem::zeroed();

View file

@ -1912,6 +1912,7 @@ fn permission_prompt(message: &str, name: &str) -> bool {
use winapi::um::winuser::MAPVK_VK_TO_VSC; use winapi::um::winuser::MAPVK_VK_TO_VSC;
use winapi::um::winuser::VK_RETURN; use winapi::um::winuser::VK_RETURN;
// SAFETY: winapi calls
unsafe { unsafe {
let stdin = GetStdHandle(STD_INPUT_HANDLE); let stdin = GetStdHandle(STD_INPUT_HANDLE);
// emulate an enter key press to clear any line buffered console characters // emulate an enter key press to clear any line buffered console characters

View file

@ -153,6 +153,8 @@ mod windows {
maybe_env_vars: Option<HashMap<String, String>>, maybe_env_vars: Option<HashMap<String, String>>,
) -> Self { ) -> Self {
// https://docs.microsoft.com/en-us/windows/console/creating-a-pseudoconsole-session // https://docs.microsoft.com/en-us/windows/console/creating-a-pseudoconsole-session
// SAFETY:
// Generous use of winapi to create a PTY (thus large unsafe block).
unsafe { unsafe {
let mut size: COORD = std::mem::zeroed(); let mut size: COORD = std::mem::zeroed();
size.X = 800; size.X = 800;
@ -238,22 +240,24 @@ mod windows {
impl Read for WinPseudoConsole { impl Read for WinPseudoConsole {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
unsafe { loop {
loop { let mut bytes_read = 0;
let mut bytes_read = 0; // SAFETY:
let success = ReadFile( // winapi call
let success = unsafe {
ReadFile(
self.stdout_read_handle.as_raw_handle(), self.stdout_read_handle.as_raw_handle(),
buf.as_mut_ptr() as _, buf.as_mut_ptr() as _,
buf.len() as u32, buf.len() as u32,
&mut bytes_read, &mut bytes_read,
ptr::null_mut(), ptr::null_mut(),
); )
};
// ignore zero-byte writes // ignore zero-byte writes
let is_zero_byte_write = bytes_read == 0 && success == TRUE; let is_zero_byte_write = bytes_read == 0 && success == TRUE;
if !is_zero_byte_write { if !is_zero_byte_write {
return Ok(bytes_read as usize); return Ok(bytes_read as usize);
}
} }
} }
} }
@ -271,17 +275,19 @@ mod windows {
impl std::io::Write for WinPseudoConsole { impl std::io::Write for WinPseudoConsole {
fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> { fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
unsafe { let mut bytes_written = 0;
let mut bytes_written = 0; // SAFETY:
assert_win_success!(WriteFile( // winapi call
assert_win_success!(unsafe {
WriteFile(
self.stdin_write_handle.as_raw_handle(), self.stdin_write_handle.as_raw_handle(),
buffer.as_ptr() as *const _, buffer.as_ptr() as *const _,
buffer.len() as u32, buffer.len() as u32,
&mut bytes_written, &mut bytes_written,
ptr::null_mut(), ptr::null_mut(),
)); )
Ok(bytes_written as usize) });
} Ok(bytes_written as usize)
} }
fn flush(&mut self) -> std::io::Result<()> { fn flush(&mut self) -> std::io::Result<()> {
@ -299,10 +305,14 @@ mod windows {
} }
pub fn duplicate(&self) -> WinHandle { pub fn duplicate(&self) -> WinHandle {
unsafe { // SAFETY:
let process_handle = GetCurrentProcess(); // winapi call
let mut duplicate_handle = ptr::null_mut(); let process_handle = unsafe { GetCurrentProcess() };
assert_win_success!(DuplicateHandle( let mut duplicate_handle = ptr::null_mut();
// SAFETY:
// winapi call
assert_win_success!(unsafe {
DuplicateHandle(
process_handle, process_handle,
self.inner, self.inner,
process_handle, process_handle,
@ -310,10 +320,10 @@ mod windows {
0, 0,
0, 0,
DUPLICATE_SAME_ACCESS, DUPLICATE_SAME_ACCESS,
)); )
});
WinHandle::new(duplicate_handle) WinHandle::new(duplicate_handle)
}
} }
pub fn as_raw_handle(&self) -> HANDLE { pub fn as_raw_handle(&self) -> HANDLE {
@ -333,8 +343,10 @@ mod windows {
impl Drop for WinHandle { impl Drop for WinHandle {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { if !self.inner.is_null() && self.inner != INVALID_HANDLE_VALUE {
if !self.inner.is_null() && self.inner != INVALID_HANDLE_VALUE { // SAFETY:
// winapi call
unsafe {
winapi::um::handleapi::CloseHandle(self.inner); winapi::um::handleapi::CloseHandle(self.inner);
} }
} }
@ -347,6 +359,8 @@ mod windows {
impl ProcThreadAttributeList { impl ProcThreadAttributeList {
pub fn new(console_handle: HPCON) -> Self { pub fn new(console_handle: HPCON) -> Self {
// SAFETY:
// Generous use of unsafe winapi calls to create a ProcThreadAttributeList.
unsafe { unsafe {
// discover size required for the list // discover size required for the list
let mut size = 0; let mut size = 0;
@ -393,24 +407,23 @@ mod windows {
impl Drop for ProcThreadAttributeList { impl Drop for ProcThreadAttributeList {
fn drop(&mut self) { fn drop(&mut self) {
// SAFETY:
// winapi call
unsafe { DeleteProcThreadAttributeList(self.as_mut_ptr()) }; unsafe { DeleteProcThreadAttributeList(self.as_mut_ptr()) };
} }
} }
fn create_pipe() -> (WinHandle, WinHandle) { fn create_pipe() -> (WinHandle, WinHandle) {
unsafe { let mut read_handle = std::ptr::null_mut();
let mut read_handle = std::ptr::null_mut(); let mut write_handle = std::ptr::null_mut();
let mut write_handle = std::ptr::null_mut();
assert_win_success!(CreatePipe( // SAFETY:
&mut read_handle, // Creating an anonymous pipe with winapi.
&mut write_handle, assert_win_success!(unsafe {
ptr::null_mut(), CreatePipe(&mut read_handle, &mut write_handle, ptr::null_mut(), 0)
0 });
));
(WinHandle::new(read_handle), WinHandle::new(write_handle)) (WinHandle::new(read_handle), WinHandle::new(write_handle))
}
} }
fn to_windows_str(str: &str) -> Vec<u16> { fn to_windows_str(str: &str) -> Vec<u16> {