xgamesave.rs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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. fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT {
  368. tracing::warn!(dir = %dir.display(), %e, "game save");
  369. if e.kind() == std::io::ErrorKind::StorageFull {
  370. OUT_OF_LOCAL_STORAGE
  371. } else {
  372. NO_ACCESS
  373. }
  374. }
  375. impl Update {
  376. /// Applies the update as one new version of the container.
  377. fn submit(&self) -> HRESULT {
  378. let _saves = saves_lock();
  379. let current = match current(&self.dir) {
  380. Ok(v) => v,
  381. Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
  382. Err(e) => return io_error(&self.dir, &e),
  383. };
  384. if current.as_ref().is_some_and(|v| v.name != self.name) {
  385. // Another container's name hashes alike: never mix the two.
  386. return NO_ACCESS;
  387. }
  388. // The blobs after the update: name → new data or the kept file.
  389. let mut blobs: Vec<(&str, Source<'_>)> = current
  390. .iter()
  391. .flat_map(|v| {
  392. let kept = v.blobs.iter().enumerate();
  393. kept.map(|(i, n)| (n.as_str(), Source::Kept(v.blob(i))))
  394. })
  395. .collect();
  396. for (name, data) in &self.changes {
  397. blobs.retain(|(n, _)| n != name);
  398. if let Some(data) = data {
  399. blobs.push((name, Source::Data(data)));
  400. }
  401. }
  402. blobs.sort_by(|a, b| a.0.cmp(b.0));
  403. let written: usize = blobs
  404. .iter()
  405. .map(|(_, s)| match s {
  406. Source::Data(d) => d.len(),
  407. Source::Kept(_) => 0,
  408. })
  409. .sum();
  410. if written > MAX_UPDATE {
  411. return UPDATE_TOO_BIG;
  412. }
  413. let replaced: u64 = current.as_ref().map_or(0, |v| {
  414. let sizes = v.sizes();
  415. let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n));
  416. changed.map(|(_, size)| size).sum()
  417. });
  418. let root = self.dir.parent().unwrap_or(&self.dir);
  419. if written as u64 > remaining(root) + replaced {
  420. return QUOTA_EXCEEDED;
  421. }
  422. let display = self.display.as_deref();
  423. let display = display.or(current.as_ref().map(|v| v.display.as_str()));
  424. let number = current.as_ref().map_or(1, |v| v.number + 1);
  425. if let Err(e) = commit(&self.dir, number, &self.name, display.unwrap_or(""), &blobs) {
  426. return io_error(&self.dir, &e);
  427. }
  428. // The old version is garbage now; a crash here leaves it for later.
  429. if let Some(old) = &current {
  430. let _ = std::fs::remove_dir_all(&old.dir);
  431. step();
  432. }
  433. S_OK
  434. }
  435. }
  436. /// Deletes a container: renamed away (one step), then removed.
  437. fn delete(root: &Path, name: &str) -> HRESULT {
  438. let _saves = saves_lock();
  439. let dir = container_dir(root, name);
  440. match current_named(&dir, name) {
  441. Ok(Some(_)) => {}
  442. Ok(None) => return S_OK,
  443. Err(e) => return io_error(&dir, &e),
  444. }
  445. let gone = dir.with_extension("gone");
  446. let _ = std::fs::remove_dir_all(&gone);
  447. step();
  448. if let Err(e) = std::fs::rename(&dir, &gone) {
  449. return io_error(&dir, &e);
  450. }
  451. step();
  452. let _ = std::fs::remove_dir_all(&gone);
  453. S_OK
  454. }
  455. /// Reads the named blobs (all of them for `None`) of a container.
  456. fn read(c: &Container, names: Option<Vec<String>>) -> Result<Vec<(String, Vec<u8>)>, HRESULT> {
  457. let _saves = saves_lock();
  458. let version = current_named(&c.dir, &c.name)
  459. .map_err(|e| io_error(&c.dir, &e))?
  460. .ok_or(BLOB_NOT_FOUND)?;
  461. let names = names.unwrap_or_else(|| version.blobs.clone());
  462. names
  463. .into_iter()
  464. .map(|name| {
  465. let i = version.blobs.iter().position(|b| *b == name).ok_or(BLOB_NOT_FOUND)?;
  466. let data = std::fs::read(version.blob(i)).map_err(|e| io_error(&c.dir, &e))?;
  467. Ok((name, data))
  468. })
  469. .collect()
  470. }
  471. /// One blob as the public API lays it out: name, size, data.
  472. const BLOB: usize = 24;
  473. /// Blobs laid out as the title reads them: the blob array, then each name
  474. /// (NUL-terminated) and its data, with pointers `base` plus offset.
  475. fn layout(blobs: &[(String, Vec<u8>)], base: usize) -> Vec<u8> {
  476. let mut out = vec![0u8; blobs.len() * BLOB];
  477. for (i, (name, data)) in blobs.iter().enumerate() {
  478. let name_at = base + out.len();
  479. out.extend_from_slice(name.as_bytes());
  480. out.push(0);
  481. let data_at = base + out.len();
  482. out.extend_from_slice(data);
  483. let entry = &mut out[i * BLOB..(i + 1) * BLOB];
  484. entry[..8].copy_from_slice(&name_at.to_le_bytes());
  485. entry[8..12].copy_from_slice(&(data.len() as u32).to_le_bytes());
  486. entry[16..].copy_from_slice(&data_at.to_le_bytes());
  487. }
  488. out
  489. }
  490. /// The names a title passes (`count` strings, or all blobs if null).
  491. fn names(names: *const *const c_char, count: u32) -> Option<Vec<String>> {
  492. if names.is_null() {
  493. return None;
  494. }
  495. // SAFETY: the title passes `count` strings.
  496. let names = unsafe { std::slice::from_raw_parts(names, count as usize) };
  497. Some(names.iter().map(|&n| text(n).unwrap_or_default()).collect())
  498. }
  499. type This = *const Object;
  500. type ContainerCallback = extern "system" fn(*const ContainerInfo, *mut c_void) -> bool;
  501. type BlobCallback = extern "system" fn(*const BlobInfo, *mut c_void) -> bool;
  502. #[repr(C)]
  503. pub struct ContainerInfo {
  504. pub name: *const c_char,
  505. pub display_name: *const c_char,
  506. pub blob_count: u32,
  507. pub total_size: u64,
  508. pub last_modified: i64,
  509. pub needs_sync: bool,
  510. }
  511. #[repr(C)]
  512. pub struct BlobInfo {
  513. pub name: *const c_char,
  514. pub size: u32,
  515. }
  516. /// Calls `callback` with the information of each container that passes
  517. /// `keep` until it returns false; never under our lock (it may call us).
  518. fn report(root: &Path, keep: impl Fn(&str) -> bool, context: *mut c_void, callback: ContainerCallback) {
  519. let infos: Vec<(CString, CString, u32, u64, i64)> = {
  520. let _saves = saves_lock();
  521. containers(root)
  522. .into_iter()
  523. .filter(|(name, _)| keep(name))
  524. .filter_map(|(name, dir)| current_named(&dir, &name).ok().flatten())
  525. .map(|v| {
  526. let modified = std::fs::metadata(v.dir.join(MANIFEST))
  527. .and_then(|m| m.modified())
  528. .ok()
  529. .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
  530. .map_or(0, |d| d.as_secs() as i64);
  531. let size = v.sizes().iter().map(|(_, s)| s).sum();
  532. let count = v.blobs.len() as u32;
  533. (cstring(&v.name), cstring(&v.display), count, size, modified)
  534. })
  535. .collect()
  536. };
  537. for (name, display, blob_count, total_size, last_modified) in &infos {
  538. let info = ContainerInfo {
  539. name: name.as_ptr(),
  540. display_name: display.as_ptr(),
  541. blob_count: *blob_count,
  542. total_size: *total_size,
  543. last_modified: *last_modified,
  544. needs_sync: false,
  545. };
  546. if !callback(&info, context) {
  547. break;
  548. }
  549. }
  550. }
  551. fn cstring(s: &str) -> CString {
  552. CString::new(s.replace('\0', "")).unwrap_or_default()
  553. }
  554. static INIT: u8 = 0;
  555. static QUOTA_CALL: u8 = 0;
  556. static DELETE: u8 = 0;
  557. static READ: u8 = 0;
  558. static SUBMIT: u8 = 0;
  559. extern "system" fn initialize_async(
  560. _: This,
  561. _user: *const c_void,
  562. config: *const c_char,
  563. _sync_on_demand: bool,
  564. block: *mut AsyncBlock,
  565. ) -> HRESULT {
  566. let saves = runtime::title().saves();
  567. let result = if saves.parent().is_none_or(|p| p.as_os_str().is_empty()) {
  568. Err(NO_ACCESS)
  569. } else {
  570. Provider::open(&saves, text(config).as_deref()).map(|p| xasync::bytes(give(p)))
  571. };
  572. xasync::finished_with(block, (&raw const INIT).cast(), result)
  573. }
  574. extern "system" fn initialize_result(
  575. _: This,
  576. block: *mut AsyncBlock,
  577. out: *mut *mut Provider,
  578. ) -> HRESULT {
  579. xasync::result(block, (&raw const INIT).cast(), out)
  580. }
  581. extern "system" fn close_provider(_: This, provider: *mut Provider) {
  582. take(provider);
  583. }
  584. extern "system" fn quota_async(
  585. _: This,
  586. provider: *const Provider,
  587. block: *mut AsyncBlock,
  588. ) -> HRESULT {
  589. let result = get(provider)
  590. .ok_or(E_INVALIDARG)
  591. .map(|p| xasync::bytes(p.remaining() as i64));
  592. xasync::finished_with(block, (&raw const QUOTA_CALL).cast(), result)
  593. }
  594. extern "system" fn quota_result(_: This, block: *mut AsyncBlock, out: *mut i64) -> HRESULT {
  595. xasync::result(block, (&raw const QUOTA_CALL).cast(), out)
  596. }
  597. extern "system" fn delete_async(
  598. _: This,
  599. provider: *const Provider,
  600. name: *const c_char,
  601. block: *mut AsyncBlock,
  602. ) -> HRESULT {
  603. let hr = match (get(provider), text(name)) {
  604. (Some(p), Some(name)) if valid_container(&name) => delete(&p.root, &name),
  605. (Some(_), Some(_)) => INVALID_CONTAINER_NAME,
  606. _ => E_INVALIDARG,
  607. };
  608. xasync::finished(block, (&raw const DELETE).cast(), hr)
  609. }
  610. extern "system" fn delete_result(_: This, block: *mut AsyncBlock) -> HRESULT {
  611. let none = std::ptr::null_mut();
  612. xasync::XAsyncGetResult(block, (&raw const DELETE).cast(), 0, none, none.cast())
  613. }
  614. /// Reports the container if it exists; a missing one is no error, the
  615. /// callback just does not run.
  616. extern "system" fn container_info(
  617. _: This,
  618. provider: *const Provider,
  619. name: *const c_char,
  620. context: *mut c_void,
  621. callback: Option<ContainerCallback>,
  622. ) -> HRESULT {
  623. let (Some(p), Some(name), Some(callback)) = (get(provider), text(name), callback) else {
  624. return E_INVALIDARG;
  625. };
  626. if !valid_container(&name) {
  627. return INVALID_CONTAINER_NAME;
  628. }
  629. report(&p.root, |n| n == name, context, callback);
  630. S_OK
  631. }
  632. extern "system" fn enumerate_containers(
  633. _: This,
  634. provider: *const Provider,
  635. context: *mut c_void,
  636. callback: Option<ContainerCallback>,
  637. ) -> HRESULT {
  638. let (Some(p), Some(callback)) = (get(provider), callback) else {
  639. return E_INVALIDARG;
  640. };
  641. report(&p.root, |_| true, context, callback);
  642. S_OK
  643. }
  644. /// The container exists once an update to it is submitted.
  645. extern "system" fn create_container(
  646. _: This,
  647. provider: *const Provider,
  648. name: *const c_char,
  649. out: *mut *mut Container,
  650. ) -> HRESULT {
  651. let (Some(p), Some(name)) = (get(provider), text(name)) else {
  652. return E_INVALIDARG;
  653. };
  654. if !valid_container(&name) {
  655. return INVALID_CONTAINER_NAME;
  656. }
  657. put(out, give(p.container(&name)))
  658. }
  659. extern "system" fn close_container(_: This, container: *mut Container) {
  660. take(container);
  661. }
  662. extern "system" fn enumerate_blobs(
  663. _: This,
  664. container: *const Container,
  665. prefix: *const c_char,
  666. context: *mut c_void,
  667. callback: Option<BlobCallback>,
  668. ) -> HRESULT {
  669. let (Some(c), Some(callback)) = (get(container), callback) else {
  670. return E_INVALIDARG;
  671. };
  672. let prefix = text(prefix).unwrap_or_default();
  673. let blobs = {
  674. let _saves = saves_lock();
  675. let version = current_named(&c.dir, &c.name).ok().flatten();
  676. version.map(|v| v.sizes()).unwrap_or_default()
  677. };
  678. for (name, size) in blobs.into_iter().filter(|(n, _)| n.starts_with(&prefix)) {
  679. let name = cstring(&name);
  680. let info = BlobInfo {
  681. name: name.as_ptr(),
  682. size: size as u32,
  683. };
  684. if !callback(&info, context) {
  685. break;
  686. }
  687. }
  688. S_OK
  689. }
  690. extern "system" fn read_blobs(
  691. _: This,
  692. container: *const Container,
  693. blob_names: *const *const c_char,
  694. count: *mut u32,
  695. size: usize,
  696. out: *mut u8,
  697. ) -> HRESULT {
  698. let Some(c) = get(container) else {
  699. return E_INVALIDARG;
  700. };
  701. // SAFETY: the title passes its count.
  702. let wanted = unsafe { count.as_ref() }.copied().unwrap_or(0);
  703. let blobs = match read(c, names(blob_names, wanted)) {
  704. Ok(blobs) => blobs,
  705. Err(hr) => return hr,
  706. };
  707. let bytes = layout(&blobs, out as usize);
  708. if out.is_null() || size < bytes.len() {
  709. return BUFFER_TOO_SMALL;
  710. }
  711. // SAFETY: the buffer holds `size` bytes, checked above.
  712. unsafe { out.copy_from_nonoverlapping(bytes.as_ptr(), bytes.len()) };
  713. put(count, blobs.len() as u32)
  714. }
  715. /// Read at once; the result holds the layout with pointers relative to the
  716. /// title's buffer, fixed up when the title takes it.
  717. extern "system" fn read_async(
  718. _: This,
  719. container: *const Container,
  720. blob_names: *const *const c_char,
  721. count: u32,
  722. block: *mut AsyncBlock,
  723. ) -> HRESULT {
  724. let result = match get(container) {
  725. Some(c) => read(c, names(blob_names, count)).map(|blobs| layout(&blobs, 0)),
  726. None => Err(E_INVALIDARG),
  727. };
  728. xasync::finished_with(block, (&raw const READ).cast(), result)
  729. }
  730. extern "system" fn read_result(
  731. _: This,
  732. block: *mut AsyncBlock,
  733. size: usize,
  734. out: *mut u8,
  735. count: *mut u32,
  736. ) -> HRESULT {
  737. let mut used = 0;
  738. let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used);
  739. if hr < 0 {
  740. return hr;
  741. }
  742. // The first name follows the blob array, so its offset gives the count.
  743. let blobs = if used == 0 {
  744. 0
  745. } else {
  746. // SAFETY: the result holds at least one blob entry.
  747. unsafe { out.cast::<usize>().read_unaligned() / BLOB }
  748. };
  749. for i in 0..blobs {
  750. for field in [0, 16] {
  751. // SAFETY: within the blob array just written.
  752. unsafe {
  753. let p = out.add(i * BLOB + field).cast::<usize>();
  754. p.write_unaligned(p.read_unaligned() + out as usize);
  755. }
  756. }
  757. }
  758. put(count, blobs as u32)
  759. }
  760. extern "system" fn create_update(
  761. _: This,
  762. container: *const Container,
  763. display: *const c_char,
  764. out: *mut *mut Update,
  765. ) -> HRESULT {
  766. let Some(c) = get(container) else {
  767. return E_INVALIDARG;
  768. };
  769. put(
  770. out,
  771. give(Update {
  772. name: c.name.clone(),
  773. dir: c.dir.clone(),
  774. display: text(display),
  775. changes: Vec::new(),
  776. }),
  777. )
  778. }
  779. extern "system" fn close_update(_: This, update: *mut Update) {
  780. take(update);
  781. }
  782. extern "system" fn write_blob(
  783. _: This,
  784. update: *mut Update,
  785. name: *const c_char,
  786. data: *const u8,
  787. size: usize,
  788. ) -> HRESULT {
  789. // SAFETY: a handle we gave out; the title does not use it concurrently.
  790. let (Some(update), Some(name)) = (unsafe { update.as_mut() }, text(name)) else {
  791. return E_INVALIDARG;
  792. };
  793. if name.is_empty() || (data.is_null() && size > 0) {
  794. return E_INVALIDARG;
  795. }
  796. if size > MAX_UPDATE {
  797. return UPDATE_TOO_BIG;
  798. }
  799. let data = if size == 0 {
  800. Vec::new()
  801. } else {
  802. // SAFETY: the title passes `size` bytes.
  803. unsafe { std::slice::from_raw_parts(data, size) }.to_vec()
  804. };
  805. update.changes.push((name, Some(data)));
  806. S_OK
  807. }
  808. extern "system" fn delete_blob(_: This, update: *mut Update, name: *const c_char) -> HRESULT {
  809. // SAFETY: as in `write_blob`.
  810. match (unsafe { update.as_mut() }, text(name)) {
  811. (Some(update), Some(name)) if !name.is_empty() => {
  812. update.changes.push((name, None));
  813. S_OK
  814. }
  815. _ => E_INVALIDARG,
  816. }
  817. }
  818. extern "system" fn submit_async(_: This, update: *const Update, block: *mut AsyncBlock) -> HRESULT {
  819. let hr = get(update).map_or(E_INVALIDARG, Update::submit);
  820. xasync::finished(block, (&raw const SUBMIT).cast(), hr)
  821. }
  822. extern "system" fn submit_result(_: This, block: *mut AsyncBlock) -> HRESULT {
  823. let none = std::ptr::null_mut();
  824. xasync::XAsyncGetResult(block, (&raw const SUBMIT).cast(), 0, none, none.cast())
  825. }
  826. static VTABLE: Methods<30> = Methods([
  827. missing::<0> as *const (),
  828. add_ref as *const (),
  829. add_ref as *const (),
  830. missing::<3> as *const (), // 0x18 initialize (blocking)
  831. initialize_async as *const (), // 0x20
  832. initialize_result as *const (), // 0x28
  833. close_provider as *const (), // 0x30
  834. missing::<7> as *const (), // 0x38 remaining quota (blocking)
  835. quota_async as *const (), // 0x40
  836. quota_result as *const (), // 0x48
  837. missing::<10> as *const (), // 0x50 delete (blocking)
  838. delete_async as *const (), // 0x58
  839. delete_result as *const (), // 0x60
  840. container_info as *const (), // 0x68
  841. enumerate_containers as *const (), // 0x70
  842. missing::<15> as *const (), // 0x78 by name prefix
  843. create_container as *const (), // 0x80
  844. close_container as *const (), // 0x88
  845. missing::<18> as *const (), // 0x90 all blob info
  846. enumerate_blobs as *const (), // 0x98 by name prefix
  847. read_blobs as *const (), // 0xa0
  848. read_async as *const (), // 0xa8
  849. read_result as *const (), // 0xb0
  850. create_update as *const (), // 0xb8
  851. close_update as *const (), // 0xc0
  852. write_blob as *const (), // 0xc8
  853. delete_blob as *const (), // 0xd0
  854. missing::<27> as *const (), // 0xd8 submit (blocking)
  855. submit_async as *const (), // 0xe0
  856. submit_result as *const (), // 0xe8
  857. ]);
  858. #[cfg(test)]
  859. mod tests {
  860. use std::io::BufRead;
  861. use std::sync::atomic::{AtomicU32, Ordering};
  862. use super::*;
  863. use crate::modules::xgameruntime::method;
  864. fn block() -> AsyncBlock {
  865. AsyncBlock {
  866. queue: std::ptr::null(),
  867. context: std::ptr::null_mut(),
  868. callback: None,
  869. internal: [0; 4],
  870. }
  871. }
  872. static STEPS: AtomicU32 = AtomicU32::new(0);
  873. /// In a child process of the crash test, stops for good at the step
  874. /// `VICTORY_SAVE_STOP` names and says so.
  875. pub(super) fn crash_point() {
  876. let Ok(stop) = std::env::var("VICTORY_SAVE_STOP") else {
  877. return;
  878. };
  879. if stop.parse() == Ok(STEPS.fetch_add(1, Ordering::SeqCst) + 1) {
  880. println!("STOPPED");
  881. let _ = std::io::stdout().flush();
  882. loop {
  883. std::thread::sleep(std::time::Duration::from_secs(60));
  884. }
  885. }
  886. }
  887. fn update(root: &Path, display: &str, changes: &[(&str, Option<&str>)]) -> HRESULT {
  888. Update {
  889. name: "Slot".into(),
  890. dir: container_dir(root, "Slot"),
  891. display: Some(display.into()),
  892. changes: changes
  893. .iter()
  894. .map(|(n, d)| (n.to_string(), d.map(|d| d.as_bytes().to_vec())))
  895. .collect(),
  896. }
  897. .submit()
  898. }
  899. /// The container `Slot`: display name and blobs.
  900. fn state(root: &Path) -> Option<(String, Vec<(String, String)>)> {
  901. let c = Provider { root: root.into() }.container("Slot");
  902. let display = current_named(&c.dir, "Slot").unwrap()?.display;
  903. let blobs = read(&c, None).unwrap();
  904. let text = |(n, d): (String, Vec<u8>)| (n, String::from_utf8(d).unwrap());
  905. Some((display, blobs.into_iter().map(text).collect()))
  906. }
  907. fn old_state() -> Option<(String, Vec<(String, String)>)> {
  908. Some(("one".into(), vec![("a".into(), "old a".into()), ("b".into(), "old b".into())]))
  909. }
  910. /// Run by the crash test in a child process; does nothing otherwise.
  911. #[test]
  912. fn crash_child() {
  913. let (Ok(root), Ok(op)) = (std::env::var("VICTORY_SAVE_CHILD"), std::env::var("VICTORY_SAVE_OP")) else {
  914. return;
  915. };
  916. let root = PathBuf::from(root);
  917. let hr = if op == "update" {
  918. update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))])
  919. } else {
  920. delete(&root, "Slot")
  921. };
  922. assert_eq!(hr, S_OK);
  923. println!("FINISHED");
  924. }
  925. /// Kills a process in the middle of an update (and of a deletion) at
  926. /// every step: what is left is the whole old container or the whole
  927. /// new one.
  928. #[test]
  929. fn a_kill_at_any_step_leaves_old_or_new() {
  930. let new = Some(("two".into(), vec![("a".into(), "new a".into()), ("c".into(), "new c".into())]));
  931. for (op, after) in [("update", new), ("delete", None)] {
  932. let mut seen = (0, 0);
  933. for stop in 1.. {
  934. let dir = tempfile::tempdir().unwrap();
  935. let root = dir.path();
  936. assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK);
  937. let mut child = std::process::Command::new(std::env::current_exe().unwrap())
  938. .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"])
  939. .args(["--test-threads=1"])
  940. .env("VICTORY_SAVE_CHILD", root)
  941. .env("VICTORY_SAVE_OP", op)
  942. .env("VICTORY_SAVE_STOP", stop.to_string())
  943. .stdout(std::process::Stdio::piped())
  944. .spawn()
  945. .unwrap();
  946. let out = std::io::BufReader::new(child.stdout.take().unwrap());
  947. let mut finished = false;
  948. for line in out.lines() {
  949. let line = line.unwrap();
  950. if line.contains("STOPPED") {
  951. break;
  952. }
  953. finished |= line.contains("FINISHED");
  954. }
  955. let _ = child.kill();
  956. child.wait().unwrap();
  957. let left = state(root);
  958. if left == old_state() {
  959. seen.0 += 1;
  960. } else {
  961. assert_eq!(left, after, "{op}, killed at step {stop}");
  962. seen.1 += 1;
  963. }
  964. if finished {
  965. break;
  966. }
  967. }
  968. assert!(seen.0 > 0 && seen.1 > 1, "{op}: {seen:?}");
  969. }
  970. }
  971. #[test]
  972. fn names_are_exact() {
  973. for name in ["Save_1", "slot/2", "a.b c%", "\u{e9}t\u{e9}"] {
  974. let file = file_name(name);
  975. assert!(!file.contains(['.', '/', ' ']), "{file}");
  976. assert_eq!(decode(&file).as_deref(), Some(name));
  977. }
  978. assert_eq!(decode("x.new"), None);
  979. for good in ["Profile/Slot_1", "a/b/Save-2.sav", "x", &"a".repeat(256)] {
  980. assert!(valid_container(good), "{good}");
  981. }
  982. for bad in ["a b", "", "a/", "a.", "a..b", "a.b/c", "a-b/c", &"a".repeat(257)] {
  983. assert!(!valid_container(bad), "{bad}");
  984. }
  985. // Containers and blobs differing only in case, reserved device
  986. // names, characters the host forbids, long names: all distinct.
  987. let dir = tempfile::tempdir().unwrap();
  988. let p = Provider { root: dir.path().into() };
  989. let long = "n".repeat(300);
  990. let blobs = ["A", "a", "CON", "nul.txt", "x/y:z*?\"<>|", long.as_str(), "end. "];
  991. for container in ["Save", "save", "SAVE/CON.x"] {
  992. let c = p.container(container);
  993. let u = Update {
  994. name: c.name.clone(),
  995. dir: c.dir.clone(),
  996. display: None,
  997. changes: blobs
  998. .iter()
  999. .map(|b| (b.to_string(), Some(format!("{container}:{b}").into_bytes())))
  1000. .collect(),
  1001. };
  1002. assert_eq!(u.submit(), S_OK, "{container}");
  1003. }
  1004. let _saves = saves_lock();
  1005. let names: Vec<String> = containers(dir.path()).into_iter().map(|c| c.0).collect();
  1006. drop(_saves);
  1007. assert_eq!(names, ["SAVE/CON.x", "Save", "save"]);
  1008. for container in ["Save", "save", "SAVE/CON.x"] {
  1009. let read = read(&p.container(container), None).unwrap();
  1010. let mut expected: Vec<_> = blobs
  1011. .iter()
  1012. .map(|b| (b.to_string(), format!("{container}:{b}").into_bytes()))
  1013. .collect();
  1014. expected.sort();
  1015. assert_eq!(read, expected, "{container}");
  1016. }
  1017. }
  1018. #[test]
  1019. fn the_old_layout_moves_over() {
  1020. let saves = tempfile::tempdir().unwrap();
  1021. let root = saves.path().join(format!("{:016X}", xuser::XUID)).join("scid");
  1022. let old = root.join("Player");
  1023. std::fs::create_dir_all(&old).unwrap();
  1024. std::fs::write(old.join("Save%20Game%20Data"), b"data").unwrap();
  1025. std::fs::write(old.join("Save%20Game%20Header"), b"header").unwrap();
  1026. std::fs::write(old.join("Save%20Game%20Data.new"), b"half").unwrap();
  1027. std::fs::write(old.join(".display"), b"Chapter 1").unwrap();
  1028. let p = Provider::open(saves.path(), Some("scid")).unwrap();
  1029. assert!(!old.exists());
  1030. let c = p.container("Player");
  1031. let blobs = read(&c, None).unwrap();
  1032. assert_eq!(
  1033. blobs,
  1034. [
  1035. ("Save Game Data".into(), b"data".to_vec()),
  1036. ("Save Game Header".into(), b"header".to_vec())
  1037. ]
  1038. );
  1039. let v = current_named(&c.dir, "Player").unwrap().unwrap();
  1040. assert_eq!((v.number, v.display.as_str()), (1, "Chapter 1"));
  1041. }
  1042. /// An empty configuration id names none. As a folder name it would be
  1043. /// the folder every configuration lives in, whose folders then look
  1044. /// like containers of the old layout and are converted away.
  1045. #[test]
  1046. fn an_empty_configuration_id_is_the_default_one() {
  1047. let saves = tempfile::tempdir().unwrap();
  1048. let scid = Provider::open(saves.path(), Some("scid")).unwrap();
  1049. assert_eq!(update(&scid.root, "one", &[("a", Some("kept"))]), S_OK);
  1050. let kept = Some(("one".into(), vec![("a".into(), "kept".into())]));
  1051. assert_eq!(state(&scid.root), kept);
  1052. let empty = Provider::open(saves.path(), Some("")).unwrap();
  1053. assert!(scid.root.is_dir(), "another configuration's saves are gone");
  1054. assert_eq!(state(&scid.root), kept);
  1055. let default = Provider::open(saves.path(), None).unwrap();
  1056. assert_eq!(empty.root, default.root);
  1057. // Named configurations stay apart, from it and from each other.
  1058. assert_ne!(empty.root, scid.root);
  1059. assert_eq!(state(&empty.root), None);
  1060. let other = Provider::open(saves.path(), Some("other")).unwrap();
  1061. assert_eq!(state(&other.root), None);
  1062. assert_eq!(state(&scid.root), kept);
  1063. }
  1064. #[test]
  1065. fn saves_persist_across_providers() {
  1066. let this: This = &OBJECT;
  1067. let saves = tempfile::tempdir().unwrap();
  1068. let provider = give(Provider::open(saves.path(), Some("scid")).unwrap());
  1069. // Write two blobs through an update.
  1070. let mut container = std::ptr::null_mut();
  1071. type Create = extern "system" fn(
  1072. This,
  1073. *const Provider,
  1074. *const c_char,
  1075. *mut *mut Container,
  1076. ) -> HRESULT;
  1077. let create = method::<Create>(&OBJECT, 0x80);
  1078. assert_eq!(
  1079. create(this, provider, c"bad name".as_ptr(), &mut container),
  1080. INVALID_CONTAINER_NAME
  1081. );
  1082. assert_eq!(
  1083. create(this, provider, c"Slot_1".as_ptr(), &mut container),
  1084. S_OK
  1085. );
  1086. let mut update = std::ptr::null_mut();
  1087. type Update_ =
  1088. extern "system" fn(This, *const Container, *const c_char, *mut *mut Update) -> HRESULT;
  1089. assert_eq!(
  1090. method::<Update_>(&OBJECT, 0xb8)(this, container, c"Chapter 1".as_ptr(), &mut update),
  1091. S_OK
  1092. );
  1093. type Write =
  1094. extern "system" fn(This, *mut Update, *const c_char, *const u8, usize) -> HRESULT;
  1095. let write = method::<Write>(&OBJECT, 0xc8);
  1096. assert_eq!(
  1097. write(this, update, c"world".as_ptr(), b"hello".as_ptr(), 5),
  1098. S_OK
  1099. );
  1100. assert_eq!(
  1101. write(this, update, c"player.dat".as_ptr(), b"xy".as_ptr(), 2),
  1102. S_OK
  1103. );
  1104. assert_eq!(
  1105. write(this, update, c"gone".as_ptr(), b"z".as_ptr(), 1),
  1106. S_OK
  1107. );
  1108. type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT;
  1109. assert_eq!(method::<Delete>(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), S_OK);
  1110. type Submit = extern "system" fn(This, *const Update, *mut AsyncBlock) -> HRESULT;
  1111. let mut b = block();
  1112. assert_eq!(method::<Submit>(&OBJECT, 0xe0)(this, update, &mut b), S_OK);
  1113. assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
  1114. close_update(this, update);
  1115. close_container(this, container);
  1116. close_provider(this, provider);
  1117. // A new provider sees the container and reads both blobs back.
  1118. let provider = give(Provider::open(saves.path(), Some("scid")).unwrap());
  1119. extern "system" fn seen(info: *const ContainerInfo, context: *mut c_void) -> bool {
  1120. // SAFETY: valid during the callback; the context is the test's vector.
  1121. let (info, out) = unsafe {
  1122. (
  1123. &*info,
  1124. &mut *context.cast::<Vec<(String, String, u32, u64)>>(),
  1125. )
  1126. };
  1127. out.push((
  1128. text(info.name).unwrap(),
  1129. text(info.display_name).unwrap(),
  1130. info.blob_count,
  1131. info.total_size,
  1132. ));
  1133. true
  1134. }
  1135. let mut found: Vec<(String, String, u32, u64)> = Vec::new();
  1136. let context = (&raw mut found).cast();
  1137. assert_eq!(
  1138. enumerate_containers(this, provider, context, Some(seen)),
  1139. S_OK
  1140. );
  1141. assert_eq!(found, [("Slot_1".into(), "Chapter 1".into(), 2, 7)]);
  1142. let mut container = std::ptr::null_mut();
  1143. assert_eq!(
  1144. create_container(this, provider, c"Slot_1".as_ptr(), &mut container),
  1145. S_OK
  1146. );
  1147. let mut b = block();
  1148. let wanted = [c"world".as_ptr(), c"player.dat".as_ptr()];
  1149. assert_eq!(
  1150. read_async(this, container, wanted.as_ptr(), 2, &mut b),
  1151. S_OK
  1152. );
  1153. assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
  1154. let mut size = 0;
  1155. assert_eq!(xasync::XAsyncGetResultSize(&mut b, &mut size), S_OK);
  1156. assert_eq!(
  1157. size,
  1158. 2 * BLOB + "world\0hello".len() + "player.dat\0xy".len()
  1159. );
  1160. let mut buffer = vec![0u64; size.div_ceil(8)];
  1161. let mut count = 0;
  1162. assert_eq!(
  1163. read_result(this, &mut b, size, buffer.as_mut_ptr().cast(), &mut count),
  1164. S_OK
  1165. );
  1166. assert_eq!(count, 2);
  1167. let blob = |i: usize| {
  1168. // SAFETY: the layout the call wrote.
  1169. unsafe {
  1170. let entry = buffer.as_ptr().cast::<u8>().add(i * BLOB);
  1171. let name = text(entry.cast::<*const c_char>().read_unaligned()).unwrap();
  1172. let len = entry.add(8).cast::<u32>().read_unaligned() as usize;
  1173. let data = std::slice::from_raw_parts(
  1174. entry.add(16).cast::<*const u8>().read_unaligned(),
  1175. len,
  1176. );
  1177. (name, data.to_vec())
  1178. }
  1179. };
  1180. assert_eq!(blob(0), ("world".into(), b"hello".to_vec()));
  1181. assert_eq!(blob(1), ("player.dat".into(), b"xy".to_vec()));
  1182. let missing = [c"nothing".as_ptr()];
  1183. let mut one = 1;
  1184. let mut small = [0u8; 8];
  1185. let read_now = method::<
  1186. extern "system" fn(
  1187. This,
  1188. *const Container,
  1189. *const *const c_char,
  1190. *mut u32,
  1191. usize,
  1192. *mut u8,
  1193. ) -> HRESULT,
  1194. >(&OBJECT, 0xa0);
  1195. assert_eq!(
  1196. read_now(
  1197. this,
  1198. container,
  1199. missing.as_ptr(),
  1200. &mut one,
  1201. 8,
  1202. small.as_mut_ptr()
  1203. ),
  1204. BLOB_NOT_FOUND
  1205. );
  1206. assert_eq!(
  1207. read_now(
  1208. this,
  1209. container,
  1210. wanted.as_ptr(),
  1211. &mut 2,
  1212. 8,
  1213. small.as_mut_ptr()
  1214. ),
  1215. BUFFER_TOO_SMALL
  1216. );
  1217. // Quota counts the blobs; deleting the container frees it.
  1218. let mut b = block();
  1219. assert_eq!(quota_async(this, provider, &mut b), S_OK);
  1220. let mut left = 0i64;
  1221. assert_eq!(quota_result(this, &mut b, &mut left), S_OK);
  1222. assert!(left as u64 <= QUOTA - 7);
  1223. let mut b = block();
  1224. assert_eq!(
  1225. delete_async(this, provider, c"Slot_1".as_ptr(), &mut b),
  1226. S_OK
  1227. );
  1228. assert_eq!(delete_result(this, &mut b), S_OK);
  1229. found.clear();
  1230. let context = (&raw mut found).cast();
  1231. assert_eq!(
  1232. enumerate_containers(this, provider, context, Some(seen)),
  1233. S_OK
  1234. );
  1235. assert!(found.is_empty());
  1236. close_container(this, container);
  1237. close_provider(this, provider);
  1238. }
  1239. }