files.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. //! Virtual drives over host folders: on the console, title storage is a
  2. //! drive of its own, and titles build paths on that assumption.
  3. //!
  4. //! Every title import that takes a path is bound here. A path on a virtual
  5. //! drive (`X:\..`, `X:/..`, `X:`, `\\?\X:\..`) is rewritten to the host
  6. //! folder behind it and handed to the host's own function; any other path
  7. //! goes to the host unchanged. A rewritten narrow path goes to the host's
  8. //! wide twin, so host folders outside the ANSI code page work; never to our
  9. //! wide wrapper, which would rewrite the host path a second time when its
  10. //! drive letter is mounted too. Letters are chosen among those the host
  11. //! does not use, so no host drive is hidden.
  12. #![allow(non_snake_case)]
  13. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  14. #![allow(clippy::too_many_arguments)]
  15. use std::ffi::{CStr, c_char, c_void};
  16. use std::os::windows::ffi::OsStrExt;
  17. use std::path::Path;
  18. use std::sync::{Mutex, MutexGuard};
  19. use windows_sys::Win32::Globalization::{CP_ACP, MultiByteToWideChar};
  20. use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives;
  21. use crate::{HleExport, HleModule, hle_export};
  22. /// The host's own function: what the import would have been bound to.
  23. macro_rules! host {
  24. ($dll:literal, $name:literal: $ty:ty) => {{
  25. static ADDRESS: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
  26. let address = *ADDRESS.get_or_init(|| {
  27. crate::host::function($dll, $name)
  28. .unwrap_or_else(|| panic!("the host lacks {}!{}", $dll, $name))
  29. });
  30. // SAFETY: the host exports this function with this signature.
  31. unsafe { std::mem::transmute::<usize, $ty>(address) }
  32. }};
  33. }
  34. pub(crate) use host;
  35. /// Mounted drives: upper-case letter and host root (UTF-16, no trailing
  36. /// separator, no NUL).
  37. static DRIVES: Mutex<Vec<(u16, Vec<u16>)>> = Mutex::new(Vec::new());
  38. fn drives() -> MutexGuard<'static, Vec<(u16, Vec<u16>)>> {
  39. DRIVES.lock().unwrap_or_else(|e| e.into_inner())
  40. }
  41. /// Gives the host folder `root` a drive letter (the same one if it already
  42. /// has one): the highest letter neither the host nor another mount uses.
  43. pub fn mount(root: &Path) -> Option<char> {
  44. let wide = root_wide(root);
  45. let mut drives = drives();
  46. if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) {
  47. return char::from_u32(letter.into());
  48. }
  49. // SAFETY: no arguments.
  50. let host = unsafe { GetLogicalDrives() };
  51. let letter = (b'D'..=b'Z').rev().find(|&l| {
  52. host >> (l - b'A') & 1 == 0 && !drives.iter().any(|(m, _)| *m == u16::from(l))
  53. })?;
  54. tracing::info!(drive = %char::from(letter), root = %root.display(), "virtual drive");
  55. drives.push((letter.into(), wide));
  56. Some(letter.into())
  57. }
  58. /// Gives the host folder `root` a drive letter the console fixes (titles
  59. /// open their package as `G:\..` and temporary files as `T:\..`). A host
  60. /// drive of that letter is hidden from the title.
  61. pub fn mount_at(letter: char, root: &Path) {
  62. let letter = letter.to_ascii_uppercase();
  63. let Some(index) = u32::from(letter)
  64. .checked_sub(u32::from('A'))
  65. .filter(|i| *i < 26)
  66. else {
  67. return;
  68. };
  69. // SAFETY: no arguments.
  70. let hides_host_drive = unsafe { GetLogicalDrives() } >> index & 1 != 0;
  71. tracing::info!(drive = %letter, root = %root.display(), hides_host_drive, "virtual drive");
  72. let mut drives = drives();
  73. drives.retain(|(l, _)| u32::from(*l) != u32::from(letter));
  74. drives.push((letter as u16, root_wide(root)));
  75. }
  76. /// `root` as UTF-16, absolute, without trailing separators (a drive root
  77. /// keeps its own).
  78. fn root_wide(root: &Path) -> Vec<u16> {
  79. let root = std::path::absolute(root).unwrap_or_else(|_| root.to_owned());
  80. let mut wide: Vec<u16> = root.as_os_str().encode_wide().collect();
  81. while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) {
  82. wide.pop();
  83. }
  84. wide
  85. }
  86. const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16];
  87. const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16];
  88. /// Host paths from this length on take the `\\?\` form, which lifts the
  89. /// host's MAX_PATH limit (248 characters for a directory, 260 for a file).
  90. const LONG: usize = 248;
  91. /// `root` and the title's `tail` as a `\\?\` path. That form turns off the
  92. /// host's own clean-up, so `/` becomes `\` and `.` and `..` are resolved
  93. /// here (`..` stops at the root).
  94. fn verbatim(root: &[u16], tail: &[u16]) -> Vec<u16> {
  95. let backslash = u16::from(b'\\');
  96. let mut out = if root.starts_with(&VERBATIM) {
  97. root.to_vec()
  98. } else if let Some(unc) = root.strip_prefix(&[backslash; 2][..]) {
  99. let mut out = VERBATIM.to_vec();
  100. out.extend("UNC\\".encode_utf16());
  101. out.extend_from_slice(unc);
  102. out
  103. } else {
  104. [&VERBATIM[..], root].concat()
  105. };
  106. while out.last() == Some(&backslash) {
  107. out.pop();
  108. }
  109. let dot = u16::from(b'.');
  110. let mut parts: Vec<&[u16]> = Vec::new();
  111. for part in tail.split(|c| SEPARATORS.contains(c)) {
  112. match part {
  113. [] => {}
  114. [d] if *d == dot => {}
  115. [d, e] if [*d, *e] == [dot; 2] => drop(parts.pop()),
  116. _ => parts.push(part),
  117. }
  118. }
  119. for part in parts {
  120. out.push(backslash);
  121. out.extend_from_slice(part);
  122. }
  123. out
  124. }
  125. /// The host path, NUL-terminated, for `path` (without its NUL) if it is on
  126. /// a virtual drive.
  127. pub(crate) fn translate(path: &[u16]) -> Option<Vec<u16>> {
  128. let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) {
  129. Some(rest) => (&VERBATIM[..], rest),
  130. None => (&[][..], path),
  131. };
  132. let &[letter, colon, ..] = rest else {
  133. return None;
  134. };
  135. if colon != u16::from(b':') {
  136. return None;
  137. }
  138. let letter = u8::try_from(letter).ok().filter(u8::is_ascii_alphabetic)?;
  139. let letter = u16::from(letter.to_ascii_uppercase());
  140. let drives = drives();
  141. let (_, root) = drives.iter().find(|(l, _)| *l == letter)?;
  142. let tail = &rest[2..];
  143. if prefix.is_empty() && root.len() + tail.len() >= LONG {
  144. let mut out = verbatim(root, tail);
  145. out.push(0);
  146. return Some(out);
  147. }
  148. let mut out = prefix.to_vec();
  149. out.extend_from_slice(root);
  150. // `X:` and `X:name` are relative to the root.
  151. if !tail.first().is_some_and(|c| SEPARATORS.contains(c)) {
  152. out.push(b'\\'.into());
  153. }
  154. let verbatim = !prefix.is_empty();
  155. out.extend(tail.iter().map(|&c| {
  156. if verbatim && c == u16::from(b'/') {
  157. b'\\'.into()
  158. } else {
  159. c
  160. }
  161. }));
  162. out.push(0);
  163. Some(out)
  164. }
  165. /// A title's wide path: the host path when it is on a virtual drive, else
  166. /// the title's own pointer.
  167. struct Wide(*const u16, Option<Vec<u16>>);
  168. impl Wide {
  169. fn ptr(&self) -> *const u16 {
  170. self.1.as_ref().map_or(self.0, |p| p.as_ptr())
  171. }
  172. }
  173. fn wide(path: *const u16) -> Wide {
  174. if path.is_null() {
  175. return Wide(path, None);
  176. }
  177. // SAFETY: the title passes a NUL-terminated path.
  178. let path_slice = unsafe {
  179. let len = (0..).take_while(|&i| *path.add(i) != 0).count();
  180. std::slice::from_raw_parts(path, len)
  181. };
  182. let host = translate(path_slice);
  183. trace(path_slice, host.as_deref());
  184. Wide(path, host)
  185. }
  186. /// Every title path at debug level, with the host path if rewritten.
  187. fn trace(path: &[u16], host: Option<&[u16]>) {
  188. tracing::debug!(
  189. path = %String::from_utf16_lossy(path),
  190. host = host.map(|h| String::from_utf16_lossy(&h[..h.len() - 1])),
  191. "title path"
  192. );
  193. }
  194. /// A narrow path (ANSI code page, as the host decodes it) on a virtual
  195. /// drive, as a wide host path.
  196. fn narrow(path: *const c_char) -> Option<Vec<u16>> {
  197. if path.is_null() {
  198. return None;
  199. }
  200. // SAFETY: the title passes a NUL-terminated path.
  201. let bytes = unsafe { CStr::from_ptr(path) }.to_bytes();
  202. // The drive part is ASCII in every code page; decode only candidates.
  203. match bytes.strip_prefix(br"\\?\").unwrap_or(bytes) {
  204. [letter, b':', ..] if letter.is_ascii_alphabetic() => {}
  205. _ => {
  206. tracing::debug!(path = %String::from_utf8_lossy(bytes), "title path");
  207. return None;
  208. }
  209. }
  210. let len = i32::try_from(bytes.len()).ok()?;
  211. // SAFETY: sizing call, then a call with room for `n` units.
  212. let wide = unsafe {
  213. let n = MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0);
  214. let mut wide = vec![0u16; usize::try_from(n).ok()?];
  215. MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n);
  216. wide
  217. };
  218. let host = translate(&wide);
  219. trace(&wide, host.as_deref());
  220. host
  221. }
  222. /// An ASCII mode string (`"rb"`, `"w, ccs=UTF-8"`) for a wide CRT call.
  223. fn widen(mode: *const c_char) -> Vec<u16> {
  224. if mode.is_null() {
  225. return vec![0];
  226. }
  227. // SAFETY: a NUL-terminated mode string.
  228. let bytes = unsafe { CStr::from_ptr(mode) }.to_bytes();
  229. bytes.iter().map(|&b| u16::from(b)).chain([0]).collect()
  230. }
  231. type Handle = *mut c_void;
  232. type File = *mut c_void;
  233. // kernel32 and its file API sets.
  234. pub extern "system" fn CreateFileW(
  235. path: *const u16,
  236. access: u32,
  237. share: u32,
  238. security: *const c_void,
  239. disposition: u32,
  240. flags: u32,
  241. template: Handle,
  242. ) -> Handle {
  243. let p = wide(path);
  244. host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)(
  245. p.ptr(),
  246. access,
  247. share,
  248. security,
  249. disposition,
  250. flags,
  251. template,
  252. )
  253. }
  254. pub extern "system" fn CreateFileA(
  255. path: *const c_char,
  256. access: u32,
  257. share: u32,
  258. security: *const c_void,
  259. disposition: u32,
  260. flags: u32,
  261. template: Handle,
  262. ) -> Handle {
  263. match narrow(path) {
  264. Some(p) => {
  265. host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)(
  266. p.as_ptr(),
  267. access,
  268. share,
  269. security,
  270. disposition,
  271. flags,
  272. template,
  273. )
  274. }
  275. None => {
  276. host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)(
  277. path,
  278. access,
  279. share,
  280. security,
  281. disposition,
  282. flags,
  283. template,
  284. )
  285. }
  286. }
  287. }
  288. /// Used by Bink.
  289. pub extern "system" fn CreateFile2(
  290. path: *const u16,
  291. access: u32,
  292. share: u32,
  293. disposition: u32,
  294. params: *const c_void,
  295. ) -> Handle {
  296. let p = wide(path);
  297. host!("kernel32.dll", "CreateFile2": extern "system" fn(*const u16, u32, u32, u32, *const c_void) -> Handle)(
  298. p.ptr(),
  299. access,
  300. share,
  301. disposition,
  302. params,
  303. )
  304. }
  305. pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 {
  306. match narrow(path) {
  307. Some(p) => {
  308. host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.as_ptr())
  309. }
  310. None => {
  311. host!("kernel32.dll", "DeleteFileA": extern "system" fn(*const c_char) -> i32)(path)
  312. }
  313. }
  314. }
  315. pub extern "system" fn DeleteFileW(path: *const u16) -> i32 {
  316. let p = wide(path);
  317. host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.ptr())
  318. }
  319. pub extern "system" fn RemoveDirectoryW(path: *const u16) -> i32 {
  320. let p = wide(path);
  321. host!("kernel32.dll", "RemoveDirectoryW": extern "system" fn(*const u16) -> i32)(p.ptr())
  322. }
  323. pub extern "system" fn SetFileAttributesW(path: *const u16, attributes: u32) -> i32 {
  324. let p = wide(path);
  325. host!("kernel32.dll", "SetFileAttributesW": extern "system" fn(*const u16, u32) -> i32)(
  326. p.ptr(),
  327. attributes,
  328. )
  329. }
  330. pub extern "system" fn GetFileAttributesA(path: *const c_char) -> u32 {
  331. match narrow(path) {
  332. Some(p) => {
  333. host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)(
  334. p.as_ptr(),
  335. )
  336. }
  337. None => {
  338. host!("kernel32.dll", "GetFileAttributesA": extern "system" fn(*const c_char) -> u32)(
  339. path,
  340. )
  341. }
  342. }
  343. }
  344. pub extern "system" fn CreateDirectoryW(path: *const u16, security: *const c_void) -> i32 {
  345. let p = wide(path);
  346. host!("kernel32.dll", "CreateDirectoryW": extern "system" fn(*const u16, *const c_void) -> i32)(
  347. p.ptr(),
  348. security,
  349. )
  350. }
  351. pub extern "system" fn GetFileAttributesExW(
  352. path: *const u16,
  353. level: i32,
  354. info: *mut c_void,
  355. ) -> i32 {
  356. let p = wide(path);
  357. host!("kernel32.dll", "GetFileAttributesExW": extern "system" fn(*const u16, i32, *mut c_void) -> i32)(
  358. p.ptr(),
  359. level,
  360. info,
  361. )
  362. }
  363. pub extern "system" fn GetFileAttributesW(path: *const u16) -> u32 {
  364. let p = wide(path);
  365. host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)(p.ptr())
  366. }
  367. pub extern "system" fn GetDiskFreeSpaceExW(
  368. path: *const u16,
  369. available: *mut u64,
  370. total: *mut u64,
  371. free: *mut u64,
  372. ) -> i32 {
  373. let p = wide(path);
  374. host!("kernel32.dll", "GetDiskFreeSpaceExW": extern "system" fn(*const u16, *mut u64, *mut u64, *mut u64) -> i32)(
  375. p.ptr(),
  376. available,
  377. total,
  378. free,
  379. )
  380. }
  381. /// Wants a volume root: a virtual drive answers for the host volume its
  382. /// folder is on.
  383. pub extern "system" fn GetDiskFreeSpaceW(
  384. root: *const u16,
  385. sectors_per_cluster: *mut u32,
  386. bytes_per_sector: *mut u32,
  387. free_clusters: *mut u32,
  388. clusters: *mut u32,
  389. ) -> i32 {
  390. let mut p = wide(root);
  391. if let Some(host) = &mut p.1
  392. && let [letter, colon, sep, ..] = host[..]
  393. && colon == u16::from(b':')
  394. && SEPARATORS.contains(&sep)
  395. {
  396. *host = vec![letter, colon, sep, 0];
  397. }
  398. host!("kernel32.dll", "GetDiskFreeSpaceW": extern "system" fn(*const u16, *mut u32, *mut u32, *mut u32, *mut u32) -> i32)(
  399. p.ptr(),
  400. sectors_per_cluster,
  401. bytes_per_sector,
  402. free_clusters,
  403. clusters,
  404. )
  405. }
  406. pub extern "system" fn FindFirstFileW(path: *const u16, data: *mut c_void) -> Handle {
  407. let p = wide(path);
  408. host!("kernel32.dll", "FindFirstFileW": extern "system" fn(*const u16, *mut c_void) -> Handle)(
  409. p.ptr(),
  410. data,
  411. )
  412. }
  413. pub extern "system" fn FindFirstFileExW(
  414. path: *const u16,
  415. level: i32,
  416. data: *mut c_void,
  417. search: i32,
  418. filter: *mut c_void,
  419. flags: u32,
  420. ) -> Handle {
  421. let p = wide(path);
  422. host!("kernel32.dll", "FindFirstFileExW": extern "system" fn(*const u16, i32, *mut c_void, i32, *mut c_void, u32) -> Handle)(
  423. p.ptr(),
  424. level,
  425. data,
  426. search,
  427. filter,
  428. flags,
  429. )
  430. }
  431. pub extern "system" fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32 {
  432. let (from, to) = (wide(from), wide(to));
  433. host!("kernel32.dll", "MoveFileExW": extern "system" fn(*const u16, *const u16, u32) -> i32)(
  434. from.ptr(),
  435. to.ptr(),
  436. flags,
  437. )
  438. }
  439. pub extern "system" fn SetCurrentDirectoryA(path: *const c_char) -> i32 {
  440. match narrow(path) {
  441. Some(p) => {
  442. host!("kernel32.dll", "SetCurrentDirectoryW": extern "system" fn(*const u16) -> i32)(
  443. p.as_ptr(),
  444. )
  445. }
  446. None => {
  447. host!("kernel32.dll", "SetCurrentDirectoryA": extern "system" fn(*const c_char) -> i32)(
  448. path,
  449. )
  450. }
  451. }
  452. }
  453. // The C runtime (ucrtbase, which the title's CRT imports bind to).
  454. pub extern "C" fn _wfopen(path: *const u16, mode: *const u16) -> File {
  455. let p = wide(path);
  456. host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)(p.ptr(), mode)
  457. }
  458. pub extern "C" fn _wfopen_s(out: *mut File, path: *const u16, mode: *const u16) -> i32 {
  459. let p = wide(path);
  460. host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)(
  461. out,
  462. p.ptr(),
  463. mode,
  464. )
  465. }
  466. pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> File {
  467. let p = wide(path);
  468. host!("ucrtbase.dll", "_wfsopen": extern "C" fn(*const u16, *const u16, i32) -> File)(
  469. p.ptr(),
  470. mode,
  471. share,
  472. )
  473. }
  474. // Kernel reads into title memory. The GPU side leaves blocks of title GPU
  475. // buffers read-only to see the title's next write, and the kernel's writes
  476. // fail there instead of faulting into its handler; the title's
  477. // synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned
  478. // destinations and retry a failed `ReadFile` forever. So the destination
  479. // is opened first, and not guarded again before the call is done.
  480. pub extern "system" fn ReadFile(
  481. file: *mut c_void,
  482. buffer: *mut u8,
  483. len: u32,
  484. read: *mut u32,
  485. overlapped: *mut c_void,
  486. ) -> i32 {
  487. let writing = victory_gpu::kernel_writing(buffer as usize, len as usize);
  488. let done = host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)(
  489. file, buffer, len, read, overlapped,
  490. );
  491. // The call's error is the title's to ask for.
  492. // SAFETY: plain calls.
  493. let error = unsafe { windows_sys::Win32::Foundation::GetLastError() };
  494. // shortcut: a read that goes on after the call (overlapped) is written
  495. // into pages the kernel has locked by now: it lands all the same, but a
  496. // refresh that guards its blocks before it does will not see it.
  497. if done == 0 && error == windows_sys::Win32::Foundation::ERROR_IO_PENDING {
  498. static ONCE: std::sync::Once = std::sync::Once::new();
  499. ONCE.call_once(|| tracing::info!(len, "ReadFile: a read of the title's goes on after the call"));
  500. }
  501. if done == 0 && error == windows_sys::Win32::Foundation::ERROR_NOACCESS {
  502. static FAILED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  503. let n = FAILED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  504. if n.is_power_of_two() {
  505. tracing::warn!(n, buffer = format_args!("{buffer:p}"), len, "ReadFile: the title's buffer could not be written");
  506. }
  507. }
  508. drop(writing);
  509. // SAFETY: as above.
  510. unsafe { windows_sys::Win32::Foundation::SetLastError(error) };
  511. done
  512. }
  513. /// The host CRT reads large requests straight into the caller's buffer.
  514. pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize {
  515. let _writing = victory_gpu::kernel_writing(buffer as usize, size.saturating_mul(count));
  516. host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)(
  517. buffer, size, count, stream,
  518. )
  519. }
  520. pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File {
  521. match narrow(path) {
  522. Some(p) => host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)(
  523. p.as_ptr(),
  524. widen(mode).as_ptr(),
  525. ),
  526. None => {
  527. host!("ucrtbase.dll", "fopen": extern "C" fn(*const c_char, *const c_char) -> File)(
  528. path, mode,
  529. )
  530. }
  531. }
  532. }
  533. pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_char) -> i32 {
  534. match narrow(path) {
  535. Some(p) => {
  536. host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)(
  537. out,
  538. p.as_ptr(),
  539. widen(mode).as_ptr(),
  540. )
  541. }
  542. None => {
  543. host!("ucrtbase.dll", "fopen_s": extern "C" fn(*mut File, *const c_char, *const c_char) -> i32)(
  544. out, path, mode,
  545. )
  546. }
  547. }
  548. }
  549. /// `_open(path, flags[, mode])` is variadic; on x64 the optional integer
  550. /// travels in the same register either way, so it is passed on as is.
  551. pub extern "C" fn _open(path: *const c_char, flags: i32, mode: i32) -> i32 {
  552. match narrow(path) {
  553. Some(p) => host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)(
  554. p.as_ptr(),
  555. flags,
  556. mode,
  557. ),
  558. None => host!("ucrtbase.dll", "_open": extern "C" fn(*const c_char, i32, i32) -> i32)(
  559. path, flags, mode,
  560. ),
  561. }
  562. }
  563. /// See [`_open`]; used by libHttpClient.
  564. pub extern "C" fn _wopen(path: *const u16, flags: i32, mode: i32) -> i32 {
  565. let p = wide(path);
  566. host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)(
  567. p.ptr(),
  568. flags,
  569. mode,
  570. )
  571. }
  572. pub extern "C" fn _wstat64(path: *const u16, stat: *mut c_void) -> i32 {
  573. let p = wide(path);
  574. host!("ucrtbase.dll", "_wstat64": extern "C" fn(*const u16, *mut c_void) -> i32)(p.ptr(), stat)
  575. }
  576. pub extern "C" fn _stat64i32(path: *const c_char, stat: *mut c_void) -> i32 {
  577. match narrow(path) {
  578. Some(p) => {
  579. host!("ucrtbase.dll", "_wstat64i32": extern "C" fn(*const u16, *mut c_void) -> i32)(
  580. p.as_ptr(),
  581. stat,
  582. )
  583. }
  584. None => {
  585. host!("ucrtbase.dll", "_stat64i32": extern "C" fn(*const c_char, *mut c_void) -> i32)(
  586. path, stat,
  587. )
  588. }
  589. }
  590. }
  591. pub extern "C" fn remove(path: *const c_char) -> i32 {
  592. match narrow(path) {
  593. Some(p) => host!("ucrtbase.dll", "_wremove": extern "C" fn(*const u16) -> i32)(p.as_ptr()),
  594. None => host!("ucrtbase.dll", "remove": extern "C" fn(*const c_char) -> i32)(path),
  595. }
  596. }
  597. pub extern "C" fn _wchmod(path: *const u16, mode: i32) -> i32 {
  598. let p = wide(path);
  599. host!("ucrtbase.dll", "_wchmod": extern "C" fn(*const u16, i32) -> i32)(p.ptr(), mode)
  600. }
  601. pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 {
  602. let p = wide(path);
  603. host!("ucrtbase.dll", "_wutime64": extern "C" fn(*const u16, *mut c_void) -> i32)(
  604. p.ptr(),
  605. times,
  606. )
  607. }
  608. // The C++ library: `std::basic_filebuf::open` goes through `_Fiopen`.
  609. const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z";
  610. const FIOPEN_WIDE: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z";
  611. /// `_Fiopen(const wchar_t* path, ios_base::openmode, int protection)`.
  612. extern "C" fn fiopen_wide(path: *const u16, mode: i32, protection: i32) -> File {
  613. let p = wide(path);
  614. host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)(
  615. p.ptr(),
  616. mode,
  617. protection,
  618. )
  619. }
  620. /// `_Fiopen(const char* path, ios_base::openmode, int protection)`.
  621. extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File {
  622. match narrow(path) {
  623. Some(p) => {
  624. host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)(
  625. p.as_ptr(),
  626. mode,
  627. protection,
  628. )
  629. }
  630. None => {
  631. host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)(
  632. path, mode, protection,
  633. )
  634. }
  635. }
  636. }
  637. pub(crate) fn module() -> HleModule {
  638. HleModule {
  639. name: "files",
  640. dlls: &[
  641. "kernel32.dll",
  642. "kernelbase.dll",
  643. "api-ms-win-core-file-*",
  644. "api-ms-win-core-processenvironment-*",
  645. "ucrtbase.dll",
  646. "api-ms-win-crt-stdio-*",
  647. "api-ms-win-crt-filesystem-*",
  648. "api-ms-win-crt-time-*",
  649. "msvcp140.dll",
  650. ],
  651. exports: vec![
  652. hle_export!(ReadFile),
  653. hle_export!(fread),
  654. hle_export!(CreateFileW),
  655. hle_export!(CreateFileA),
  656. hle_export!(CreateFile2),
  657. hle_export!(DeleteFileA),
  658. hle_export!(DeleteFileW),
  659. hle_export!(RemoveDirectoryW),
  660. hle_export!(SetFileAttributesW),
  661. hle_export!(GetFileAttributesA),
  662. hle_export!(CreateDirectoryW),
  663. hle_export!(GetFileAttributesW),
  664. hle_export!(GetFileAttributesExW),
  665. hle_export!(GetDiskFreeSpaceExW),
  666. hle_export!(GetDiskFreeSpaceW),
  667. hle_export!(FindFirstFileW),
  668. hle_export!(FindFirstFileExW),
  669. hle_export!(MoveFileExW),
  670. hle_export!(SetCurrentDirectoryA),
  671. hle_export!(_wfopen),
  672. hle_export!(_wfopen_s),
  673. hle_export!(_wfsopen),
  674. hle_export!(fopen),
  675. hle_export!(fopen_s),
  676. hle_export!(_open),
  677. hle_export!(_wopen),
  678. hle_export!(_wstat64),
  679. hle_export!(_stat64i32),
  680. hle_export!(remove),
  681. hle_export!(_wchmod),
  682. hle_export!(_wutime64),
  683. HleExport {
  684. name: FIOPEN,
  685. address: fiopen as *const () as usize,
  686. },
  687. HleExport {
  688. name: FIOPEN_WIDE,
  689. address: fiopen_wide as *const () as usize,
  690. },
  691. ],
  692. }
  693. }
  694. #[cfg(test)]
  695. mod tests {
  696. use super::*;
  697. fn w(s: &str) -> Vec<u16> {
  698. s.encode_utf16().chain([0]).collect()
  699. }
  700. #[test]
  701. fn kernel_reads_reach_the_buffer() {
  702. use std::os::windows::io::AsRawHandle;
  703. let dir = tempfile::tempdir().unwrap();
  704. let path = dir.path().join("data.bin");
  705. std::fs::write(&path, b"0123456789").unwrap();
  706. let file = std::fs::File::open(&path).unwrap();
  707. let (mut out, mut n) = ([0u8; 10], 0);
  708. let handle = file.as_raw_handle().cast();
  709. assert_ne!(ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), 0);
  710. assert_eq!((&out, n), (b"0123456789", 10));
  711. }
  712. fn text(v: &[u16]) -> String {
  713. String::from_utf16_lossy(&v[..v.len() - 1])
  714. }
  715. #[test]
  716. fn rewrites_only_paths_on_mounted_drives() {
  717. let dir = tempfile::tempdir().unwrap();
  718. let root = dir.path().to_string_lossy().into_owned();
  719. let letter = mount(dir.path()).unwrap();
  720. assert_eq!(
  721. mount(dir.path()),
  722. Some(letter),
  723. "mounting twice reuses the letter"
  724. );
  725. let tr = |s: String| translate(&w(&s)[..s.encode_utf16().count()]).map(|v| text(&v));
  726. assert_eq!(
  727. tr(format!("{letter}:/a/b.txt")),
  728. Some(format!("{root}/a/b.txt"))
  729. );
  730. let lower = letter.to_ascii_lowercase();
  731. assert_eq!(tr(format!("{lower}:\\a")), Some(format!("{root}\\a")));
  732. assert_eq!(tr(format!("{letter}:")), Some(format!("{root}\\")));
  733. assert_eq!(
  734. tr(format!(r"\\?\{letter}:/a/b")),
  735. Some(format!(r"\\?\{root}\a\b"))
  736. );
  737. assert_eq!(tr(r"C:\Windows".into()), None);
  738. assert_eq!(tr("relative/path".into()), None);
  739. assert_eq!(tr(String::new()), None);
  740. // Fixed letters, as the console's package drive; a later mount of
  741. // the same letter replaces the earlier one.
  742. let package = tempfile::tempdir().unwrap();
  743. mount_at('g', dir.path());
  744. mount_at('G', package.path());
  745. assert_eq!(
  746. tr(r"G:\appdata0.rpf".into()),
  747. Some(format!(r"{}\appdata0.rpf", package.path().display()))
  748. );
  749. assert_ne!(mount(dir.path()), Some('G'), "free letters skip fixed ones");
  750. // Long ones take the `\\?\` form, cleaned up as the host would.
  751. let long = "d".repeat(250);
  752. assert_eq!(
  753. tr(format!(r"G:/a/./b/../{long}//f")),
  754. Some(format!(r"\\?\{}\a\{long}\f", package.path().display()))
  755. );
  756. assert_eq!(
  757. verbatim(&w(r"\\server\share\")[..15], &w("/x/../../y")[..10]),
  758. w(r"\\?\UNC\server\share\y")[..22].to_vec()
  759. );
  760. }
  761. #[test]
  762. fn long_title_paths_work_on_the_host() {
  763. let dir = tempfile::tempdir().unwrap();
  764. let letter = mount(dir.path()).unwrap();
  765. let deep = format!("{letter}:/{}/{}", "a".repeat(200), "b".repeat(100));
  766. let null = std::ptr::null_mut();
  767. let first = w(&deep[..203]);
  768. assert_ne!(CreateDirectoryW(first.as_ptr(), null), 0);
  769. assert_ne!(CreateDirectoryW(w(&deep).as_ptr(), null), 0);
  770. let file = format!("{deep}/../{}/f.txt", "b".repeat(100));
  771. let f = _wfopen(w(&file).as_ptr(), w("wb").as_ptr());
  772. assert!(!f.is_null(), "{file}");
  773. host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32)(f);
  774. assert_ne!(DeleteFileW(w(&format!("{deep}/f.txt")).as_ptr()), 0);
  775. assert_ne!(RemoveDirectoryW(w(&deep).as_ptr()), 0);
  776. }
  777. #[test]
  778. fn title_file_calls_land_in_the_host_folder() {
  779. let dir = tempfile::tempdir().unwrap();
  780. let letter = mount(dir.path()).unwrap();
  781. const GENERIC_WRITE: u32 = 0x4000_0000;
  782. const CREATE_ALWAYS: u32 = 2;
  783. let close = host!("kernel32.dll", "CloseHandle": extern "system" fn(Handle) -> i32);
  784. let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32);
  785. let path = w(&format!(r"{letter}:\created.bin"));
  786. let null = std::ptr::null_mut();
  787. let h = CreateFileW(
  788. path.as_ptr(),
  789. GENERIC_WRITE,
  790. 0,
  791. null,
  792. CREATE_ALWAYS,
  793. 0,
  794. null,
  795. );
  796. assert_ne!(h as isize, -1);
  797. close(h);
  798. assert!(dir.path().join("created.bin").is_file());
  799. let path = format!("{letter}:/opened.txt\0");
  800. let f = fopen(path.as_ptr().cast(), c"wb".as_ptr());
  801. assert!(!f.is_null());
  802. fclose(f);
  803. assert!(dir.path().join("opened.txt").is_file());
  804. let path = format!("{letter}:/stream.txt\0");
  805. const OUT: i32 = 2;
  806. let f = fiopen(path.as_ptr().cast(), OUT, 0x40);
  807. assert!(!f.is_null());
  808. fclose(f);
  809. assert!(dir.path().join("stream.txt").is_file());
  810. assert_eq!(remove(path.as_ptr().cast()), 0);
  811. assert!(!dir.path().join("stream.txt").exists());
  812. let f = fiopen_wide(w(&format!("{letter}:/wide.txt")).as_ptr(), OUT, 0x40);
  813. assert!(!f.is_null());
  814. fclose(f);
  815. assert!(dir.path().join("wide.txt").is_file());
  816. const OPEN_EXISTING: u32 = 3;
  817. let path = w(&format!(r"{letter}:\created.bin"));
  818. let h = CreateFile2(path.as_ptr(), GENERIC_WRITE, 0, OPEN_EXISTING, null);
  819. assert_ne!(h as isize, -1);
  820. close(h);
  821. const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX;
  822. assert_ne!(GetFileAttributesW(path.as_ptr()), INVALID_FILE_ATTRIBUTES);
  823. const O_WRONLY: i32 = 1;
  824. const O_CREAT: i32 = 0x100;
  825. const S_IWRITE: i32 = 0x80;
  826. let path = format!("{letter}:/low.bin\0");
  827. let fd = _open(path.as_ptr().cast(), O_WRONLY | O_CREAT, S_IWRITE);
  828. assert!(fd >= 0);
  829. host!("ucrtbase.dll", "_close": extern "C" fn(i32) -> i32)(fd);
  830. assert!(dir.path().join("low.bin").is_file());
  831. // Other paths pass through untouched.
  832. let host_path = format!("{}\0", dir.path().join("plain.txt").display());
  833. let f = fopen(host_path.as_ptr().cast(), c"wb".as_ptr());
  834. assert!(!f.is_null());
  835. fclose(f);
  836. assert!(dir.path().join("plain.txt").is_file());
  837. }
  838. /// A narrow path is rewritten once, as its wide twin is. The inner
  839. /// drive's folder lies on the outer virtual drive, as the title folder
  840. /// does when it sits on a host `G:` drive and is mounted as `G:`. The
  841. /// outer letter is no host drive, so the host finds nothing there; a
  842. /// narrow call that reaches the outer folder rewrote the path twice.
  843. #[test]
  844. fn narrow_paths_are_rewritten_once() {
  845. let dir = tempfile::tempdir().unwrap();
  846. let folder = dir.path().join("inner");
  847. std::fs::create_dir(&folder).unwrap();
  848. std::fs::write(folder.join("present.txt"), b"").unwrap();
  849. let outer = mount(dir.path()).unwrap();
  850. let inner = mount(Path::new(&format!(r"{outer}:\inner"))).unwrap();
  851. let path = |name: &str| format!("{inner}:/{name}\0");
  852. const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX;
  853. let wide = GetFileAttributesW(w(&format!("{inner}:/present.txt")).as_ptr());
  854. assert_eq!(wide, INVALID_FILE_ATTRIBUTES);
  855. let narrow = GetFileAttributesA(path("present.txt").as_ptr().cast());
  856. assert_eq!(narrow, wide, "GetFileAttributesA agrees with its wide twin");
  857. const GENERIC_WRITE: u32 = 0x4000_0000;
  858. const CREATE_ALWAYS: u32 = 2;
  859. let null = std::ptr::null_mut();
  860. let h = CreateFileA(
  861. path("a.bin").as_ptr().cast(),
  862. GENERIC_WRITE,
  863. 0,
  864. null,
  865. CREATE_ALWAYS,
  866. 0,
  867. null,
  868. );
  869. assert_eq!(h as isize, -1);
  870. assert!(fopen(path("b.txt").as_ptr().cast(), c"wb".as_ptr()).is_null());
  871. let mut f: File = std::ptr::null_mut();
  872. let error = fopen_s(&mut f, path("c.txt").as_ptr().cast(), c"wb".as_ptr());
  873. assert_ne!(error, 0);
  874. const OUT: i32 = 2;
  875. assert!(fiopen(path("d.txt").as_ptr().cast(), OUT, 0x40).is_null());
  876. // Nothing was made behind a path rewritten twice.
  877. let names: Vec<_> = std::fs::read_dir(&folder)
  878. .unwrap()
  879. .map(|e| e.unwrap().file_name())
  880. .collect();
  881. assert_eq!(names, ["present.txt"]);
  882. }
  883. }