xgamesave.rs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. //! XGameSave: the user's game saves, kept on the host under the title's
  2. //! data directory, next to persistent local storage (`runtime::Title::
  3. //! saves`), never in the cache. A provider is a folder per user and
  4. //! service configuration, a container a folder in it.
  5. //!
  6. //! An update is all or nothing, as documented: each one writes a complete
  7. //! new version of the container (`v<N>.new/`, unchanged blobs hard-linked
  8. //! from the previous version), flushed to disk, and one directory rename
  9. //! commits it (`v<N>`); the highest committed version is the container.
  10. //! A crash leaves the old version or the new one, never a mix; leftovers
  11. //! are removed on sight. Deleting a container renames it away first.
  12. //!
  13. //! Names are exact: a version's `manifest` holds the container's name, its
  14. //! display name and the blob names (blob `i` is the file `i`), so case,
  15. //! characters the host forbids, reserved device names and length never
  16. //! reach a file name. A container's folder is its name made safe (and
  17. //! shortened) plus a hash of the exact name, so names differing only in
  18. //! case get different folders. Offline there is no cloud copy, so nothing
  19. //! ever needs a sync.
  20. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  21. use std::ffi::{CString, c_char, c_void};
  22. use std::io::Write as _;
  23. use std::path::{Path, PathBuf};
  24. use std::sync::Mutex;
  25. use super::xasync::{self, AsyncBlock, E_INVALIDARG};
  26. use super::xgameruntime::{
  27. Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text,
  28. };
  29. use super::{storage, xuser};
  30. use crate::runtime;
  31. pub const PROVIDER: Guid = Guid::new(
  32. 0x704c_3f58,
  33. 0xe629,
  34. 0x4cc2,
  35. [0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2],
  36. );
  37. /// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes
  38. /// the public API's arguments in the same order as under the provider's
  39. /// own id (older titles).
  40. pub const IID_2026: Guid = Guid::new(
  41. 0x1bff_f3af,
  42. 0xf14a,
  43. 0x40a3,
  44. [0x8e, 0x35, 0x9a, 0xda, 0x90, 0x65, 0x93, 0xf9],
  45. );
  46. pub static OBJECT: Object = Object::new("game save", &VTABLE);
  47. pub const INTERFACES: &[Interface] =
  48. &[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
  49. // The public API's error codes.
  50. pub const INVALID_CONTAINER_NAME: HRESULT = 0x8083_0001_u32 as i32;
  51. pub const NO_ACCESS: HRESULT = 0x8083_0002_u32 as i32;
  52. pub const OUT_OF_LOCAL_STORAGE: HRESULT = 0x8083_0003_u32 as i32;
  53. pub const UPDATE_TOO_BIG: HRESULT = 0x8083_0005_u32 as i32;
  54. pub const QUOTA_EXCEEDED: HRESULT = 0x8083_0006_u32 as i32;
  55. pub const BUFFER_TOO_SMALL: HRESULT = 0x8083_0007_u32 as i32;
  56. pub const BLOB_NOT_FOUND: HRESULT = 0x8083_0008_u32 as i32;
  57. /// Per user and title, as documented.
  58. const QUOTA: u64 = 256 << 20;
  59. /// What one update may write in all, as documented.
  60. const MAX_UPDATE: usize = 16 << 20;
  61. const MANIFEST: &str = "manifest";
  62. /// Readable part of a container's folder name, at most.
  63. const READABLE: usize = 100;
  64. /// Every save operation, so none sees another's half-made version.
  65. static SAVES: Mutex<()> = Mutex::new(());
  66. fn saves_lock() -> std::sync::MutexGuard<'static, ()> {
  67. SAVES.lock().unwrap_or_else(|e| e.into_inner())
  68. }
  69. /// `name` as a file name: letters, digits, `-` and `_` stay, every other
  70. /// byte becomes `%XX`. The result never contains a dot.
  71. fn file_name(name: &str) -> String {
  72. name.bytes()
  73. .map(|b| match b {
  74. b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' => (b as char).to_string(),
  75. _ => format!("%{b:02X}"),
  76. })
  77. .collect()
  78. }
  79. /// The name behind a file name from [`file_name`]; `None` for other files.
  80. fn decode(file: &str) -> Option<String> {
  81. if file.contains('.') {
  82. return None;
  83. }
  84. let mut out = Vec::new();
  85. let mut bytes = file.bytes();
  86. while let Some(b) = bytes.next() {
  87. if b == b'%' {
  88. let hex = [bytes.next()?, bytes.next()?];
  89. out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?);
  90. } else {
  91. out.push(b);
  92. }
  93. }
  94. String::from_utf8(out).ok()
  95. }
  96. /// The container's folder: its name made safe, cut short, then `~` and a
  97. /// hash of the exact name (64-bit FNV-1a, stable across builds).
  98. fn container_dir(root: &Path, name: &str) -> PathBuf {
  99. let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
  100. (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
  101. });
  102. let mut readable = file_name(name);
  103. readable.truncate(READABLE); // ASCII only
  104. root.join(format!("{readable}~{hash:016x}"))
  105. }
  106. /// Documented: the path part (up to the last `/`) letters, digits, `_` and
  107. /// `/`; the file part letters, digits, `_`, `.` and `-`, not empty, not
  108. /// ending in `.`, no `..`; 256 characters at most.
  109. fn valid_container(name: &str) -> bool {
  110. let (path, file) = name.rsplit_once('/').unwrap_or(("", name));
  111. name.len() <= 256
  112. && path
  113. .bytes()
  114. .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'/')
  115. && !file.is_empty()
  116. && !file.ends_with('.')
  117. && !file.contains("..")
  118. && file
  119. .bytes()
  120. .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
  121. }
  122. /// A committed version of a container.
  123. struct Version {
  124. dir: PathBuf,
  125. number: u64,
  126. name: String,
  127. display: String,
  128. /// Blob names; blob `i` is the file `i`.
  129. blobs: Vec<String>,
  130. }
  131. impl Version {
  132. fn blob(&self, i: usize) -> PathBuf {
  133. self.dir.join(i.to_string())
  134. }
  135. fn sizes(&self) -> Vec<(String, u64)> {
  136. let size = |i| std::fs::metadata(self.blob(i)).map_or(0, |m| m.len());
  137. let blobs = self.blobs.iter().enumerate();
  138. blobs.map(|(i, n)| (n.clone(), size(i))).collect()
  139. }
  140. }
  141. /// The manifest: length-prefixed strings (u32 LE): container name, display
  142. /// name, then each blob name.
  143. fn manifest(name: &str, display: &str, blobs: &[&str]) -> Vec<u8> {
  144. let mut out = Vec::new();
  145. for s in [name, display].into_iter().chain(blobs.iter().copied()) {
  146. out.extend_from_slice(&(s.len() as u32).to_le_bytes());
  147. out.extend_from_slice(s.as_bytes());
  148. }
  149. out
  150. }
  151. fn parse_manifest(bytes: &[u8]) -> Option<Vec<String>> {
  152. let mut out = Vec::new();
  153. let mut rest = bytes;
  154. while !rest.is_empty() {
  155. let (len, tail) = rest.split_first_chunk::<4>()?;
  156. let len = u32::from_le_bytes(*len) as usize;
  157. out.push(String::from_utf8(tail.get(..len)?.to_vec()).ok()?);
  158. rest = &tail[len..];
  159. }
  160. (out.len() >= 2).then_some(out)
  161. }
  162. /// The container's newest committed version, if any. Removes what a crash
  163. /// left: unfinished versions and older ones.
  164. fn current(dir: &Path) -> std::io::Result<Option<Version>> {
  165. let mut committed = Vec::new();
  166. for entry in std::fs::read_dir(dir)?.flatten() {
  167. let file = entry.file_name();
  168. let file = file.to_string_lossy();
  169. if file.ends_with(".new") {
  170. std::fs::remove_dir_all(entry.path())?;
  171. } else if let Some(n) = file.strip_prefix('v').and_then(|n| n.parse::<u64>().ok()) {
  172. committed.push(n);
  173. }
  174. }
  175. committed.sort_unstable();
  176. let Some(&number) = committed.last() else {
  177. return Ok(None);
  178. };
  179. for old in &committed[..committed.len() - 1] {
  180. std::fs::remove_dir_all(dir.join(format!("v{old}")))?;
  181. }
  182. let version = dir.join(format!("v{number}"));
  183. let bad = || std::io::Error::new(std::io::ErrorKind::InvalidData, "bad save manifest");
  184. let mut names = parse_manifest(&std::fs::read(version.join(MANIFEST))?).ok_or_else(bad)?;
  185. let blobs = names.split_off(2);
  186. let [name, display] = <[String; 2]>::try_from(names).map_err(|_| bad())?;
  187. Ok(Some(Version {
  188. dir: version,
  189. number,
  190. name,
  191. display,
  192. blobs,
  193. }))
  194. }
  195. /// The version of container `name` in `dir`; none for a missing container
  196. /// or another name that hashes alike.
  197. fn current_named(dir: &Path, name: &str) -> std::io::Result<Option<Version>> {
  198. match current(dir) {
  199. Ok(v) => Ok(v.filter(|v| v.name == name)),
  200. Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
  201. Err(e) => Err(e),
  202. }
  203. }
  204. /// Where a crash test stops the process (test builds only).
  205. fn step() {
  206. #[cfg(test)]
  207. tests::crash_point();
  208. }
  209. /// A blob of a new version: new data, or the previous version's file.
  210. enum Source<'a> {
  211. Data(&'a [u8]),
  212. Kept(PathBuf),
  213. }
  214. /// Writes version `number` of the container in `dir` and commits it.
  215. fn commit(
  216. dir: &Path,
  217. number: u64,
  218. name: &str,
  219. display: &str,
  220. blobs: &[(&str, Source<'_>)],
  221. ) -> std::io::Result<()> {
  222. let staged = dir.join(format!("v{number}.new"));
  223. if staged.exists() {
  224. std::fs::remove_dir_all(&staged)?;
  225. }
  226. std::fs::create_dir_all(&staged)?;
  227. let write = |path: PathBuf, data: &[u8]| -> std::io::Result<()> {
  228. let mut file = std::fs::File::create(path)?;
  229. file.write_all(data)?;
  230. file.sync_all()
  231. };
  232. for (i, (_, source)) in blobs.iter().enumerate() {
  233. let path = staged.join(i.to_string());
  234. match source {
  235. Source::Data(data) => write(path, data)?,
  236. // Files are never changed in place, so sharing one is safe.
  237. Source::Kept(from) => std::fs::hard_link(from, &path)
  238. .or_else(|_| std::fs::copy(from, &path).map(drop))?,
  239. }
  240. step();
  241. }
  242. let names: Vec<&str> = blobs.iter().map(|(n, _)| *n).collect();
  243. write(staged.join(MANIFEST), &manifest(name, display, &names))?;
  244. step();
  245. std::fs::rename(&staged, dir.join(format!("v{number}")))?;
  246. step();
  247. Ok(())
  248. }
  249. /// The containers under a provider's root, by exact name; containers in
  250. /// the old one-file-per-blob layout are converted first.
  251. fn containers(root: &Path) -> Vec<(String, PathBuf)> {
  252. let mut out = Vec::new();
  253. for entry in std::fs::read_dir(root).into_iter().flatten().flatten() {
  254. let path = entry.path();
  255. let file = entry.file_name().to_string_lossy().into_owned();
  256. if !path.is_dir() {
  257. continue;
  258. }
  259. if file.ends_with(".gone") {
  260. let _ = std::fs::remove_dir_all(&path);
  261. } else if file.contains('~') {
  262. if let Ok(Some(v)) = current(&path) {
  263. out.push((v.name, path));
  264. }
  265. } else if let Some(name) = decode(&file)
  266. && let Some(dir) = migrate(root, &name, &path)
  267. {
  268. out.push((name, dir));
  269. }
  270. }
  271. out.sort();
  272. out
  273. }
  274. /// Moves a container of the old layout (blob files named by encoded name,
  275. /// a `.display` file) into a committed version, then removes it.
  276. fn migrate(root: &Path, name: &str, old: &Path) -> Option<PathBuf> {
  277. let dir = container_dir(root, name);
  278. let done = current_named(&dir, name).ok()?.is_some(); // a crash after the commit
  279. if !done {
  280. let display = std::fs::read_to_string(old.join(".display")).unwrap_or_default();
  281. let mut blobs: Vec<(String, Vec<u8>)> = std::fs::read_dir(old)
  282. .ok()?
  283. .flatten()
  284. .filter_map(|e| {
  285. let blob = decode(e.file_name().to_str()?)?;
  286. Some((blob, std::fs::read(e.path()).ok()?))
  287. })
  288. .collect();
  289. blobs.sort();
  290. let sources: Vec<_> = blobs
  291. .iter()
  292. .map(|(n, d)| (n.as_str(), Source::Data(d)))
  293. .collect();
  294. commit(&dir, 1, name, &display, &sources).ok()?;
  295. }
  296. std::fs::remove_dir_all(old).ok()?;
  297. tracing::info!(container = name, "game save moved to the versioned layout");
  298. Some(dir)
  299. }
  300. fn used_bytes(root: &Path) -> u64 {
  301. containers(root)
  302. .iter()
  303. .filter_map(|(name, dir)| current_named(dir, name).ok().flatten())
  304. .map(|v| v.sizes().iter().map(|(_, size)| size).sum::<u64>())
  305. .sum()
  306. }
  307. struct Provider {
  308. root: PathBuf,
  309. }
  310. struct Container {
  311. name: String,
  312. dir: PathBuf,
  313. }
  314. struct Update {
  315. name: String,
  316. dir: PathBuf,
  317. display: Option<String>,
  318. /// Blob writes (`Some`) and deletions (`None`), in order.
  319. changes: Vec<(String, Option<Vec<u8>>)>,
  320. }
  321. /// A handle we gave out.
  322. fn get<'a, T>(handle: *const T) -> Option<&'a T> {
  323. // SAFETY: handles are boxes we created and the title has not closed.
  324. unsafe { handle.as_ref() }
  325. }
  326. fn give<T>(value: T) -> *mut T {
  327. Box::into_raw(Box::new(value))
  328. }
  329. fn take<T>(handle: *mut T) {
  330. if !handle.is_null() {
  331. // SAFETY: as in `get`; closing ends the handle.
  332. drop(unsafe { Box::from_raw(handle) });
  333. }
  334. }
  335. impl Provider {
  336. /// The provider for the only user and `config` (the service
  337. /// configuration id), under `saves`. An empty id names no
  338. /// configuration, like none: as a folder name it would be the user's
  339. /// folder itself, where the other configurations' folders are.
  340. fn open(saves: &Path, config: Option<&str>) -> Result<Provider, HRESULT> {
  341. let config = config.filter(|c| !c.is_empty()).unwrap_or("default");
  342. let root = saves
  343. .join(format!("{:016X}", xuser::XUID))
  344. .join(file_name(config));
  345. std::fs::create_dir_all(&root).map_err(|_| NO_ACCESS)?;
  346. let _saves = saves_lock();
  347. containers(&root); // converts old containers now
  348. Ok(Provider { root })
  349. }
  350. fn remaining(&self) -> u64 {
  351. let _saves = saves_lock();
  352. remaining(&self.root)
  353. }
  354. fn container(&self, name: &str) -> Container {
  355. Container {
  356. name: name.to_owned(),
  357. dir: container_dir(&self.root, name),
  358. }
  359. }
  360. }
  361. /// Quota left under a provider's root, or less if the host disk is fuller.
  362. fn remaining(root: &Path) -> u64 {
  363. QUOTA
  364. .saturating_sub(used_bytes(root))
  365. .min(storage::disk_free(root))
  366. }
  367. /// Why an update writing `written` bytes, `replaced` of them over blobs it
  368. /// replaces, does not fit: past the per-user quota (`used` bytes kept), or
  369. /// past the host disk's `free` bytes, which is not the user's quota (the
  370. /// new version is written before the old one goes, so nothing it replaces
  371. /// counts there).
  372. fn no_room(written: u64, replaced: u64, used: u64, free: u64) -> Option<HRESULT> {
  373. if written > QUOTA.saturating_sub(used) + replaced {
  374. Some(QUOTA_EXCEEDED)
  375. } else if written > free {
  376. Some(OUT_OF_LOCAL_STORAGE)
  377. } else {
  378. None
  379. }
  380. }
  381. fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT {
  382. tracing::warn!(dir = %dir.display(), %e, "game save");
  383. if e.kind() == std::io::ErrorKind::StorageFull {
  384. OUT_OF_LOCAL_STORAGE
  385. } else {
  386. NO_ACCESS
  387. }
  388. }
  389. impl Update {
  390. /// Applies the update as one new version of the container.
  391. fn submit(&self) -> HRESULT {
  392. let _saves = saves_lock();
  393. let current = match current(&self.dir) {
  394. Ok(v) => v,
  395. Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
  396. Err(e) => return io_error(&self.dir, &e),
  397. };
  398. if current.as_ref().is_some_and(|v| v.name != self.name) {
  399. // Another container's name hashes alike: never mix the two.
  400. return NO_ACCESS;
  401. }
  402. // The blobs after the update: name → new data or the kept file.
  403. let mut blobs: Vec<(&str, Source<'_>)> = current
  404. .iter()
  405. .flat_map(|v| {
  406. let kept = v.blobs.iter().enumerate();
  407. kept.map(|(i, n)| (n.as_str(), Source::Kept(v.blob(i))))
  408. })
  409. .collect();
  410. for (name, data) in &self.changes {
  411. blobs.retain(|(n, _)| n != name);
  412. if let Some(data) = data {
  413. blobs.push((name, Source::Data(data)));
  414. }
  415. }
  416. blobs.sort_by(|a, b| a.0.cmp(b.0));
  417. let written: usize = blobs
  418. .iter()
  419. .map(|(_, s)| match s {
  420. Source::Data(d) => d.len(),
  421. Source::Kept(_) => 0,
  422. })
  423. .sum();
  424. if written > MAX_UPDATE {
  425. return UPDATE_TOO_BIG;
  426. }
  427. let replaced: u64 = current.as_ref().map_or(0, |v| {
  428. let sizes = v.sizes();
  429. let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n));
  430. changed.map(|(_, size)| size).sum()
  431. });
  432. let root = self.dir.parent().unwrap_or(&self.dir);
  433. let free = storage::disk_free(root);
  434. if let Some(hr) = no_room(written as u64, replaced, used_bytes(root), free) {
  435. return hr;
  436. }
  437. let display = self.display.as_deref();
  438. let display = display.or(current.as_ref().map(|v| v.display.as_str()));
  439. let number = current.as_ref().map_or(1, |v| v.number + 1);
  440. if let Err(e) = commit(&self.dir, number, &self.name, display.unwrap_or(""), &blobs) {
  441. return io_error(&self.dir, &e);
  442. }
  443. // The old version is garbage now; a crash here leaves it for later.
  444. if let Some(old) = &current {
  445. let _ = std::fs::remove_dir_all(&old.dir);
  446. step();
  447. }
  448. S_OK
  449. }
  450. }
  451. /// Deletes a container: renamed away (one step), then removed.
  452. fn delete(root: &Path, name: &str) -> HRESULT {
  453. let _saves = saves_lock();
  454. let dir = container_dir(root, name);
  455. match current_named(&dir, name) {
  456. Ok(Some(_)) => {}
  457. Ok(None) => return S_OK,
  458. Err(e) => return io_error(&dir, &e),
  459. }
  460. let gone = dir.with_extension("gone");
  461. let _ = std::fs::remove_dir_all(&gone);
  462. step();
  463. if let Err(e) = std::fs::rename(&dir, &gone) {
  464. return io_error(&dir, &e);
  465. }
  466. step();
  467. let _ = std::fs::remove_dir_all(&gone);
  468. S_OK
  469. }
  470. /// Reads the named blobs (all of them for `None`) of a container.
  471. fn read(c: &Container, names: Option<Vec<String>>) -> Result<Vec<(String, Vec<u8>)>, HRESULT> {
  472. let _saves = saves_lock();
  473. let version = current_named(&c.dir, &c.name)
  474. .map_err(|e| io_error(&c.dir, &e))?
  475. .ok_or(BLOB_NOT_FOUND)?;
  476. let names = names.unwrap_or_else(|| version.blobs.clone());
  477. names
  478. .into_iter()
  479. .map(|name| {
  480. let i = version.blobs.iter().position(|b| *b == name).ok_or(BLOB_NOT_FOUND)?;
  481. let data = std::fs::read(version.blob(i)).map_err(|e| io_error(&c.dir, &e))?;
  482. Ok((name, data))
  483. })
  484. .collect()
  485. }
  486. /// One blob as the public API lays it out: name, size, data.
  487. const BLOB: usize = 24;
  488. /// Blobs laid out as the title reads them: the blob array, then each name
  489. /// (NUL-terminated) and its data, with pointers `base` plus offset.
  490. fn layout(blobs: &[(String, Vec<u8>)], base: usize) -> Vec<u8> {
  491. let mut out = vec![0u8; blobs.len() * BLOB];
  492. for (i, (name, data)) in blobs.iter().enumerate() {
  493. let name_at = base + out.len();
  494. out.extend_from_slice(name.as_bytes());
  495. out.push(0);
  496. let data_at = base + out.len();
  497. out.extend_from_slice(data);
  498. let entry = &mut out[i * BLOB..(i + 1) * BLOB];
  499. entry[..8].copy_from_slice(&name_at.to_le_bytes());
  500. entry[8..12].copy_from_slice(&(data.len() as u32).to_le_bytes());
  501. entry[16..].copy_from_slice(&data_at.to_le_bytes());
  502. }
  503. out
  504. }
  505. /// The names a title passes (`count` strings, or all blobs if null).
  506. fn names(names: *const *const c_char, count: u32) -> Option<Vec<String>> {
  507. if names.is_null() {
  508. return None;
  509. }
  510. // SAFETY: the title passes `count` strings.
  511. let names = unsafe { std::slice::from_raw_parts(names, count as usize) };
  512. Some(names.iter().map(|&n| text(n).unwrap_or_default()).collect())
  513. }
  514. type This = *const Object;
  515. type ContainerCallback = extern "system" fn(*const ContainerInfo, *mut c_void) -> bool;
  516. type BlobCallback = extern "system" fn(*const BlobInfo, *mut c_void) -> bool;
  517. #[repr(C)]
  518. pub struct ContainerInfo {
  519. pub name: *const c_char,
  520. pub display_name: *const c_char,
  521. pub blob_count: u32,
  522. pub total_size: u64,
  523. pub last_modified: i64,
  524. pub needs_sync: bool,
  525. }
  526. #[repr(C)]
  527. pub struct BlobInfo {
  528. pub name: *const c_char,
  529. pub size: u32,
  530. }
  531. /// Calls `callback` with the information of each container that passes
  532. /// `keep` until it returns false; never under our lock (it may call us).
  533. fn report(root: &Path, keep: impl Fn(&str) -> bool, context: *mut c_void, callback: ContainerCallback) {
  534. let infos: Vec<(CString, CString, u32, u64, i64)> = {
  535. let _saves = saves_lock();
  536. containers(root)
  537. .into_iter()
  538. .filter(|(name, _)| keep(name))
  539. .filter_map(|(name, dir)| current_named(&dir, &name).ok().flatten())
  540. .map(|v| {
  541. let modified = std::fs::metadata(v.dir.join(MANIFEST))
  542. .and_then(|m| m.modified())
  543. .ok()
  544. .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
  545. .map_or(0, |d| d.as_secs() as i64);
  546. let size = v.sizes().iter().map(|(_, s)| s).sum();
  547. let count = v.blobs.len() as u32;
  548. (cstring(&v.name), cstring(&v.display), count, size, modified)
  549. })
  550. .collect()
  551. };
  552. for (name, display, blob_count, total_size, last_modified) in &infos {
  553. let info = ContainerInfo {
  554. name: name.as_ptr(),
  555. display_name: display.as_ptr(),
  556. blob_count: *blob_count,
  557. total_size: *total_size,
  558. last_modified: *last_modified,
  559. needs_sync: false,
  560. };
  561. if !callback(&info, context) {
  562. break;
  563. }
  564. }
  565. }
  566. fn cstring(s: &str) -> CString {
  567. CString::new(s.replace('\0', "")).unwrap_or_default()
  568. }
  569. static INIT: u8 = 0;
  570. static QUOTA_CALL: u8 = 0;
  571. static DELETE: u8 = 0;
  572. static READ: u8 = 0;
  573. static SUBMIT: u8 = 0;
  574. extern "system" fn initialize_async(
  575. _: This,
  576. _user: *const c_void,
  577. config: *const c_char,
  578. _sync_on_demand: bool,
  579. block: *mut AsyncBlock,
  580. ) -> HRESULT {
  581. let saves = runtime::title().saves();
  582. let result = if saves.parent().is_none_or(|p| p.as_os_str().is_empty()) {
  583. Err(NO_ACCESS)
  584. } else {
  585. Provider::open(&saves, text(config).as_deref()).map(|p| xasync::bytes(give(p)))
  586. };
  587. xasync::finished_with(block, (&raw const INIT).cast(), result)
  588. }
  589. extern "system" fn initialize_result(
  590. _: This,
  591. block: *mut AsyncBlock,
  592. out: *mut *mut Provider,
  593. ) -> HRESULT {
  594. xasync::result(block, (&raw const INIT).cast(), out)
  595. }
  596. extern "system" fn close_provider(_: This, provider: *mut Provider) {
  597. take(provider);
  598. }
  599. extern "system" fn quota_async(
  600. _: This,
  601. provider: *const Provider,
  602. block: *mut AsyncBlock,
  603. ) -> HRESULT {
  604. let result = get(provider)
  605. .ok_or(E_INVALIDARG)
  606. .map(|p| xasync::bytes(p.remaining() as i64));
  607. xasync::finished_with(block, (&raw const QUOTA_CALL).cast(), result)
  608. }
  609. extern "system" fn quota_result(_: This, block: *mut AsyncBlock, out: *mut i64) -> HRESULT {
  610. xasync::result(block, (&raw const QUOTA_CALL).cast(), out)
  611. }
  612. extern "system" fn delete_async(
  613. _: This,
  614. provider: *const Provider,
  615. name: *const c_char,
  616. block: *mut AsyncBlock,
  617. ) -> HRESULT {
  618. let hr = match (get(provider), text(name)) {
  619. (Some(p), Some(name)) if valid_container(&name) => delete(&p.root, &name),
  620. (Some(_), Some(_)) => INVALID_CONTAINER_NAME,
  621. _ => E_INVALIDARG,
  622. };
  623. xasync::finished(block, (&raw const DELETE).cast(), hr)
  624. }
  625. extern "system" fn delete_result(_: This, block: *mut AsyncBlock) -> HRESULT {
  626. let none = std::ptr::null_mut();
  627. xasync::XAsyncGetResult(block, (&raw const DELETE).cast(), 0, none, none.cast())
  628. }
  629. /// Reports the container if it exists; a missing one is no error, the
  630. /// callback just does not run.
  631. extern "system" fn container_info(
  632. _: This,
  633. provider: *const Provider,
  634. name: *const c_char,
  635. context: *mut c_void,
  636. callback: Option<ContainerCallback>,
  637. ) -> HRESULT {
  638. let (Some(p), Some(name), Some(callback)) = (get(provider), text(name), callback) else {
  639. return E_INVALIDARG;
  640. };
  641. if !valid_container(&name) {
  642. return INVALID_CONTAINER_NAME;
  643. }
  644. report(&p.root, |n| n == name, context, callback);
  645. S_OK
  646. }
  647. extern "system" fn enumerate_containers(
  648. _: This,
  649. provider: *const Provider,
  650. context: *mut c_void,
  651. callback: Option<ContainerCallback>,
  652. ) -> HRESULT {
  653. let (Some(p), Some(callback)) = (get(provider), callback) else {
  654. return E_INVALIDARG;
  655. };
  656. report(&p.root, |_| true, context, callback);
  657. S_OK
  658. }
  659. /// The container exists once an update to it is submitted.
  660. extern "system" fn create_container(
  661. _: This,
  662. provider: *const Provider,
  663. name: *const c_char,
  664. out: *mut *mut Container,
  665. ) -> HRESULT {
  666. let (Some(p), Some(name)) = (get(provider), text(name)) else {
  667. return E_INVALIDARG;
  668. };
  669. if !valid_container(&name) {
  670. return INVALID_CONTAINER_NAME;
  671. }
  672. put(out, give(p.container(&name)))
  673. }
  674. extern "system" fn close_container(_: This, container: *mut Container) {
  675. take(container);
  676. }
  677. extern "system" fn enumerate_blobs(
  678. _: This,
  679. container: *const Container,
  680. prefix: *const c_char,
  681. context: *mut c_void,
  682. callback: Option<BlobCallback>,
  683. ) -> HRESULT {
  684. let (Some(c), Some(callback)) = (get(container), callback) else {
  685. return E_INVALIDARG;
  686. };
  687. let prefix = text(prefix).unwrap_or_default();
  688. let blobs = {
  689. let _saves = saves_lock();
  690. let version = current_named(&c.dir, &c.name).ok().flatten();
  691. version.map(|v| v.sizes()).unwrap_or_default()
  692. };
  693. for (name, size) in blobs.into_iter().filter(|(n, _)| n.starts_with(&prefix)) {
  694. let name = cstring(&name);
  695. let info = BlobInfo {
  696. name: name.as_ptr(),
  697. size: size as u32,
  698. };
  699. if !callback(&info, context) {
  700. break;
  701. }
  702. }
  703. S_OK
  704. }
  705. extern "system" fn read_blobs(
  706. _: This,
  707. container: *const Container,
  708. blob_names: *const *const c_char,
  709. count: *mut u32,
  710. size: usize,
  711. out: *mut u8,
  712. ) -> HRESULT {
  713. let Some(c) = get(container) else {
  714. return E_INVALIDARG;
  715. };
  716. // SAFETY: the title passes its count.
  717. let wanted = unsafe { count.as_ref() }.copied().unwrap_or(0);
  718. let blobs = match read(c, names(blob_names, wanted)) {
  719. Ok(blobs) => blobs,
  720. Err(hr) => return hr,
  721. };
  722. let bytes = layout(&blobs, out as usize);
  723. if out.is_null() || size < bytes.len() {
  724. return BUFFER_TOO_SMALL;
  725. }
  726. // SAFETY: the buffer holds `size` bytes, checked above.
  727. unsafe { out.copy_from_nonoverlapping(bytes.as_ptr(), bytes.len()) };
  728. put(count, blobs.len() as u32)
  729. }
  730. /// Read at once; the result holds the layout with pointers relative to the
  731. /// title's buffer, fixed up when the title takes it.
  732. extern "system" fn read_async(
  733. _: This,
  734. container: *const Container,
  735. blob_names: *const *const c_char,
  736. count: u32,
  737. block: *mut AsyncBlock,
  738. ) -> HRESULT {
  739. let result = match get(container) {
  740. Some(c) => read(c, names(blob_names, count)).map(|blobs| layout(&blobs, 0)),
  741. None => Err(E_INVALIDARG),
  742. };
  743. xasync::finished_with(block, (&raw const READ).cast(), result)
  744. }
  745. extern "system" fn read_result(
  746. _: This,
  747. block: *mut AsyncBlock,
  748. size: usize,
  749. out: *mut u8,
  750. count: *mut u32,
  751. ) -> HRESULT {
  752. let mut used = 0;
  753. let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used);
  754. // The documented error for a small buffer; the result stays for a
  755. // retry with a larger one.
  756. if hr == xasync::E_NOT_SUFFICIENT_BUFFER {
  757. return BUFFER_TOO_SMALL;
  758. }
  759. if hr < 0 {
  760. return hr;
  761. }
  762. // The first name follows the blob array, so its offset gives the count.
  763. let blobs = if used == 0 {
  764. 0
  765. } else {
  766. // SAFETY: the result holds at least one blob entry.
  767. unsafe { out.cast::<usize>().read_unaligned() / BLOB }
  768. };
  769. for i in 0..blobs {
  770. for field in [0, 16] {
  771. // SAFETY: within the blob array just written.
  772. unsafe {
  773. let p = out.add(i * BLOB + field).cast::<usize>();
  774. p.write_unaligned(p.read_unaligned() + out as usize);
  775. }
  776. }
  777. }
  778. put(count, blobs as u32)
  779. }
  780. extern "system" fn create_update(
  781. _: This,
  782. container: *const Container,
  783. display: *const c_char,
  784. out: *mut *mut Update,
  785. ) -> HRESULT {
  786. let Some(c) = get(container) else {
  787. return E_INVALIDARG;
  788. };
  789. put(
  790. out,
  791. give(Update {
  792. name: c.name.clone(),
  793. dir: c.dir.clone(),
  794. display: text(display),
  795. changes: Vec::new(),
  796. }),
  797. )
  798. }
  799. extern "system" fn close_update(_: This, update: *mut Update) {
  800. take(update);
  801. }
  802. extern "system" fn write_blob(
  803. _: This,
  804. update: *mut Update,
  805. name: *const c_char,
  806. data: *const u8,
  807. size: usize,
  808. ) -> HRESULT {
  809. // SAFETY: a handle we gave out; the title does not use it concurrently.
  810. let (Some(update), Some(name)) = (unsafe { update.as_mut() }, text(name)) else {
  811. return E_INVALIDARG;
  812. };
  813. if name.is_empty() || (data.is_null() && size > 0) {
  814. return E_INVALIDARG;
  815. }
  816. if size > MAX_UPDATE {
  817. return UPDATE_TOO_BIG;
  818. }
  819. let data = if size == 0 {
  820. Vec::new()
  821. } else {
  822. // SAFETY: the title passes `size` bytes.
  823. unsafe { std::slice::from_raw_parts(data, size) }.to_vec()
  824. };
  825. update.changes.push((name, Some(data)));
  826. S_OK
  827. }
  828. extern "system" fn delete_blob(_: This, update: *mut Update, name: *const c_char) -> HRESULT {
  829. // SAFETY: as in `write_blob`.
  830. match (unsafe { update.as_mut() }, text(name)) {
  831. (Some(update), Some(name)) if !name.is_empty() => {
  832. update.changes.push((name, None));
  833. S_OK
  834. }
  835. _ => E_INVALIDARG,
  836. }
  837. }
  838. extern "system" fn submit_async(_: This, update: *const Update, block: *mut AsyncBlock) -> HRESULT {
  839. let hr = get(update).map_or(E_INVALIDARG, Update::submit);
  840. xasync::finished(block, (&raw const SUBMIT).cast(), hr)
  841. }
  842. extern "system" fn submit_result(_: This, block: *mut AsyncBlock) -> HRESULT {
  843. let none = std::ptr::null_mut();
  844. xasync::XAsyncGetResult(block, (&raw const SUBMIT).cast(), 0, none, none.cast())
  845. }
  846. static VTABLE: Methods<30> = Methods([
  847. missing::<0> as *const (),
  848. add_ref as *const (),
  849. add_ref as *const (),
  850. missing::<3> as *const (), // 0x18 initialize (blocking)
  851. initialize_async as *const (), // 0x20
  852. initialize_result as *const (), // 0x28
  853. close_provider as *const (), // 0x30
  854. missing::<7> as *const (), // 0x38 remaining quota (blocking)
  855. quota_async as *const (), // 0x40
  856. quota_result as *const (), // 0x48
  857. missing::<10> as *const (), // 0x50 delete (blocking)
  858. delete_async as *const (), // 0x58
  859. delete_result as *const (), // 0x60
  860. container_info as *const (), // 0x68
  861. enumerate_containers as *const (), // 0x70
  862. missing::<15> as *const (), // 0x78 by name prefix
  863. create_container as *const (), // 0x80
  864. close_container as *const (), // 0x88
  865. missing::<18> as *const (), // 0x90 all blob info
  866. enumerate_blobs as *const (), // 0x98 by name prefix
  867. read_blobs as *const (), // 0xa0
  868. read_async as *const (), // 0xa8
  869. read_result as *const (), // 0xb0
  870. create_update as *const (), // 0xb8
  871. close_update as *const (), // 0xc0
  872. write_blob as *const (), // 0xc8
  873. delete_blob as *const (), // 0xd0
  874. missing::<27> as *const (), // 0xd8 submit (blocking)
  875. submit_async as *const (), // 0xe0
  876. submit_result as *const (), // 0xe8
  877. ]);
  878. #[cfg(test)]
  879. mod tests {
  880. use std::io::BufRead;
  881. use std::sync::atomic::{AtomicU32, Ordering};
  882. use super::*;
  883. use crate::modules::xgameruntime::method;
  884. fn block() -> AsyncBlock {
  885. AsyncBlock {
  886. queue: std::ptr::null(),
  887. context: std::ptr::null_mut(),
  888. callback: None,
  889. internal: [0; 4],
  890. }
  891. }
  892. static STEPS: AtomicU32 = AtomicU32::new(0);
  893. /// In a child process of the crash test, stops for good at the step
  894. /// `VICTORY_SAVE_STOP` names and says so.
  895. pub(super) fn crash_point() {
  896. let Ok(stop) = std::env::var("VICTORY_SAVE_STOP") else {
  897. return;
  898. };
  899. if stop.parse() == Ok(STEPS.fetch_add(1, Ordering::SeqCst) + 1) {
  900. println!("STOPPED");
  901. let _ = std::io::stdout().flush();
  902. loop {
  903. std::thread::sleep(std::time::Duration::from_secs(60));
  904. }
  905. }
  906. }
  907. /// The per-user quota and the host disk fail with their own errors.
  908. #[test]
  909. fn a_full_disk_is_not_the_quota() {
  910. let mb = 1 << 20;
  911. assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE));
  912. assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED));
  913. // Replacing a blob of the same size fits a full quota.
  914. assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None);
  915. assert_eq!(no_room(mb, 0, 0, mb), None);
  916. }
  917. fn update(root: &Path, display: &str, changes: &[(&str, Option<&str>)]) -> HRESULT {
  918. Update {
  919. name: "Slot".into(),
  920. dir: container_dir(root, "Slot"),
  921. display: Some(display.into()),
  922. changes: changes
  923. .iter()
  924. .map(|(n, d)| (n.to_string(), d.map(|d| d.as_bytes().to_vec())))
  925. .collect(),
  926. }
  927. .submit()
  928. }
  929. /// The container `Slot`: display name and blobs.
  930. fn state(root: &Path) -> Option<(String, Vec<(String, String)>)> {
  931. let c = Provider { root: root.into() }.container("Slot");
  932. let display = current_named(&c.dir, "Slot").unwrap()?.display;
  933. let blobs = read(&c, None).unwrap();
  934. let text = |(n, d): (String, Vec<u8>)| (n, String::from_utf8(d).unwrap());
  935. Some((display, blobs.into_iter().map(text).collect()))
  936. }
  937. fn old_state() -> Option<(String, Vec<(String, String)>)> {
  938. Some(("one".into(), vec![("a".into(), "old a".into()), ("b".into(), "old b".into())]))
  939. }
  940. /// Run by the crash test in a child process; does nothing otherwise.
  941. #[test]
  942. fn crash_child() {
  943. let (Ok(root), Ok(op)) = (std::env::var("VICTORY_SAVE_CHILD"), std::env::var("VICTORY_SAVE_OP")) else {
  944. return;
  945. };
  946. let root = PathBuf::from(root);
  947. let hr = if op == "update" {
  948. update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))])
  949. } else {
  950. delete(&root, "Slot")
  951. };
  952. assert_eq!(hr, S_OK);
  953. println!("FINISHED");
  954. }
  955. /// Kills a process in the middle of an update (and of a deletion) at
  956. /// every step: what is left is the whole old container or the whole
  957. /// new one.
  958. #[test]
  959. fn a_kill_at_any_step_leaves_old_or_new() {
  960. let new = Some(("two".into(), vec![("a".into(), "new a".into()), ("c".into(), "new c".into())]));
  961. for (op, after) in [("update", new), ("delete", None)] {
  962. let mut seen = (0, 0);
  963. for stop in 1.. {
  964. let dir = tempfile::tempdir().unwrap();
  965. let root = dir.path();
  966. assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK);
  967. let mut child = std::process::Command::new(std::env::current_exe().unwrap())
  968. .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"])
  969. .args(["--test-threads=1"])
  970. .env("VICTORY_SAVE_CHILD", root)
  971. .env("VICTORY_SAVE_OP", op)
  972. .env("VICTORY_SAVE_STOP", stop.to_string())
  973. .stdout(std::process::Stdio::piped())
  974. .spawn()
  975. .unwrap();
  976. let out = std::io::BufReader::new(child.stdout.take().unwrap());
  977. let mut finished = false;
  978. for line in out.lines() {
  979. let line = line.unwrap();
  980. if line.contains("STOPPED") {
  981. break;
  982. }
  983. finished |= line.contains("FINISHED");
  984. }
  985. let _ = child.kill();
  986. child.wait().unwrap();
  987. let left = state(root);
  988. if left == old_state() {
  989. seen.0 += 1;
  990. } else {
  991. assert_eq!(left, after, "{op}, killed at step {stop}");
  992. seen.1 += 1;
  993. }
  994. if finished {
  995. break;
  996. }
  997. }
  998. assert!(seen.0 > 0 && seen.1 > 1, "{op}: {seen:?}");
  999. }
  1000. }
  1001. #[test]
  1002. fn names_are_exact() {
  1003. for name in ["Save_1", "slot/2", "a.b c%", "\u{e9}t\u{e9}"] {
  1004. let file = file_name(name);
  1005. assert!(!file.contains(['.', '/', ' ']), "{file}");
  1006. assert_eq!(decode(&file).as_deref(), Some(name));
  1007. }
  1008. assert_eq!(decode("x.new"), None);
  1009. for good in ["Profile/Slot_1", "a/b/Save-2.sav", "x", &"a".repeat(256)] {
  1010. assert!(valid_container(good), "{good}");
  1011. }
  1012. for bad in ["a b", "", "a/", "a.", "a..b", "a.b/c", "a-b/c", &"a".repeat(257)] {
  1013. assert!(!valid_container(bad), "{bad}");
  1014. }
  1015. // Containers and blobs differing only in case, reserved device
  1016. // names, characters the host forbids, long names: all distinct.
  1017. let dir = tempfile::tempdir().unwrap();
  1018. let p = Provider { root: dir.path().into() };
  1019. let long = "n".repeat(300);
  1020. let blobs = ["A", "a", "CON", "nul.txt", "x/y:z*?\"<>|", long.as_str(), "end. "];
  1021. for container in ["Save", "save", "SAVE/CON.x"] {
  1022. let c = p.container(container);
  1023. let u = Update {
  1024. name: c.name.clone(),
  1025. dir: c.dir.clone(),
  1026. display: None,
  1027. changes: blobs
  1028. .iter()
  1029. .map(|b| (b.to_string(), Some(format!("{container}:{b}").into_bytes())))
  1030. .collect(),
  1031. };
  1032. assert_eq!(u.submit(), S_OK, "{container}");
  1033. }
  1034. let _saves = saves_lock();
  1035. let names: Vec<String> = containers(dir.path()).into_iter().map(|c| c.0).collect();
  1036. drop(_saves);
  1037. assert_eq!(names, ["SAVE/CON.x", "Save", "save"]);
  1038. for container in ["Save", "save", "SAVE/CON.x"] {
  1039. let read = read(&p.container(container), None).unwrap();
  1040. let mut expected: Vec<_> = blobs
  1041. .iter()
  1042. .map(|b| (b.to_string(), format!("{container}:{b}").into_bytes()))
  1043. .collect();
  1044. expected.sort();
  1045. assert_eq!(read, expected, "{container}");
  1046. }
  1047. }
  1048. #[test]
  1049. fn the_old_layout_moves_over() {
  1050. let saves = tempfile::tempdir().unwrap();
  1051. let root = saves.path().join(format!("{:016X}", xuser::XUID)).join("scid");
  1052. let old = root.join("Player");
  1053. std::fs::create_dir_all(&old).unwrap();
  1054. std::fs::write(old.join("Save%20Game%20Data"), b"data").unwrap();
  1055. std::fs::write(old.join("Save%20Game%20Header"), b"header").unwrap();
  1056. std::fs::write(old.join("Save%20Game%20Data.new"), b"half").unwrap();
  1057. std::fs::write(old.join(".display"), b"Chapter 1").unwrap();
  1058. let p = Provider::open(saves.path(), Some("scid")).unwrap();
  1059. assert!(!old.exists());
  1060. let c = p.container("Player");
  1061. let blobs = read(&c, None).unwrap();
  1062. assert_eq!(
  1063. blobs,
  1064. [
  1065. ("Save Game Data".into(), b"data".to_vec()),
  1066. ("Save Game Header".into(), b"header".to_vec())
  1067. ]
  1068. );
  1069. let v = current_named(&c.dir, "Player").unwrap().unwrap();
  1070. assert_eq!((v.number, v.display.as_str()), (1, "Chapter 1"));
  1071. }
  1072. /// An empty configuration id names none. As a folder name it would be
  1073. /// the folder every configuration lives in, whose folders then look
  1074. /// like containers of the old layout and are converted away.
  1075. #[test]
  1076. fn an_empty_configuration_id_is_the_default_one() {
  1077. let saves = tempfile::tempdir().unwrap();
  1078. let scid = Provider::open(saves.path(), Some("scid")).unwrap();
  1079. assert_eq!(update(&scid.root, "one", &[("a", Some("kept"))]), S_OK);
  1080. let kept = Some(("one".into(), vec![("a".into(), "kept".into())]));
  1081. assert_eq!(state(&scid.root), kept);
  1082. let empty = Provider::open(saves.path(), Some("")).unwrap();
  1083. assert!(scid.root.is_dir(), "another configuration's saves are gone");
  1084. assert_eq!(state(&scid.root), kept);
  1085. let default = Provider::open(saves.path(), None).unwrap();
  1086. assert_eq!(empty.root, default.root);
  1087. // Named configurations stay apart, from it and from each other.
  1088. assert_ne!(empty.root, scid.root);
  1089. assert_eq!(state(&empty.root), None);
  1090. let other = Provider::open(saves.path(), Some("other")).unwrap();
  1091. assert_eq!(state(&other.root), None);
  1092. assert_eq!(state(&scid.root), kept);
  1093. }
  1094. #[test]
  1095. fn saves_persist_across_providers() {
  1096. let this: This = &OBJECT;
  1097. let saves = tempfile::tempdir().unwrap();
  1098. let provider = give(Provider::open(saves.path(), Some("scid")).unwrap());
  1099. // Write two blobs through an update.
  1100. let mut container = std::ptr::null_mut();
  1101. type Create = extern "system" fn(
  1102. This,
  1103. *const Provider,
  1104. *const c_char,
  1105. *mut *mut Container,
  1106. ) -> HRESULT;
  1107. let create = method::<Create>(&OBJECT, 0x80);
  1108. assert_eq!(
  1109. create(this, provider, c"bad name".as_ptr(), &mut container),
  1110. INVALID_CONTAINER_NAME
  1111. );
  1112. assert_eq!(
  1113. create(this, provider, c"Slot_1".as_ptr(), &mut container),
  1114. S_OK
  1115. );
  1116. let mut update = std::ptr::null_mut();
  1117. type Update_ =
  1118. extern "system" fn(This, *const Container, *const c_char, *mut *mut Update) -> HRESULT;
  1119. assert_eq!(
  1120. method::<Update_>(&OBJECT, 0xb8)(this, container, c"Chapter 1".as_ptr(), &mut update),
  1121. S_OK
  1122. );
  1123. type Write =
  1124. extern "system" fn(This, *mut Update, *const c_char, *const u8, usize) -> HRESULT;
  1125. let write = method::<Write>(&OBJECT, 0xc8);
  1126. assert_eq!(
  1127. write(this, update, c"world".as_ptr(), b"hello".as_ptr(), 5),
  1128. S_OK
  1129. );
  1130. assert_eq!(
  1131. write(this, update, c"player.dat".as_ptr(), b"xy".as_ptr(), 2),
  1132. S_OK
  1133. );
  1134. assert_eq!(
  1135. write(this, update, c"gone".as_ptr(), b"z".as_ptr(), 1),
  1136. S_OK
  1137. );
  1138. type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT;
  1139. assert_eq!(method::<Delete>(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), S_OK);
  1140. type Submit = extern "system" fn(This, *const Update, *mut AsyncBlock) -> HRESULT;
  1141. let mut b = block();
  1142. assert_eq!(method::<Submit>(&OBJECT, 0xe0)(this, update, &mut b), S_OK);
  1143. assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
  1144. close_update(this, update);
  1145. close_container(this, container);
  1146. close_provider(this, provider);
  1147. // A new provider sees the container and reads both blobs back.
  1148. let provider = give(Provider::open(saves.path(), Some("scid")).unwrap());
  1149. extern "system" fn seen(info: *const ContainerInfo, context: *mut c_void) -> bool {
  1150. // SAFETY: valid during the callback; the context is the test's vector.
  1151. let (info, out) = unsafe {
  1152. (
  1153. &*info,
  1154. &mut *context.cast::<Vec<(String, String, u32, u64)>>(),
  1155. )
  1156. };
  1157. out.push((
  1158. text(info.name).unwrap(),
  1159. text(info.display_name).unwrap(),
  1160. info.blob_count,
  1161. info.total_size,
  1162. ));
  1163. true
  1164. }
  1165. let mut found: Vec<(String, String, u32, u64)> = Vec::new();
  1166. let context = (&raw mut found).cast();
  1167. assert_eq!(
  1168. enumerate_containers(this, provider, context, Some(seen)),
  1169. S_OK
  1170. );
  1171. assert_eq!(found, [("Slot_1".into(), "Chapter 1".into(), 2, 7)]);
  1172. let mut container = std::ptr::null_mut();
  1173. assert_eq!(
  1174. create_container(this, provider, c"Slot_1".as_ptr(), &mut container),
  1175. S_OK
  1176. );
  1177. let mut b = block();
  1178. let wanted = [c"world".as_ptr(), c"player.dat".as_ptr()];
  1179. assert_eq!(
  1180. read_async(this, container, wanted.as_ptr(), 2, &mut b),
  1181. S_OK
  1182. );
  1183. assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
  1184. let mut size = 0;
  1185. assert_eq!(xasync::XAsyncGetResultSize(&mut b, &mut size), S_OK);
  1186. assert_eq!(
  1187. size,
  1188. 2 * BLOB + "world\0hello".len() + "player.dat\0xy".len()
  1189. );
  1190. let mut buffer = vec![0u64; size.div_ceil(8)];
  1191. let mut count = 0;
  1192. assert_eq!(
  1193. read_result(this, &mut b, 8, buffer.as_mut_ptr().cast(), &mut count),
  1194. BUFFER_TOO_SMALL
  1195. );
  1196. assert_eq!(
  1197. read_result(this, &mut b, size, buffer.as_mut_ptr().cast(), &mut count),
  1198. S_OK
  1199. );
  1200. assert_eq!(count, 2);
  1201. let blob = |i: usize| {
  1202. // SAFETY: the layout the call wrote.
  1203. unsafe {
  1204. let entry = buffer.as_ptr().cast::<u8>().add(i * BLOB);
  1205. let name = text(entry.cast::<*const c_char>().read_unaligned()).unwrap();
  1206. let len = entry.add(8).cast::<u32>().read_unaligned() as usize;
  1207. let data = std::slice::from_raw_parts(
  1208. entry.add(16).cast::<*const u8>().read_unaligned(),
  1209. len,
  1210. );
  1211. (name, data.to_vec())
  1212. }
  1213. };
  1214. assert_eq!(blob(0), ("world".into(), b"hello".to_vec()));
  1215. assert_eq!(blob(1), ("player.dat".into(), b"xy".to_vec()));
  1216. let missing = [c"nothing".as_ptr()];
  1217. let mut one = 1;
  1218. let mut small = [0u8; 8];
  1219. let read_now = method::<
  1220. extern "system" fn(
  1221. This,
  1222. *const Container,
  1223. *const *const c_char,
  1224. *mut u32,
  1225. usize,
  1226. *mut u8,
  1227. ) -> HRESULT,
  1228. >(&OBJECT, 0xa0);
  1229. assert_eq!(
  1230. read_now(
  1231. this,
  1232. container,
  1233. missing.as_ptr(),
  1234. &mut one,
  1235. 8,
  1236. small.as_mut_ptr()
  1237. ),
  1238. BLOB_NOT_FOUND
  1239. );
  1240. assert_eq!(
  1241. read_now(
  1242. this,
  1243. container,
  1244. wanted.as_ptr(),
  1245. &mut 2,
  1246. 8,
  1247. small.as_mut_ptr()
  1248. ),
  1249. BUFFER_TOO_SMALL
  1250. );
  1251. // Quota counts the blobs; deleting the container frees it.
  1252. let mut b = block();
  1253. assert_eq!(quota_async(this, provider, &mut b), S_OK);
  1254. let mut left = 0i64;
  1255. assert_eq!(quota_result(this, &mut b, &mut left), S_OK);
  1256. assert!(left as u64 <= QUOTA - 7);
  1257. let mut b = block();
  1258. assert_eq!(
  1259. delete_async(this, provider, c"Slot_1".as_ptr(), &mut b),
  1260. S_OK
  1261. );
  1262. assert_eq!(delete_result(this, &mut b), S_OK);
  1263. found.clear();
  1264. let context = (&raw mut found).cast();
  1265. assert_eq!(
  1266. enumerate_containers(this, provider, context, Some(seen)),
  1267. S_OK
  1268. );
  1269. assert!(found.is_empty());
  1270. close_container(this, container);
  1271. close_provider(this, provider);
  1272. }
  1273. }