files.rs 35 KB

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