Refact, replace GetLastError() by std::io::Error::last_os_error()

Signed-off-by: fufesou <shuanglongchen@yeah.net>
This commit is contained in:
fufesou 2023-11-20 17:15:15 +08:00
parent 9c12c3ee4e
commit c85682de8d
5 changed files with 102 additions and 67 deletions

@ -139,9 +139,9 @@ impl MagInterface {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!( format!(
"Failed to LoadLibraryExA {}, error: {}", "Failed to LoadLibraryExA {}, error: {:?}",
lib_file_name, lib_file_name,
GetLastError() Error::last_os_error()
), ),
)); ));
}; };
@ -173,7 +173,7 @@ impl MagInterface {
if FALSE == init_func() { if FALSE == init_func() {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!("Failed to MagInitialize, error: {}", GetLastError()), format!("Failed to MagInitialize, error: {:?}", Error::last_os_error()),
)); ));
} else { } else {
s.init_succeeded = true; s.init_succeeded = true;
@ -195,9 +195,9 @@ impl MagInterface {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!( format!(
"Failed to GetProcAddress {}, error: {}", "Failed to GetProcAddress {}, error {:?}",
func_name, func_name,
GetLastError() Error::last_os_error()
), ),
)); ));
} }
@ -209,14 +209,14 @@ impl MagInterface {
if let Some(uninit_func) = self.mag_uninitialize_func { if let Some(uninit_func) = self.mag_uninitialize_func {
unsafe { unsafe {
if FALSE == uninit_func() { if FALSE == uninit_func() {
println!("Failed MagUninitialize {}", GetLastError()) println!("Failed MagUninitialize, error {:?}", Error::last_os_error())
} }
} }
} }
if !self.lib_handle.is_null() { if !self.lib_handle.is_null() {
unsafe { unsafe {
if FALSE == FreeLibrary(self.lib_handle) { if FALSE == FreeLibrary(self.lib_handle) {
println!("Failed FreeLibrary {}", GetLastError()) println!("Failed FreeLibrary, error {:?}", Error::last_os_error())
} }
} }
self.lib_handle = NULL as _; self.lib_handle = NULL as _;
@ -315,7 +315,7 @@ impl CapturerMag {
) { ) {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!("Failed to GetModuleHandleExA, error: {}", GetLastError()), format!("Failed to GetModuleHandleExA, error {:?}", Error::last_os_error()),
)); ));
} }
@ -366,8 +366,8 @@ impl CapturerMag {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!( format!(
"Failed to CreateWindowExA host_window, error: {}", "Failed to CreateWindowExA host_window, error {:?}",
GetLastError() Error::last_os_error()
), ),
)); ));
} }
@ -391,8 +391,8 @@ impl CapturerMag {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!( format!(
"Failed CreateWindowA magnifier_window, error: {}", "Failed CreateWindowA magnifier_window, error {:?}",
GetLastError() Error::last_os_error()
), ),
)); ));
} }
@ -411,8 +411,8 @@ impl CapturerMag {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!( format!(
"Failed to MagSetImageScalingCallback, error: {}", "Failed to MagSetImageScalingCallback, error {:?}",
GetLastError() Error::last_os_error()
), ),
)); ));
} }
@ -455,10 +455,10 @@ impl CapturerMag {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!( format!(
"Failed MagSetWindowFilterList for cls {} name {}, err: {}", "Failed MagSetWindowFilterList for cls {} name {}, error {:?}",
cls, cls,
name, name,
GetLastError() Error::last_os_error()
), ),
)); ));
} }
@ -530,12 +530,12 @@ impl CapturerMag {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!( format!(
"Failed SetWindowPos (x, y, w , h) - ({}, {}, {}, {}), error {}", "Failed SetWindowPos (x, y, w , h) - ({}, {}, {}, {}), error {:?}",
self.rect.left, self.rect.left,
self.rect.top, self.rect.top,
self.rect.right - self.rect.left, self.rect.right - self.rect.left,
self.rect.bottom - self.rect.top, self.rect.bottom - self.rect.top,
GetLastError() Error::last_os_error()
), ),
)); ));
} }
@ -546,7 +546,7 @@ impl CapturerMag {
if FALSE == set_window_source_func(self.magnifier_window, self.rect) { if FALSE == set_window_source_func(self.magnifier_window, self.rect) {
return Err(Error::new( return Err(Error::new(
ErrorKind::Other, ErrorKind::Other,
format!("Failed to MagSetWindowSource, error: {}", GetLastError()), format!("Failed to MagSetWindowSource, error {:?}", Error::last_os_error()),
)); ));
} }
} else { } else {
@ -578,7 +578,7 @@ impl CapturerMag {
unsafe { unsafe {
if FALSE == DestroyWindow(self.magnifier_window) { if FALSE == DestroyWindow(self.magnifier_window) {
// //
println!("Failed DestroyWindow magnifier window {}", GetLastError()) println!("Failed DestroyWindow magnifier window, error {:?}", Error::last_os_error())
} }
} }
} }
@ -588,7 +588,7 @@ impl CapturerMag {
unsafe { unsafe {
if FALSE == DestroyWindow(self.host_window) { if FALSE == DestroyWindow(self.host_window) {
// //
println!("Failed DestroyWindow host window {}", GetLastError()) println!("Failed DestroyWindow host window, error {:?}", Error::last_os_error())
} }
} }
} }

