#![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] #![allow(clippy::too_many_arguments)] use std::ffi::{CStr, c_char, c_void}; use std::os::windows::ffi::OsStrExt; use std::path::Path; use std::sync::{Mutex, MutexGuard}; use windows_sys::Win32::Globalization::{CP_ACP, MultiByteToWideChar}; use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives; use crate::hle::{HleExport, HleModule}; use crate::hle_export; macro_rules! host { ($dll:literal, $name:literal: $ty:ty) => {{ static ADDRESS: std::sync::OnceLock = std::sync::OnceLock::new(); let address = *ADDRESS.get_or_init(|| { crate::hle::host::function($dll, $name) .unwrap_or_else(|| panic!("the host lacks {}!{}", $dll, $name)) }); unsafe { std::mem::transmute::(address) } }}; } pub(crate) use host; static DRIVES: Mutex)>> = Mutex::new(Vec::new()); fn drives() -> MutexGuard<'static, Vec<(u16, Vec)>> { DRIVES.lock().unwrap_or_else(|e| e.into_inner()) } pub fn mount(root: &Path) -> Option { mount_in(&mut drives(), root, || { unsafe { GetLogicalDrives() } }) } fn mount_in( drives: &mut Vec<(u16, Vec)>, root: &Path, host_drives: impl FnOnce() -> u32, ) -> Option { let wide = root_wide(root); if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) { return char::from_u32(letter.into()); } let host = host_drives(); if host == 0 { tracing::warn!(root = %root.display(), "GetLogicalDrives failed"); return None; } let letter = (b'D'..=b'Z').rev().find(|&l| { host >> (l - b'A') & 1 == 0 && !drives.iter().any(|(m, _)| *m == u16::from(l)) })?; tracing::info!(drive = %char::from(letter), root = %root.display(), "virtual drive"); drives.push((letter.into(), wide)); Some(letter.into()) } pub fn mount_at(letter: char, root: &Path) { let letter = letter.to_ascii_uppercase(); let Some(index) = u32::from(letter) .checked_sub(u32::from('A')) .filter(|i| *i < 26) else { return; }; let hides_host_drive = unsafe { GetLogicalDrives() } >> index & 1 != 0; tracing::info!(drive = %letter, root = %root.display(), hides_host_drive, "virtual drive"); let mut drives = drives(); drives.retain(|(l, _)| u32::from(*l) != u32::from(letter)); drives.push((letter as u16, root_wide(root))); } fn root_wide(root: &Path) -> Vec { let root = if root.as_os_str().is_empty() { Path::new(".") } else { root }; let root = std::path::absolute(root).unwrap_or_else(|_| root.to_owned()); let mut wide: Vec = root.as_os_str().encode_wide().collect(); while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) { wide.pop(); } wide } const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16]; const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; const LONG: usize = 248; fn verbatim(root: &[u16], tail: &[u16]) -> Vec { let backslash = u16::from(b'\\'); let mut out = if root.starts_with(&VERBATIM) { root.to_vec() } else if let Some(unc) = root.strip_prefix(&[backslash; 2][..]) { let mut out = VERBATIM.to_vec(); out.extend("UNC\\".encode_utf16()); out.extend_from_slice(unc); out } else { [&VERBATIM[..], root].concat() }; while out.last() == Some(&backslash) { out.pop(); } let dot = u16::from(b'.'); let mut parts: Vec<&[u16]> = Vec::new(); for part in tail.split(|c| SEPARATORS.contains(c)) { match part { [] => {} [d] if *d == dot => {} [d, e] if [*d, *e] == [dot; 2] => drop(parts.pop()), _ => parts.push(part), } } for part in parts { out.push(backslash); out.extend_from_slice(part); } out } fn clean_path(tail: &[u16]) -> Option<(Vec<&[u16]>, bool)> { let dot = u16::from(b'.'); let mut parts: Vec<&[u16]> = Vec::new(); let mut dotted = false; for part in tail.split(|c| SEPARATORS.contains(c)) { match part { [] => {} [d] if *d == dot => dotted = true, [d, e] if [*d, *e] == [dot; 2] => { dotted = true; parts.pop(); } _ => parts.push(part), } } dotted.then_some((parts, tail.last().is_some_and(|c| SEPARATORS.contains(c)))) } pub(crate) fn translate(path: &[u16]) -> Option> { let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) { Some(rest) => (&VERBATIM[..], rest), None => (&[][..], path), }; let &[letter, colon, ..] = rest else { return None; }; if colon != u16::from(b':') { return None; } let letter = u8::try_from(letter).ok().filter(u8::is_ascii_alphabetic)?; let letter = u16::from(letter.to_ascii_uppercase()); let drives = drives(); let (_, root) = drives.iter().find(|(l, _)| *l == letter)?; let tail = &rest[2..]; if prefix.is_empty() && root.len() + tail.len() >= LONG { let mut out = verbatim(root, tail); out.push(0); return Some(out); } if let Some((parts, trailing)) = clean_path(tail) { let mut out = prefix.to_vec(); out.extend_from_slice(root); for part in parts { out.push(b'\\'.into()); out.extend_from_slice(part); } if trailing { out.push(b'\\'.into()); } out.push(0); return Some(out); } let mut out = prefix.to_vec(); out.extend_from_slice(root); if !tail.first().is_some_and(|c| SEPARATORS.contains(c)) { out.push(b'\\'.into()); } let verbatim = !prefix.is_empty(); out.extend(tail.iter().map(|&c| { if verbatim && c == u16::from(b'/') { b'\\'.into() } else { c } })); out.push(0); Some(out) } struct Wide(*const u16, Option>); impl Wide { fn ptr(&self) -> *const u16 { self.1.as_ref().map_or(self.0, |p| p.as_ptr()) } fn shown(&self) -> String { let ptr = self.ptr(); if ptr.is_null() { return String::new(); } unsafe { let len = (0..).take_while(|&i| *ptr.add(i) != 0).count(); String::from_utf16_lossy(std::slice::from_raw_parts(ptr, len)) } } } fn wide(path: *const u16) -> Wide { if path.is_null() { return Wide(path, None); } let path_slice = unsafe { let len = (0..).take_while(|&i| *path.add(i) != 0).count(); std::slice::from_raw_parts(path, len) }; let host = translate(path_slice); trace(path_slice, host.as_deref()); Wide(path, host) } fn trace(path: &[u16], host: Option<&[u16]>) { tracing::debug!( path = %String::from_utf16_lossy(path), host = host.map(|h| String::from_utf16_lossy(&h[..h.len() - 1])), "title path" ); } fn narrow(path: *const c_char) -> Option> { if path.is_null() { return None; } let bytes = unsafe { CStr::from_ptr(path) }.to_bytes(); match bytes.strip_prefix(br"\\?\").unwrap_or(bytes) { [letter, b':', ..] if letter.is_ascii_alphabetic() => {} _ => { tracing::debug!(path = %String::from_utf8_lossy(bytes), "title path"); return None; } } let len = i32::try_from(bytes.len()).ok()?; let wide = unsafe { let n = MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0); let mut wide = vec![0u16; usize::try_from(n).ok()?]; MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n); wide }; let host = translate(&wide); trace(&wide, host.as_deref()); host } fn widen(mode: *const c_char) -> Vec { if mode.is_null() { return vec![0]; } let bytes = unsafe { CStr::from_ptr(mode) }.to_bytes(); bytes.iter().map(|&b| u16::from(b)).chain([0]).collect() } type Handle = *mut c_void; type File = *mut c_void; mod title_io { use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; const NO_BUFFERING: u32 = 0x2000_0000; const RANDOM_ACCESS: u32 = 0x1000_0000; const OVERLAPPED: u32 = 0x4000_0000; const WRITES: u32 = 0x4000_0000 | 0x1000_0000 | 0x0000_0002 | 0x0000_0004; fn buffered() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| { let on = std::env::var_os("EONACAT_XS_FILE_BUFFERED").is_none_or(|v| v != "0"); tracing::info!(on, "title files: read-only opens go through the host's file cache (EONACAT_XS_FILE_BUFFERED)"); on }) } pub(super) fn sent(access: u32, flags: u32, on: bool) -> u32 { if on && access & WRITES == 0 && flags & OVERLAPPED == 0 { flags & !(NO_BUFFERING | RANDOM_ACCESS) } else { flags } } pub(super) fn flags(path: &str, access: u32, flags: u32) -> u32 { let out = sent(access, flags, buffered()); let read_only = access & WRITES == 0; static KINDS: Mutex> = Mutex::new(Vec::new()); let mut kinds = KINDS.lock().unwrap_or_else(|e| e.into_inner()); let kind = (flags & 0xFFFF_0000, read_only); if !kinds.contains(&kind) { kinds.push(kind); tracing::info!( flags = format_args!("{flags:#010x}"), sent = format_args!("{out:#010x}"), access = format_args!("{access:#010x}"), path, "title file opened, the first with these flags" ); } out } static READS: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; static LAST: AtomicU64 = AtomicU64::new(0); pub(super) fn read(len: u32, ns: u64) { READS[0].fetch_add(1, Relaxed); READS[1].fetch_add(u64::from(len), Relaxed); READS[2].fetch_add(ns, Relaxed); if len <= 4096 { READS[3].fetch_add(1, Relaxed); } static START: std::sync::OnceLock = std::sync::OnceLock::new(); let now = START .get_or_init(std::time::Instant::now) .elapsed() .as_millis() as u64; let last = LAST.load(Relaxed); if now.saturating_sub(last) < 2000 || LAST.compare_exchange(last, now, Relaxed, Relaxed).is_err() { return; } let v: [u64; 4] = std::array::from_fn(|i| READS[i].swap(0, Relaxed)); if v[0] >= 1000 { let secs = (now - last).max(1) as f64 / 1000.0; tracing::info!( "title ReadFile, last {secs:.1} s: {} calls ({} of 4 KiB or less), {:.1} MB, {:.0} us a call in the host's ReadFile", v[0], v[3], v[1] as f64 / 1e6, v[2] as f64 / v[0] as f64 / 1e3, ); } } } pub extern "system" fn CreateFileW( path: *const u16, access: u32, share: u32, security: *const c_void, disposition: u32, flags: u32, template: Handle, ) -> Handle { let p = wide(path); let flags = title_io::flags(&p.shown(), access, flags); host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( p.ptr(), access, share, security, disposition, flags, template, ) } pub extern "system" fn CreateFileA( path: *const c_char, access: u32, share: u32, security: *const c_void, disposition: u32, flags: u32, template: Handle, ) -> Handle { match narrow(path) { Some(p) => { let flags = title_io::flags( &String::from_utf16_lossy(&p[..p.len().saturating_sub(1)]), access, flags, ); host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( p.as_ptr(), access, share, security, disposition, flags, template, ) } None => { let shown = if path.is_null() { String::new() } else { unsafe { CStr::from_ptr(path) } .to_string_lossy() .into_owned() }; let flags = title_io::flags(&shown, access, flags); host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( path, access, share, security, disposition, flags, template, ) } } } pub extern "system" fn CreateFile2( path: *const u16, access: u32, share: u32, disposition: u32, params: *const c_void, ) -> Handle { let p = wide(path); let mut copy = [0u8; 32]; let mut params = params; if !params.is_null() { let size = unsafe { *(params as *const u32) } as usize; if size >= 12 && size <= copy.len() { unsafe { std::ptr::copy_nonoverlapping(params as *const u8, copy.as_mut_ptr(), size) }; let flags = u32::from_le_bytes([copy[8], copy[9], copy[10], copy[11]]); let sent = title_io::flags(&p.shown(), access, flags); if sent != flags { copy[8..12].copy_from_slice(&sent.to_le_bytes()); params = copy.as_ptr() as *const c_void; } } } host!("kernel32.dll", "CreateFile2": extern "system" fn(*const u16, u32, u32, u32, *const c_void) -> Handle)( p.ptr(), access, share, disposition, params, ) } pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 { match narrow(path) { Some(p) => { host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.as_ptr()) } None => { host!("kernel32.dll", "DeleteFileA": extern "system" fn(*const c_char) -> i32)(path) } } } pub extern "system" fn DeleteFileW(path: *const u16) -> i32 { let p = wide(path); host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.ptr()) } pub extern "system" fn RemoveDirectoryW(path: *const u16) -> i32 { let p = wide(path); host!("kernel32.dll", "RemoveDirectoryW": extern "system" fn(*const u16) -> i32)(p.ptr()) } pub extern "system" fn SetFileAttributesW(path: *const u16, attributes: u32) -> i32 { let p = wide(path); host!("kernel32.dll", "SetFileAttributesW": extern "system" fn(*const u16, u32) -> i32)( p.ptr(), attributes, ) } pub extern "system" fn GetFileAttributesA(path: *const c_char) -> u32 { match narrow(path) { Some(p) => { host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)( p.as_ptr(), ) } None => { host!("kernel32.dll", "GetFileAttributesA": extern "system" fn(*const c_char) -> u32)( path, ) } } } pub extern "system" fn CreateDirectoryW(path: *const u16, security: *const c_void) -> i32 { let p = wide(path); host!("kernel32.dll", "CreateDirectoryW": extern "system" fn(*const u16, *const c_void) -> i32)( p.ptr(), security, ) } pub extern "system" fn GetFileAttributesExW( path: *const u16, level: i32, info: *mut c_void, ) -> i32 { let p = wide(path); host!("kernel32.dll", "GetFileAttributesExW": extern "system" fn(*const u16, i32, *mut c_void) -> i32)( p.ptr(), level, info, ) } pub extern "system" fn GetFileAttributesW(path: *const u16) -> u32 { let p = wide(path); host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)(p.ptr()) } pub extern "system" fn WerRegisterFile(path: *const u16, kind: u32, flags: u32) -> i32 { let p = wide(path); host!("kernel32.dll", "WerRegisterFile": extern "system" fn(*const u16, u32, u32) -> i32)( p.ptr(), kind, flags, ) } pub extern "system" fn GetDiskFreeSpaceExW( path: *const u16, available: *mut u64, total: *mut u64, free: *mut u64, ) -> i32 { let p = wide(path); host!("kernel32.dll", "GetDiskFreeSpaceExW": extern "system" fn(*const u16, *mut u64, *mut u64, *mut u64) -> i32)( p.ptr(), available, total, free, ) } pub extern "system" fn GetDiskFreeSpaceW( root: *const u16, sectors_per_cluster: *mut u32, bytes_per_sector: *mut u32, free_clusters: *mut u32, clusters: *mut u32, ) -> i32 { let mut p = wide(root); host_volume_root(&mut p.1); host!("kernel32.dll", "GetDiskFreeSpaceW": extern "system" fn(*const u16, *mut u32, *mut u32, *mut u32, *mut u32) -> i32)( p.ptr(), sectors_per_cluster, bytes_per_sector, free_clusters, clusters, ) } pub extern "system" fn FindFirstFileW(path: *const u16, data: *mut c_void) -> Handle { let p = wide(path); host!("kernel32.dll", "FindFirstFileW": extern "system" fn(*const u16, *mut c_void) -> Handle)( p.ptr(), data, ) } pub extern "system" fn FindFirstFileExW( path: *const u16, level: i32, data: *mut c_void, search: i32, filter: *mut c_void, flags: u32, ) -> Handle { let p = wide(path); host!("kernel32.dll", "FindFirstFileExW": extern "system" fn(*const u16, i32, *mut c_void, i32, *mut c_void, u32) -> Handle)( p.ptr(), level, data, search, filter, flags, ) } pub extern "system" fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32 { let (from, to) = (wide(from), wide(to)); host!("kernel32.dll", "MoveFileExW": extern "system" fn(*const u16, *const u16, u32) -> i32)( from.ptr(), to.ptr(), flags, ) } pub extern "system" fn SetCurrentDirectoryA(path: *const c_char) -> i32 { match narrow(path) { Some(p) => { host!("kernel32.dll", "SetCurrentDirectoryW": extern "system" fn(*const u16) -> i32)( p.as_ptr(), ) } None => { host!("kernel32.dll", "SetCurrentDirectoryA": extern "system" fn(*const c_char) -> i32)( path, ) } } } fn narrow_wide(path: *const c_char) -> Option> { if path.is_null() { return None; } narrow(path).or_else(|| { let bytes = unsafe { CStr::from_ptr(path) }.to_bytes_with_nul(); let len = i32::try_from(bytes.len()).ok()?; unsafe { let n = MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0); let mut wide = vec![0u16; usize::try_from(n).ok()?]; MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n); Some(wide) } }) } fn wide_ptr(path: &Option>) -> *const u16 { path.as_ref().map_or(std::ptr::null(), |p| p.as_ptr()) } fn narrow_host(path: *const c_char) -> Option> { use windows_sys::Win32::Globalization::WideCharToMultiByte; let wide = narrow(path)?; let len = i32::try_from(wide.len()).ok()?; unsafe { let n = WideCharToMultiByte(CP_ACP, 0, wide.as_ptr(), len, std::ptr::null_mut(), 0, std::ptr::null(), std::ptr::null_mut()); let mut out = vec![0u8; usize::try_from(n).ok()?]; WideCharToMultiByte(CP_ACP, 0, wide.as_ptr(), len, out.as_mut_ptr(), n, std::ptr::null(), std::ptr::null_mut()); Some(out) } } fn narrow_ptr(host: &Option>, title: *const c_char) -> *const c_char { host.as_ref().map_or(title, |p| p.as_ptr().cast()) } fn host_volume_root(path: &mut Option>) { if let Some(host) = path && let [letter, colon, sep, ..] = host[..] && colon == u16::from(b':') && SEPARATORS.contains(&sep) { *host = vec![letter, colon, sep, 0]; } } pub extern "system" fn SetCurrentDirectoryW(path: *const u16) -> i32 { let p = wide(path); host!("kernel32.dll", "SetCurrentDirectoryW": extern "system" fn(*const u16) -> i32)(p.ptr()) } pub extern "system" fn CreateDirectoryA(path: *const c_char, security: *const c_void) -> i32 { let p = narrow_wide(path); host!("kernel32.dll", "CreateDirectoryW": extern "system" fn(*const u16, *const c_void) -> i32)( wide_ptr(&p), security, ) } pub extern "system" fn CreateDirectoryExW( template: *const u16, path: *const u16, security: *const c_void, ) -> i32 { let (template, path) = (wide(template), wide(path)); host!("kernel32.dll", "CreateDirectoryExW": extern "system" fn(*const u16, *const u16, *const c_void) -> i32)( template.ptr(), path.ptr(), security, ) } pub extern "system" fn CreateDirectoryExA( template: *const c_char, path: *const c_char, security: *const c_void, ) -> i32 { let (template, path) = (narrow_wide(template), narrow_wide(path)); host!("kernel32.dll", "CreateDirectoryExW": extern "system" fn(*const u16, *const u16, *const c_void) -> i32)( wide_ptr(&template), wide_ptr(&path), security, ) } pub extern "system" fn RemoveDirectoryA(path: *const c_char) -> i32 { let p = narrow_wide(path); host!("kernel32.dll", "RemoveDirectoryW": extern "system" fn(*const u16) -> i32)(wide_ptr(&p)) } pub extern "system" fn SetFileAttributesA(path: *const c_char, attributes: u32) -> i32 { let p = narrow_wide(path); host!("kernel32.dll", "SetFileAttributesW": extern "system" fn(*const u16, u32) -> i32)( wide_ptr(&p), attributes, ) } pub extern "system" fn GetFileAttributesExA( path: *const c_char, level: i32, info: *mut c_void, ) -> i32 { let p = narrow_wide(path); host!("kernel32.dll", "GetFileAttributesExW": extern "system" fn(*const u16, i32, *mut c_void) -> i32)( wide_ptr(&p), level, info, ) } pub extern "system" fn GetDiskFreeSpaceExA( path: *const c_char, available: *mut u64, total: *mut u64, free: *mut u64, ) -> i32 { let p = narrow_wide(path); host!("kernel32.dll", "GetDiskFreeSpaceExW": extern "system" fn(*const u16, *mut u64, *mut u64, *mut u64) -> i32)( wide_ptr(&p), available, total, free, ) } pub extern "system" fn GetDiskFreeSpaceA( root: *const c_char, sectors_per_cluster: *mut u32, bytes_per_sector: *mut u32, free_clusters: *mut u32, clusters: *mut u32, ) -> i32 { let mut p = narrow(root); host_volume_root(&mut p); match p { Some(p) => host!("kernel32.dll", "GetDiskFreeSpaceW": extern "system" fn(*const u16, *mut u32, *mut u32, *mut u32, *mut u32) -> i32)( p.as_ptr(), sectors_per_cluster, bytes_per_sector, free_clusters, clusters, ), None => host!("kernel32.dll", "GetDiskFreeSpaceA": extern "system" fn(*const c_char, *mut u32, *mut u32, *mut u32, *mut u32) -> i32)( root, sectors_per_cluster, bytes_per_sector, free_clusters, clusters, ), } } pub extern "system" fn GetDriveTypeW(root: *const u16) -> u32 { let mut p = wide(root); host_volume_root(&mut p.1); host!("kernel32.dll", "GetDriveTypeW": extern "system" fn(*const u16) -> u32)(p.ptr()) } pub extern "system" fn GetDriveTypeA(root: *const c_char) -> u32 { let mut p = narrow(root); host_volume_root(&mut p); match p { Some(p) => host!("kernel32.dll", "GetDriveTypeW": extern "system" fn(*const u16) -> u32)(p.as_ptr()), None => host!("kernel32.dll", "GetDriveTypeA": extern "system" fn(*const c_char) -> u32)(root), } } pub extern "system" fn GetVolumeInformationW( root: *const u16, name: *mut u16, name_size: u32, serial: *mut u32, max_component: *mut u32, flags: *mut u32, file_system: *mut u16, file_system_size: u32, ) -> i32 { let mut p = wide(root); host_volume_root(&mut p.1); host!("kernel32.dll", "GetVolumeInformationW": extern "system" fn(*const u16, *mut u16, u32, *mut u32, *mut u32, *mut u32, *mut u16, u32) -> i32)( p.ptr(), name, name_size, serial, max_component, flags, file_system, file_system_size, ) } pub extern "system" fn GetVolumeInformationA( root: *const c_char, name: *mut c_char, name_size: u32, serial: *mut u32, max_component: *mut u32, flags: *mut u32, file_system: *mut c_char, file_system_size: u32, ) -> i32 { let mut p = narrow_host(root); if let Some(host) = &mut p && let [letter, b':', sep, ..] = host[..] && (sep == b'\\' || sep == b'/') { *host = vec![letter, b':', sep, 0]; } host!("kernel32.dll", "GetVolumeInformationA": extern "system" fn(*const c_char, *mut c_char, u32, *mut u32, *mut u32, *mut u32, *mut c_char, u32) -> i32)( narrow_ptr(&p, root), name, name_size, serial, max_component, flags, file_system, file_system_size, ) } pub extern "system" fn GetVolumePathNameW(path: *const u16, out: *mut u16, len: u32) -> i32 { let p = wide(path); host!("kernel32.dll", "GetVolumePathNameW": extern "system" fn(*const u16, *mut u16, u32) -> i32)( p.ptr(), out, len, ) } pub extern "system" fn GetVolumePathNameA(path: *const c_char, out: *mut c_char, len: u32) -> i32 { let p = narrow_host(path); host!("kernel32.dll", "GetVolumePathNameA": extern "system" fn(*const c_char, *mut c_char, u32) -> i32)( narrow_ptr(&p, path), out, len, ) } pub extern "system" fn GetTempFileNameW( path: *const u16, prefix: *const u16, unique: u32, out: *mut u16, ) -> u32 { let p = wide(path); host!("kernel32.dll", "GetTempFileNameW": extern "system" fn(*const u16, *const u16, u32, *mut u16) -> u32)( p.ptr(), prefix, unique, out, ) } pub extern "system" fn SearchPathW( folders: *const u16, file: *const u16, extension: *const u16, len: u32, out: *mut u16, file_part: *mut *mut u16, ) -> u32 { let (folders, file) = (wide(folders), wide(file)); host!("kernel32.dll", "SearchPathW": extern "system" fn(*const u16, *const u16, *const u16, u32, *mut u16, *mut *mut u16) -> u32)( folders.ptr(), file.ptr(), extension, len, out, file_part, ) } pub extern "system" fn SearchPathA( folders: *const c_char, file: *const c_char, extension: *const c_char, len: u32, out: *mut c_char, file_part: *mut *mut c_char, ) -> u32 { let (f, n) = (narrow_host(folders), narrow_host(file)); host!("kernel32.dll", "SearchPathA": extern "system" fn(*const c_char, *const c_char, *const c_char, u32, *mut c_char, *mut *mut c_char) -> u32)( narrow_ptr(&f, folders), narrow_ptr(&n, file), extension, len, out, file_part, ) } pub extern "system" fn FindFirstFileA(path: *const c_char, data: *mut c_void) -> Handle { let p = narrow_host(path); host!("kernel32.dll", "FindFirstFileA": extern "system" fn(*const c_char, *mut c_void) -> Handle)( narrow_ptr(&p, path), data, ) } pub extern "system" fn FindFirstFileExA( path: *const c_char, level: i32, data: *mut c_void, search: i32, filter: *mut c_void, flags: u32, ) -> Handle { let p = narrow_host(path); host!("kernel32.dll", "FindFirstFileExA": extern "system" fn(*const c_char, i32, *mut c_void, i32, *mut c_void, u32) -> Handle)( narrow_ptr(&p, path), level, data, search, filter, flags, ) } pub extern "system" fn MoveFileW(from: *const u16, to: *const u16) -> i32 { let (from, to) = (wide(from), wide(to)); host!("kernel32.dll", "MoveFileW": extern "system" fn(*const u16, *const u16) -> i32)( from.ptr(), to.ptr(), ) } pub extern "system" fn MoveFileA(from: *const c_char, to: *const c_char) -> i32 { let (from, to) = (narrow_wide(from), narrow_wide(to)); host!("kernel32.dll", "MoveFileW": extern "system" fn(*const u16, *const u16) -> i32)( wide_ptr(&from), wide_ptr(&to), ) } pub extern "system" fn MoveFileExA(from: *const c_char, to: *const c_char, flags: u32) -> i32 { let (from, to) = (narrow_wide(from), narrow_wide(to)); host!("kernel32.dll", "MoveFileExW": extern "system" fn(*const u16, *const u16, u32) -> i32)( wide_ptr(&from), wide_ptr(&to), flags, ) } pub extern "system" fn CopyFileW(from: *const u16, to: *const u16, fail_if_exists: i32) -> i32 { let (from, to) = (wide(from), wide(to)); host!("kernel32.dll", "CopyFileW": extern "system" fn(*const u16, *const u16, i32) -> i32)( from.ptr(), to.ptr(), fail_if_exists, ) } pub extern "system" fn CopyFileA(from: *const c_char, to: *const c_char, fail_if_exists: i32) -> i32 { let (from, to) = (narrow_wide(from), narrow_wide(to)); host!("kernel32.dll", "CopyFileW": extern "system" fn(*const u16, *const u16, i32) -> i32)( wide_ptr(&from), wide_ptr(&to), fail_if_exists, ) } pub extern "system" fn CopyFileExW( from: *const u16, to: *const u16, progress: *const c_void, data: *mut c_void, cancel: *mut i32, flags: u32, ) -> i32 { let (from, to) = (wide(from), wide(to)); host!("kernel32.dll", "CopyFileExW": extern "system" fn(*const u16, *const u16, *const c_void, *mut c_void, *mut i32, u32) -> i32)( from.ptr(), to.ptr(), progress, data, cancel, flags, ) } pub extern "system" fn CopyFileExA( from: *const c_char, to: *const c_char, progress: *const c_void, data: *mut c_void, cancel: *mut i32, flags: u32, ) -> i32 { let (from, to) = (narrow_wide(from), narrow_wide(to)); host!("kernel32.dll", "CopyFileExW": extern "system" fn(*const u16, *const u16, *const c_void, *mut c_void, *mut i32, u32) -> i32)( wide_ptr(&from), wide_ptr(&to), progress, data, cancel, flags, ) } pub extern "system" fn CopyFile2(from: *const u16, to: *const u16, params: *const c_void) -> i32 { let (from, to) = (wide(from), wide(to)); host!("kernel32.dll", "CopyFile2": extern "system" fn(*const u16, *const u16, *const c_void) -> i32)( from.ptr(), to.ptr(), params, ) } pub extern "system" fn ReplaceFileW( replaced: *const u16, replacement: *const u16, backup: *const u16, flags: u32, exclude: *mut c_void, reserved: *mut c_void, ) -> i32 { let (replaced, replacement, backup) = (wide(replaced), wide(replacement), wide(backup)); host!("kernel32.dll", "ReplaceFileW": extern "system" fn(*const u16, *const u16, *const u16, u32, *mut c_void, *mut c_void) -> i32)( replaced.ptr(), replacement.ptr(), backup.ptr(), flags, exclude, reserved, ) } pub extern "system" fn ReplaceFileA( replaced: *const c_char, replacement: *const c_char, backup: *const c_char, flags: u32, exclude: *mut c_void, reserved: *mut c_void, ) -> i32 { let (replaced, replacement, backup) = (narrow_wide(replaced), narrow_wide(replacement), narrow_wide(backup)); host!("kernel32.dll", "ReplaceFileW": extern "system" fn(*const u16, *const u16, *const u16, u32, *mut c_void, *mut c_void) -> i32)( wide_ptr(&replaced), wide_ptr(&replacement), wide_ptr(&backup), flags, exclude, reserved, ) } pub extern "C" fn _wfopen(path: *const u16, mode: *const u16) -> File { let p = wide(path); host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)(p.ptr(), mode) } pub extern "C" fn _wfopen_s(out: *mut File, path: *const u16, mode: *const u16) -> i32 { let p = wide(path); host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)( out, p.ptr(), mode, ) } pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> File { let p = wide(path); host!("ucrtbase.dll", "_wfsopen": extern "C" fn(*const u16, *const u16, i32) -> File)( p.ptr(), mode, share, ) } fn overlapped_offset(overlapped: *mut c_void) -> u64 { if overlapped.is_null() { return 0; } unsafe { (overlapped as *const u8) .add(16) .cast::() .read_unaligned() } } fn bounced_read( file: *mut c_void, buffer: *mut u8, len: u32, read: *mut u32, overlapped: *mut c_void, ) -> i32 { use windows_sys::Win32::Foundation::{ERROR_IO_PENDING, GetLastError, SetLastError}; let host_read = host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32); let get_result = host!("kernel32.dll", "GetOverlappedResult": extern "system" fn(*mut c_void, *mut c_void, *mut u32, i32) -> i32); const CHUNK: usize = 8 << 20; let mut tmp = vec![0u8; CHUNK.min(len as usize)]; let mut offset = overlapped_offset(overlapped); let mut total: u32 = 0; while total < len { let want = ((len - total) as usize).min(CHUNK) as u32; let mut got: u32 = 0; let mut ov: [u64; 4] = [0, 0, offset, 0]; let ov_ptr: *mut c_void = if overlapped.is_null() { std::ptr::null_mut() } else { ov.as_mut_ptr().cast() }; let mut ok = host_read(file, tmp.as_mut_ptr(), want, &mut got, ov_ptr); if ok == 0 && !ov_ptr.is_null() && unsafe { GetLastError() } == ERROR_IO_PENDING { ok = get_result(file, ov_ptr, &mut got, 1); } if ok == 0 { let error = unsafe { GetLastError() }; if total > 0 { break; } unsafe { SetLastError(error) }; return 0; } if got == 0 { break; } unsafe { std::ptr::copy_nonoverlapping(tmp.as_ptr(), buffer.add(total as usize), got as usize) }; total += got; offset += u64::from(got); if got < want { break; } } if !read.is_null() { unsafe { *read = total }; } if !overlapped.is_null() { unsafe { (overlapped as *mut u64).write_unaligned(0); (overlapped as *mut u64) .add(1) .write_unaligned(u64::from(total)); } } 1 } pub extern "system" fn ReadFile( file: *mut c_void, buffer: *mut u8, len: u32, read: *mut u32, overlapped: *mut c_void, ) -> i32 { let writing = eonacat_xsbox_gpu::kernel_writing(buffer as usize, len as usize); static BOUNCE: std::sync::OnceLock = std::sync::OnceLock::new(); let bounce = *BOUNCE.get_or_init(|| std::env::var_os("EONACAT_XS_READ_BOUNCE").is_some_and(|v| v == "1")); let began = std::time::Instant::now(); let done = if bounce && len >= 0x10000 { bounced_read(file, buffer, len, read, overlapped) } else { host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( file, buffer, len, read, overlapped, ) }; let ns = began.elapsed().as_nanos() as u64; let error = unsafe { windows_sys::Win32::Foundation::GetLastError() }; title_io::read(len, ns); if done == 0 && error == windows_sys::Win32::Foundation::ERROR_IO_PENDING { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| tracing::info!(len, "ReadFile: a read of the title's goes on after the call")); } if done == 0 && error == windows_sys::Win32::Foundation::ERROR_NOACCESS { static FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let n = FAILED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; if n.is_power_of_two() { tracing::warn!(n, buffer = format_args!("{buffer:p}"), len, "ReadFile: the title's buffer could not be written"); } } drop(writing); unsafe { windows_sys::Win32::Foundation::SetLastError(error) }; done } pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { let _writing = eonacat_xsbox_gpu::kernel_writing(buffer as usize, size.saturating_mul(count)); host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)( buffer, size, count, stream, ) } pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { match narrow(path) { Some(p) => host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)( p.as_ptr(), widen(mode).as_ptr(), ), None => { host!("ucrtbase.dll", "fopen": extern "C" fn(*const c_char, *const c_char) -> File)( path, mode, ) } } } pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_char) -> i32 { match narrow(path) { Some(p) => { host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)( out, p.as_ptr(), widen(mode).as_ptr(), ) } None => { host!("ucrtbase.dll", "fopen_s": extern "C" fn(*mut File, *const c_char, *const c_char) -> i32)( out, path, mode, ) } } } pub extern "C" fn _open(path: *const c_char, flags: i32, mode: i32) -> i32 { match narrow(path) { Some(p) => host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)( p.as_ptr(), flags, mode, ), None => host!("ucrtbase.dll", "_open": extern "C" fn(*const c_char, i32, i32) -> i32)( path, flags, mode, ), } } pub extern "C" fn _wopen(path: *const u16, flags: i32, mode: i32) -> i32 { let p = wide(path); host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)( p.ptr(), flags, mode, ) } pub extern "C" fn _wstat64(path: *const u16, stat: *mut c_void) -> i32 { let p = wide(path); host!("ucrtbase.dll", "_wstat64": extern "C" fn(*const u16, *mut c_void) -> i32)(p.ptr(), stat) } pub extern "C" fn _stat64i32(path: *const c_char, stat: *mut c_void) -> i32 { match narrow(path) { Some(p) => { host!("ucrtbase.dll", "_wstat64i32": extern "C" fn(*const u16, *mut c_void) -> i32)( p.as_ptr(), stat, ) } None => { host!("ucrtbase.dll", "_stat64i32": extern "C" fn(*const c_char, *mut c_void) -> i32)( path, stat, ) } } } pub extern "C" fn remove(path: *const c_char) -> i32 { match narrow(path) { Some(p) => host!("ucrtbase.dll", "_wremove": extern "C" fn(*const u16) -> i32)(p.as_ptr()), None => host!("ucrtbase.dll", "remove": extern "C" fn(*const c_char) -> i32)(path), } } pub extern "C" fn _wchmod(path: *const u16, mode: i32) -> i32 { let p = wide(path); host!("ucrtbase.dll", "_wchmod": extern "C" fn(*const u16, i32) -> i32)(p.ptr(), mode) } pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 { let p = wide(path); host!("ucrtbase.dll", "_wutime64": extern "C" fn(*const u16, *mut c_void) -> i32)( p.ptr(), times, ) } const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z"; const FIOPEN_WIDE: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z"; extern "C" fn fiopen_wide(path: *const u16, mode: i32, protection: i32) -> File { let p = wide(path); host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( p.ptr(), mode, protection, ) } extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File { match narrow(path) { Some(p) => { host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( p.as_ptr(), mode, protection, ) } None => { host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)( path, mode, protection, ) } } } pub(crate) fn module() -> HleModule { HleModule { name: "files", dlls: &[ "kernel32.dll", "kernelbase.dll", "api-ms-win-core-file-*", "api-ms-win-core-processenvironment-*", "api-ms-win-core-kernel32-legacy-*", "api-ms-win-core-windowserrorreporting-*", "ucrtbase.dll", "api-ms-win-crt-stdio-*", "api-ms-win-crt-filesystem-*", "api-ms-win-crt-time-*", "msvcp140.dll", ], exports: vec![ hle_export!(ReadFile), hle_export!(fread), hle_export!(CreateFileW), hle_export!(CreateFileA), hle_export!(CreateFile2), hle_export!(DeleteFileA), hle_export!(DeleteFileW), hle_export!(RemoveDirectoryW), hle_export!(SetFileAttributesW), hle_export!(GetFileAttributesA), hle_export!(CreateDirectoryW), hle_export!(GetFileAttributesW), hle_export!(GetFileAttributesExW), hle_export!(GetDiskFreeSpaceExW), hle_export!(WerRegisterFile), hle_export!(GetDiskFreeSpaceW), hle_export!(FindFirstFileW), hle_export!(FindFirstFileExW), hle_export!(MoveFileExW), hle_export!(SetCurrentDirectoryA), hle_export!(SetCurrentDirectoryW), hle_export!(CreateDirectoryA), hle_export!(CreateDirectoryExA), hle_export!(CreateDirectoryExW), hle_export!(RemoveDirectoryA), hle_export!(SetFileAttributesA), hle_export!(GetFileAttributesExA), hle_export!(GetDiskFreeSpaceA), hle_export!(GetDiskFreeSpaceExA), hle_export!(GetDriveTypeA), hle_export!(GetDriveTypeW), hle_export!(GetVolumeInformationA), hle_export!(GetVolumeInformationW), hle_export!(GetVolumePathNameA), hle_export!(GetVolumePathNameW), hle_export!(GetTempFileNameW), hle_export!(SearchPathA), hle_export!(SearchPathW), hle_export!(FindFirstFileA), hle_export!(FindFirstFileExA), hle_export!(MoveFileA), hle_export!(MoveFileW), hle_export!(MoveFileExA), hle_export!(CopyFileA), hle_export!(CopyFileW), hle_export!(CopyFileExA), hle_export!(CopyFileExW), hle_export!(CopyFile2), hle_export!(ReplaceFileA), hle_export!(ReplaceFileW), hle_export!(_wfopen), hle_export!(_wfopen_s), hle_export!(_wfsopen), hle_export!(fopen), hle_export!(fopen_s), hle_export!(_open), hle_export!(_wopen), hle_export!(_wstat64), hle_export!(_stat64i32), hle_export!(remove), hle_export!(_wchmod), hle_export!(_wutime64), HleExport { name: FIOPEN, address: fiopen as *const () as usize, }, HleExport { name: FIOPEN_WIDE, address: fiopen_wide as *const () as usize, }, ], } }