@ -1285,7 +1285,7 @@ pub fn block_input(v: bool) -> (bool, String) {
if BlockInput(v) == TRUE { if BlockInput(v) == TRUE {
(true, "".to_owned()) (true, "".to_owned())
} else { } else {
(false, format!("Error code: {}", GetLastError())) (false, format!("Error: {:?}", io::Error::last_os_error()))
} }
} }
} }
@ -1559,9 +1559,10 @@ pub fn elevate_or_run_as_system(is_setup: bool, is_elevate: bool, is_run_as_syst
if run_as_system(arg_run_as_system).is_ok() { if run_as_system(arg_run_as_system).is_ok() {
std::process::exit(0); std::process::exit(0);
} else { } else {
unsafe { log::error!(
log::error!("Failed to run as system, errno = {}", GetLastError()); "Failed to run as system, error {:?}",
} io::Error::last_os_error()
);
} }
} }
} else { } else {
@ -1569,16 +1570,18 @@ pub fn elevate_or_run_as_system(is_setup: bool, is_elevate: bool, is_run_as_syst
if let Ok(true) = elevate(arg_elevate) { if let Ok(true) = elevate(arg_elevate) {
std::process::exit(0); std::process::exit(0);
} else { } else {
unsafe { log::error!(
log::error!("Failed to elevate, errno = {}", GetLastError()); "Failed to elevate, error {:?}",
} io::Error::last_os_error()
);
} }
} }
} }
} }
Err(_) => unsafe { Err(_) => log::error!(
log::error!("Failed to get elevation status, errno = {}", GetLastError()); "Failed to get elevation status, error {:?}",
}, io::Error::last_os_error()
),
} }
} }
} }
@ -1591,12 +1594,18 @@ pub fn is_elevated(process_id: Option<DWORD>) -> ResultType<bool> {
None => GetCurrentProcess(), None => GetCurrentProcess(),
}; };
if handle == NULL { if handle == NULL {
bail!("Failed to open process, errno {}", GetLastError()) bail!(
"Failed to open process, error {:?}",
io::Error::last_os_error()
)
} }
let _handle = RAIIHandle(handle); let _handle = RAIIHandle(handle);
let mut token: HANDLE = mem::zeroed(); let mut token: HANDLE = mem::zeroed();
if OpenProcessToken(handle, TOKEN_QUERY, &mut token) == FALSE { if OpenProcessToken(handle, TOKEN_QUERY, &mut token) == FALSE {
bail!("Failed to open process token, errno {}", GetLastError()) bail!(
"Failed to open process token, error {:?}",
io::Error::last_os_error()
)
} }
let _token = RAIIHandle(token); let _token = RAIIHandle(token);
let mut token_elevation: TOKEN_ELEVATION = mem::zeroed(); let mut token_elevation: TOKEN_ELEVATION = mem::zeroed();
@ -1609,7 +1618,10 @@ pub fn is_elevated(process_id: Option<DWORD>) -> ResultType<bool> {
&mut size, &mut size,
) == FALSE ) == FALSE
{ {
bail!("Failed to get token information, errno {}", GetLastError()) bail!(
"Failed to get token information, error {:?}",
io::Error::last_os_error()
)
} }
Ok(token_elevation.TokenIsElevated != 0) Ok(token_elevation.TokenIsElevated != 0)
@ -1621,7 +1633,10 @@ pub fn is_foreground_window_elevated() -> ResultType<bool> {
let mut process_id: DWORD = 0; let mut process_id: DWORD = 0;
GetWindowThreadProcessId(GetForegroundWindow(), &mut process_id); GetWindowThreadProcessId(GetForegroundWindow(), &mut process_id);
if process_id == 0 { if process_id == 0 {
bail!("Failed to get processId, errno {}", GetLastError()) bail!(
"Failed to get processId, error {}",
io::Error::last_os_error()
)
} }
is_elevated(Some(process_id)) is_elevated(Some(process_id))
} }
@ -1786,8 +1801,8 @@ pub fn current_resolution(name: &str) -> ResultType<Resolution> {
dm.dmSize = std::mem::size_of::<DEVMODEW>() as _; dm.dmSize = std::mem::size_of::<DEVMODEW>() as _;
if EnumDisplaySettingsW(device_name.as_ptr(), ENUM_CURRENT_SETTINGS, &mut dm) == 0 { if EnumDisplaySettingsW(device_name.as_ptr(), ENUM_CURRENT_SETTINGS, &mut dm) == 0 {
bail!( bail!(
"failed to get currrent resolution, errno={}", "failed to get currrent resolution, error {:?}",
GetLastError() io::Error::last_os_error()
); );
} }
let r = Resolution { let r = Resolution {
@ -1820,9 +1835,9 @@ pub(super) fn change_resolution_directly(
); );
if res != DISP_CHANGE_SUCCESSFUL { if res != DISP_CHANGE_SUCCESSFUL {
bail!( bail!(
"ChangeDisplaySettingsExW failed, res={}, errno={}", "ChangeDisplaySettingsExW failed, res={}, error {:?}",
res, res,
GetLastError() io::Error::last_os_error()
); );
} }
Ok(()) Ok(())

@ -1,7 +1,10 @@
use hbb_common::{allow_err, bail, lazy_static, log, ResultType}; use hbb_common::{allow_err, bail, lazy_static, log, ResultType};
use std::sync::{ use std::{
mpsc::{channel, Sender}, io::Error,
Mutex, sync::{
mpsc::{channel, Sender},
Mutex,
},
}; };
use winapi::{ use winapi::{
ctypes::c_int, ctypes::c_int,
@ -10,10 +13,7 @@ use winapi::{
ntdef::NULL, ntdef::NULL,
windef::{HHOOK, POINT}, windef::{HHOOK, POINT},
}, },
um::{ um::{libloaderapi::GetModuleHandleExA, processthreadsapi::GetCurrentThreadId, winuser::*},
errhandlingapi::GetLastError, libloaderapi::GetModuleHandleExA,
processthreadsapi::GetCurrentThreadId, winuser::*,
},
}; };
const GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT: u32 = 2; const GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT: u32 = 2;
@ -43,8 +43,8 @@ fn do_hook(tx: Sender<String>) -> ResultType<(HHOOK, HHOOK)> {
&mut hm_keyboard as _, &mut hm_keyboard as _,
) { ) {
tx.send(format!( tx.send(format!(
"Failed to GetModuleHandleExA, error: {}", "Failed to GetModuleHandleExA, error: {:?}",
GetLastError() Error::last_os_error()
))?; ))?;
return Ok(invalid_ret); return Ok(invalid_ret);
} }
@ -55,8 +55,8 @@ fn do_hook(tx: Sender<String>) -> ResultType<(HHOOK, HHOOK)> {
&mut hm_mouse as _, &mut hm_mouse as _,
) { ) {
tx.send(format!( tx.send(format!(
"Failed to GetModuleHandleExA, error: {}", "Failed to GetModuleHandleExA, error: {:?}",
GetLastError() Error::last_os_error()
))?; ))?;
return Ok(invalid_ret); return Ok(invalid_ret);
} }
@ -68,7 +68,10 @@ fn do_hook(tx: Sender<String>) -> ResultType<(HHOOK, HHOOK)> {
0, 0,
); );
if hook_keyboard.is_null() { if hook_keyboard.is_null() {
tx.send(format!(" SetWindowsHookExA keyboard {}", GetLastError()))?; tx.send(format!(
" SetWindowsHookExA keyboard, error {:?}",
Error::last_os_error()
))?;
return Ok(invalid_ret); return Ok(invalid_ret);
} }
@ -76,9 +79,15 @@ fn do_hook(tx: Sender<String>) -> ResultType<(HHOOK, HHOOK)> {
if hook_mouse.is_null() { if hook_mouse.is_null() {
if FALSE == UnhookWindowsHookEx(hook_keyboard) { if FALSE == UnhookWindowsHookEx(hook_keyboard) {
// Fatal error // Fatal error
log::error!(" UnhookWindowsHookEx keyboard {}", GetLastError()); log::error!(
" UnhookWindowsHookEx keyboard, error {:?}",
Error::last_os_error()
);
} }
tx.send(format!(" SetWindowsHookExA mouse {}", GetLastError()))?; tx.send(format!(
" SetWindowsHookExA mouse, error {:?}",
Error::last_os_error()
))?;
return Ok(invalid_ret); return Ok(invalid_ret);
} }
@ -131,12 +140,18 @@ pub fn hook() -> ResultType<()> {
if FALSE == UnhookWindowsHookEx(hook_keyboard as _) { if FALSE == UnhookWindowsHookEx(hook_keyboard as _) {
// Fatal error // Fatal error
log::error!("Failed UnhookWindowsHookEx keyboard {}", GetLastError()); log::error!(
"Failed UnhookWindowsHookEx keyboard, error {:?}",
Error::last_os_error()
);
} }
if FALSE == UnhookWindowsHookEx(hook_mouse as _) { if FALSE == UnhookWindowsHookEx(hook_mouse as _) {
// Fatal error // Fatal error
log::error!("Failed UnhookWindowsHookEx mouse {}", GetLastError()); log::error!(
"Failed UnhookWindowsHookEx mouse, error {:?}",
Error::last_os_error()
);
} }
*CUR_HOOK_THREAD_ID.lock().unwrap() = 0; *CUR_HOOK_THREAD_ID.lock().unwrap() = 0;
@ -162,7 +177,10 @@ pub fn unhook() -> ResultType<()> {
let cur_hook_thread_id = CUR_HOOK_THREAD_ID.lock().unwrap(); let cur_hook_thread_id = CUR_HOOK_THREAD_ID.lock().unwrap();
if *cur_hook_thread_id != 0 { if *cur_hook_thread_id != 0 {
if FALSE == PostThreadMessageA(*cur_hook_thread_id, WM_USER_EXIT_HOOK, 0, 0) { if FALSE == PostThreadMessageA(*cur_hook_thread_id, WM_USER_EXIT_HOOK, 0, 0) {
bail!("Failed to post message to exit hook, {}", GetLastError()); bail!(
"Failed to post message to exit hook, error {:?}",
Error::last_os_error()
);
} }
} }
} }

@ -3,6 +3,7 @@ use crate::{platform::windows::get_user_token, privacy_mode::PrivacyModeState};
use hbb_common::{allow_err, bail, log, ResultType}; use hbb_common::{allow_err, bail, log, ResultType};
use std::{ use std::{
ffi::CString, ffi::CString,
io::Error,
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use winapi::{ use winapi::{
@ -12,7 +13,6 @@ use winapi::{
windef::HWND, windef::HWND,
}, },
um::{ um::{
errhandlingapi::GetLastError,
handleapi::CloseHandle, handleapi::CloseHandle,
libloaderapi::{GetModuleHandleA, GetProcAddress}, libloaderapi::{GetModuleHandleA, GetProcAddress},
memoryapi::{VirtualAllocEx, WriteProcessMemory}, memoryapi::{VirtualAllocEx, WriteProcessMemory},
@ -266,9 +266,9 @@ impl PrivacyModeImpl {
CloseHandle(token); CloseHandle(token);
if 0 == create_res { if 0 == create_res {
bail!( bail!(
"Failed to create privacy window process {}, code {}", "Failed to create privacy window process {}, error {:?}",
cmdline, cmdline,
GetLastError() Error::last_os_error()
); );
}; };
@ -284,8 +284,8 @@ impl PrivacyModeImpl {
CloseHandle(proc_info.hProcess); CloseHandle(proc_info.hProcess);
bail!( bail!(
"Failed to create privacy window process, {}", "Failed to create privacy window process, error {:?}",
GetLastError() Error::last_os_error()
); );
} }

@ -1,7 +1,10 @@
use super::{PrivacyMode, PrivacyModeState, INVALID_PRIVACY_MODE_CONN_ID, NO_DISPLAYS}; use super::{PrivacyMode, PrivacyModeState, INVALID_PRIVACY_MODE_CONN_ID, NO_DISPLAYS};
use crate::virtual_display_manager; use crate::virtual_display_manager;
use hbb_common::{allow_err, bail, config::Config, log, ResultType}; use hbb_common::{allow_err, bail, config::Config, log, ResultType};
use std::ops::{Deref, DerefMut}; use std::{
io::Error,
ops::{Deref, DerefMut},
};
use virtual_display::MonitorMode; use virtual_display::MonitorMode;
use winapi::{ use winapi::{
shared::{ shared::{
@ -9,7 +12,6 @@ use winapi::{
ntdef::{NULL, WCHAR}, ntdef::{NULL, WCHAR},
}, },
um::{ um::{
errhandlingapi::GetLastError,
wingdi::{ wingdi::{
DEVMODEW, DISPLAY_DEVICEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICE_ATTACHED_TO_DESKTOP, DEVMODEW, DISPLAY_DEVICEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICE_ATTACHED_TO_DESKTOP,
DISPLAY_DEVICE_MIRRORING_DRIVER, DISPLAY_DEVICE_PRIMARY_DEVICE, DM_POSITION, DISPLAY_DEVICE_MIRRORING_DRIVER, DISPLAY_DEVICE_PRIMARY_DEVICE, DM_POSITION,
@ -193,9 +195,9 @@ impl PrivacyModeImpl {
) )
{ {
bail!( bail!(
"Failed EnumDisplaySettingsW, device name: {:?}, error code: {}", "Failed EnumDisplaySettingsW, device name: {:?}, error: {:?}",
std::string::String::from_utf16(&display.name), std::string::String::from_utf16(&display.name),
GetLastError() Error::last_os_error()
); );
} }
@ -227,9 +229,9 @@ impl PrivacyModeImpl {
== EnumDisplaySettingsW(dd.DeviceName.as_ptr(), ENUM_CURRENT_SETTINGS, &mut dm) == EnumDisplaySettingsW(dd.DeviceName.as_ptr(), ENUM_CURRENT_SETTINGS, &mut dm)
{ {
bail!( bail!(
"Failed EnumDisplaySettingsW, device name: {:?}, error code: {}", "Failed EnumDisplaySettingsW, device name: {:?}, error: {:?}",
std::string::String::from_utf16(&dd.DeviceName), std::string::String::from_utf16(&dd.DeviceName),
GetLastError() Error::last_os_error()
); );
} }