Skip to content

Commit c5fe6b5

Browse files
seeddsv0lumehi
andcommitted
Find iOS DLC in Documents and replace stale content (#486)
The iOS launcher searched only the app bundle for DLC, even when the base RomFS was deployed separately. Preserve DM_AOC_DIR overrides, then search Documents/aoc before the bundle, and exclude external DLC from backups. Push the complete DLC set from resources.env with replacement semantics. Directory merges retained removed indices, which the host still counted and mounted. Send an empty directory for builds without DLC, reject a missing declared source before transfer, and preserve DLC for image-only pushes that carry no DLC metadata. Add synthetic transfer regression tests and retain the author's Foundation startup tests. Document the mechanism and regenerate the symptom index. Validation: 59 tests passed, one disk-image test skipped; 185 iOS sources compiled; Python lint has no new findings. Regression risk is low: only iOS discovery and transfer change, so no game regression run was needed. Device transfers remain untested. Co-authored-by: v0lumehi <[email protected]>
1 parent 3d247f3 commit c5fe6b5

8 files changed

Lines changed: 196 additions & 11 deletions

File tree

‎dm/ios/Sources/main.m‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// iOS App entry: set the environment (game files, saves, shader libraries), write the host log to Documents/log.txt, create the window (front_ios.m), then run the host's dm_main on a big-stack thread.
2-
// The game files (RomFS) ship inside the App at <App>/romfs; Documents/romfs.img (one image, scripts/push_romfs.sh; its name in any letter case) or a Documents/romfs folder is also accepted (lets you swap them without reinstalling).
2+
// The game files (RomFS) ship inside the App at <App>/romfs; Documents/romfs.img (one image, scripts/push_romfs.sh; its name in any letter case) or a Documents/romfs folder is also accepted (lets you swap them without reinstalling). The DLC folder aoc/ likewise: Documents/aoc, else <App>/aoc.
33
#import <UIKit/UIKit.h>
44
#import <Metal/Metal.h>
55
#include <pthread.h>
@@ -78,6 +78,21 @@ static int romfs_identity_accepts(NSString *img) {
7878
return nil;
7979
}
8080

81+
// Add-on content (DLC): each DLC's RomFS image at <dir>/<index>.img (or a legacy <index>/ folder). Like the game files, Documents/aoc comes before <App>/aoc.
82+
// A DM_AOC_DIR that is already set (env.txt, the launch environment) wins. The host mounts and counts the DLC from DM_AOC_DIR (hle_fs.c, hle_misc.c)
83+
static void aoc_locate(void) {
84+
if (getenv("DM_AOC_DIR")) return;
85+
NSFileManager *fm = NSFileManager.defaultManager;
86+
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
87+
for (NSString *d in @[[doc stringByAppendingPathComponent:@"aoc"], [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"aoc"]]) {
88+
BOOL dir = NO;
89+
if (![fm fileExistsAtPath:d isDirectory:&dir] || !dir) continue;
90+
setenv("DM_AOC_DIR", d.fileSystemRepresentation, 0);
91+
fprintf(stderr, "boot: DLC from %s\n", d.fileSystemRepresentation);
92+
return;
93+
}
94+
}
95+
8196
// Boot prerequisites (done before UIApplicationMain): directories / environment variables / log -- the host's early load reads these
8297
// Why a slim build found no usable game files: the verdict on Documents/romfs.img (the first of romfs_document_images), in the log and for the screen (front_ios_boot_message). NULL when the build has no romfs.id
8398
static char g_boot_message[640];
@@ -101,7 +116,7 @@ static int boot_env(void) {
101116
NSString *res = NSBundle.mainBundle.resourcePath;
102117
for (NSString *d in @[@"save", @"temp"]) [fm createDirectoryAtPath:[doc stringByAppendingPathComponent:d] withIntermediateDirectories:YES attributes:nil error:nil];
103118
// Keep game files and scratch data out of device backups (Documents is backed up by default; a RomFS placed there is many GB). Saves, logs and the pipeline list stay in the backup
104-
for (NSString *d in [@[@"romfs", @"temp"] arrayByAddingObjectsFromArray:[romfs_document_images(doc) valueForKey:@"lastPathComponent"]]) {
119+
for (NSString *d in [@[@"romfs", @"aoc", @"temp"] arrayByAddingObjectsFromArray:[romfs_document_images(doc) valueForKey:@"lastPathComponent"]]) {
105120
NSURL *u = [NSURL fileURLWithPath:[doc stringByAppendingPathComponent:d]]; NSError *e = nil;
106121
if ([fm fileExistsAtPath:u.path] && ![u setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&e]) fprintf(stderr, "boot: %s could not be excluded from backup: %s\n", d.UTF8String, e.localizedDescription.UTF8String);
107122
}
@@ -160,8 +175,7 @@ static int boot_env(void) {
160175
setenv("DM_NVN_SHMAP", [dm stringByAppendingPathComponent:@"shader_map.tsv"].fileSystemRepresentation, 0);
161176
setenv("DM_MSL_DIR", [res stringByAppendingPathComponent:@"msl"].fileSystemRepresentation, 0);
162177
setenv("DM_FONT_DIR", [dm stringByAppendingPathComponent:@"font"].fileSystemRepresentation, 0); // Shared-font stand-ins (standard.ttf / nintendo_ext.ttf): iOS lacks the macOS font path
163-
NSString *aoc = [res stringByAppendingPathComponent:@"aoc"]; // add-on content: build_ipa.sh puts the RomFS extracted from the player's DLC NSPs at <App>/aoc/<index>/
164-
if ([fm fileExistsAtPath:aoc]) setenv("DM_AOC_DIR", aoc.fileSystemRepresentation, 0);
178+
aoc_locate(); // add-on content: Documents/aoc, else <App>/aoc; an empty Documents/aoc explicitly selects no DLC
165179
NSString *pso = [res stringByAppendingPathComponent:@"pso"]; // the pipeline archive made offline (build_ipa.sh, dm/gfx/tools/pso_offline.py): the shader pairs' bases, which the device then does not build
166180
if ([fm fileExistsAtPath:pso]) setenv("DM_PSO_BUNDLE", pso.fileSystemRepresentation, 0);
167181
chdir(doc.fileSystemRepresentation);

‎dm/ios/tests/test_aoc_startup.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""Run the actual iOS DLC locator (main.m aoc_locate) on macOS/Foundation with private Documents and App folders (no device or game files)."""
2+
from pathlib import Path
3+
import os
4+
import subprocess
5+
import sys
6+
import tempfile
7+
import unittest
8+
9+
REPO = Path(__file__).resolve().parents[3]
10+
11+
12+
@unittest.skipUnless(sys.platform == 'darwin', 'Foundation required')
13+
class AocStartup(unittest.TestCase):
14+
@classmethod
15+
def setUpClass(cls):
16+
cls.tools = tempfile.TemporaryDirectory(); cls.addClassCleanup(cls.tools.cleanup)
17+
root = Path(cls.tools.name)
18+
main = (REPO / 'dm/ios/Sources/main.m').read_text()
19+
locator = main[main.index('static void aoc_locate'):main.index('// Boot prerequisites')]
20+
source = root / 'aoc.m'
21+
source.write_text('#import <Foundation/Foundation.h>\n#include <stdio.h>\n#include <stdlib.h>\n'
22+
'static NSString *fixture_doc, *fixture_bundle;\n'
23+
'@interface FixtureBundle : NSObject\n+ (instancetype)mainBundle;\n- (NSString *)resourcePath;\n@end\n'
24+
'@implementation FixtureBundle\n+ (instancetype)mainBundle { return [self new]; }\n'
25+
'- (NSString *)resourcePath { return fixture_bundle; }\n@end\n#define NSBundle FixtureBundle\n'
26+
'#define NSSearchPathForDirectoriesInDomains(a,b,c) @[fixture_doc]\n' + locator +
27+
'\nint main(int argc, char **argv) { @autoreleasepool { if (argc < 3) return 2;\n'
28+
'fixture_doc = @(argv[1]); fixture_bundle = @(argv[2]); aoc_locate();\n'
29+
'const char *e = getenv("DM_AOC_DIR"); puts(e ? e : "(none)"); return 0; }}\n')
30+
cls.locator = root / 'aoc'
31+
subprocess.run(['clang', '-fobjc-arc', '-Wall', '-Werror', str(source), '-framework', 'Foundation', '-o', str(cls.locator)], check=True)
32+
33+
def locate(self, doc, app, env=None):
34+
e = {k: v for k, v in os.environ.items() if k != 'DM_AOC_DIR'}; e.update(env or {})
35+
r = subprocess.run([str(self.locator), str(doc), str(app)], capture_output=True, text=True, env=e)
36+
self.assertEqual(r.returncode, 0, r.stderr); return r.stdout.strip(), r.stderr
37+
38+
def test_order_documents_then_bundle_and_none(self):
39+
with tempfile.TemporaryDirectory() as t:
40+
doc = Path(t) / 'Documents'; app = Path(t) / 'App'; doc.mkdir(); app.mkdir()
41+
self.assertEqual(self.locate(doc, app), ('(none)', ''))
42+
(app / 'aoc').mkdir()
43+
out, log = self.locate(doc, app)
44+
self.assertEqual(out, str(app / 'aoc')); self.assertIn(f'boot: DLC from {app / "aoc"}', log)
45+
(doc / 'aoc').mkdir()
46+
out, log = self.locate(doc, app)
47+
self.assertEqual(out, str(doc / 'aoc')); self.assertIn(f'boot: DLC from {doc / "aoc"}', log)
48+
49+
def test_a_file_named_aoc_does_not_count(self):
50+
with tempfile.TemporaryDirectory() as t:
51+
doc = Path(t) / 'Documents'; app = Path(t) / 'App'; doc.mkdir(); app.mkdir()
52+
(doc / 'aoc').write_text('x'); (app / 'aoc').mkdir()
53+
self.assertEqual(self.locate(doc, app)[0], str(app / 'aoc'))
54+
55+
def test_preset_variable_wins(self):
56+
with tempfile.TemporaryDirectory() as t:
57+
doc = Path(t) / 'Documents'; app = Path(t) / 'App'; (doc / 'aoc').mkdir(parents=True); (app / 'aoc').mkdir(parents=True)
58+
out, log = self.locate(doc, app, {'DM_AOC_DIR': '/elsewhere'})
59+
self.assertEqual(out, '/elsewhere'); self.assertNotIn('DLC from', log)
60+
61+
62+
if __name__ == '__main__': unittest.main()

‎dm/ios/tests/test_romfs_startup.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def setUpClass(cls):
2020
cls.tools = tempfile.TemporaryDirectory(); cls.addClassCleanup(cls.tools.cleanup)
2121
root = Path(cls.tools.name)
2222
main = (REPO / 'dm/ios/Sources/main.m').read_text()
23-
locator = main[main.index('static int romfs_image_complete'):main.index('// Boot prerequisites')]
23+
locator = main[main.index('static int romfs_image_complete'):main.index('// Add-on content (DLC)')]
2424
source = root / 'locator.m'
2525
source.write_text('#import <Foundation/Foundation.h>\n#include <stdio.h>\n#include "romfs_image.h"\n#include "romfs_identity.h"\n'
2626
'static NSString *fixture_doc, *fixture_tmp, *fixture_bundle;\n#define DM_GAME_ROMFS_MARKER "marker"\n'

‎dm/tools/tests/test_romfs_image.py‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def test_push_helper_refreshes_cache_and_propagates_copy_failure(self):
102102
resources.write_text('DM_RESOURCE_ROMFS=' + shlex.quote(str(self.src)) + '\n')
103103
bin_dir = self.root / 'bin'; bin_dir.mkdir()
104104
xcrun = bin_dir / 'xcrun'
105-
xcrun.write_text('#!/bin/sh\nprintf "%s\\n" "$@" > "$ROMFS_PUSH_ARGS"\nexit "${ROMFS_PUSH_RC:-0}"\n')
105+
xcrun.write_text('#!/bin/sh\nprintf "%s\\n" "$@" >> "$ROMFS_PUSH_ARGS"\nexit "${ROMFS_PUSH_RC:-0}"\n')
106106
xcrun.chmod(0o755)
107107
args_file = self.root / 'copy-args'
108108
env = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'], ROMFS_PUSH_ARGS=str(args_file))
@@ -155,4 +155,86 @@ def test_size_consistent_invalid_index_is_rejected(self):
155155
self.dst.write_bytes(raw); self.assertFalse(self.valid())
156156

157157

158+
class DlcTransfers(unittest.TestCase):
159+
"""Run the push helper against devicectl's directory merge/replacement semantics."""
160+
161+
def setUp(self):
162+
temporary = tempfile.TemporaryDirectory(prefix='dlc push '); self.addCleanup(temporary.cleanup)
163+
self.root = Path(temporary.name)
164+
source = self.root / 'RomFS'; source.mkdir(); (source / 'marker').write_text('base game')
165+
self.img = self.root / 'RomFS.img'; image.pack(source, self.img)
166+
self.aoc = self.root / 'add-on content'; self.aoc.mkdir()
167+
self.device = self.root / 'device'; self.device.mkdir()
168+
self.scratch = self.root / 'scratch'; self.scratch.mkdir()
169+
bin_dir = self.root / 'bin'; bin_dir.mkdir()
170+
xcrun = bin_dir / 'xcrun'
171+
xcrun.write_text('''#!/usr/bin/env python3
172+
import os, shutil, sys
173+
from pathlib import Path
174+
args = sys.argv[1:]
175+
assert args[:4] == ['devicectl', 'device', 'copy', 'to']
176+
src = Path(args[args.index('--source') + 1])
177+
dst = Path(os.environ['DLC_PUSH_DEVICE']) / args[args.index('--destination') + 1]
178+
if dst.name == 'aoc' and os.environ.get('DLC_PUSH_FAIL'): sys.exit(int(os.environ['DLC_PUSH_FAIL']))
179+
dst.parent.mkdir(parents=True, exist_ok=True)
180+
if src.is_dir():
181+
# devicectl defaults to merging; only an explicit true removes old content.
182+
if '--remove-existing-content' in args and args[args.index('--remove-existing-content') + 1] == 'true' and dst.exists(): shutil.rmtree(dst)
183+
shutil.copytree(src, dst, dirs_exist_ok=True)
184+
else: shutil.copyfile(src, dst)
185+
''')
186+
xcrun.chmod(0o755)
187+
self.env = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'],
188+
DLC_PUSH_DEVICE=str(self.device), TMPDIR=str(self.scratch))
189+
190+
def push(self, aoc=None, *, image_only=False):
191+
resources = self.root / 'resources.env'
192+
resources.write_text('DM_RESOURCE_ROMFS=' + shlex.quote(str(self.img)) + '\n' +
193+
('DM_RESOURCE_AOC=' + shlex.quote(str(aoc)) + '\n' if aoc is not None else ''))
194+
return subprocess.run(['bash', str(REPO / 'scripts/push_romfs.sh'), 'fixture-device', 'fixture.bundle',
195+
str(self.img if image_only else resources)], env=self.env, capture_output=True, text=True)
196+
197+
def test_smaller_dlc_set_replaces_images_and_legacy_folders(self):
198+
(self.aoc / '1.img').write_text('old')
199+
(self.aoc / '2').mkdir(); (self.aoc / '2/marker').write_text('legacy DLC')
200+
result = self.push(self.aoc); self.assertEqual(result.returncode, 0, result.stderr)
201+
remote = self.device / 'Documents/aoc'
202+
self.assertEqual({p.name for p in remote.iterdir()}, {'1.img', '2'})
203+
(self.aoc / '1.img').write_text('updated'); shutil.rmtree(self.aoc / '2')
204+
result = self.push(self.aoc); self.assertEqual(result.returncode, 0, result.stderr)
205+
self.assertEqual({p.name for p in remote.iterdir()}, {'1.img'})
206+
self.assertEqual((remote / '1.img').read_text(), 'updated')
207+
208+
def test_empty_dlc_set_clears_previous_content(self):
209+
for aoc in ('', None, self.aoc):
210+
with self.subTest(aoc=aoc):
211+
remote = self.device / 'Documents/aoc'; remote.mkdir(parents=True, exist_ok=True)
212+
(remote / '1.img').write_text('stale')
213+
self.env['DM_RESOURCE_AOC'] = str(self.root / 'inherited-stale-path')
214+
result = self.push(aoc); self.assertEqual(result.returncode, 0, result.stderr)
215+
self.assertTrue(remote.is_dir()); self.assertEqual(list(remote.iterdir()), [])
216+
self.assertEqual(list(self.scratch.iterdir()), [])
217+
218+
def test_image_only_push_preserves_dlc(self):
219+
remote = self.device / 'Documents/aoc'; remote.mkdir(parents=True)
220+
(remote / '1.img').write_text('keep')
221+
self.env['DM_RESOURCE_AOC'] = str(self.aoc)
222+
result = self.push(image_only=True); self.assertEqual(result.returncode, 0, result.stderr)
223+
self.assertEqual((remote / '1.img').read_text(), 'keep')
224+
self.assertEqual((self.device / 'Documents/romfs.img').read_bytes(), self.img.read_bytes())
225+
226+
def test_missing_dlc_stops_before_any_transfer(self):
227+
result = self.push(self.root / 'missing')
228+
self.assertNotEqual(result.returncode, 0)
229+
self.assertIn('Add-on content unavailable', result.stderr)
230+
self.assertEqual(list(self.device.iterdir()), [])
231+
232+
def test_dlc_transfer_failure_is_reported(self):
233+
self.env['DLC_PUSH_FAIL'] = '7'
234+
result = self.push(self.aoc)
235+
self.assertEqual(result.returncode, 7)
236+
self.assertNotIn('DLC on the phone', result.stdout)
237+
self.assertNotIn('game files on the phone', result.stdout)
238+
239+
158240
if __name__ == '__main__': unittest.main()

‎docs/agents/symptoms.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
1313
- a `--romfs separate` app whose image was copied into its Documents folder by hand (Finder, the Files app, a LiveContainer guest) logs `boot: game files not found (Documents/romfs.img, Documents/romfs or <App>/romfs)`, and a build with `romfs.id` shows "There is no game file image on this device.", though the complete image is there. Renaming it to `romfs.img` makes the game start. → [A hand-copied RomFS.img is not found on iOS](../reference/packing.md#a-hand-copied-romfsimg-is-not-found-on-ios)
1414
- reducing the iPhone transfer to one image still creates thousands of resource files on the Mac, and build scanners require the expanded folder. → [Building creates a full RomFS tree before packing its image](../reference/packing.md#building-creates-a-full-romfs-tree-before-packing-its-image)
1515
- the NSP script stops at the shader split of a registered profile with `[RED] 13744 file(s) could not be read, their shaders are left out (first: AI/FileEntry/FileEntry.Product.100.byml.zs: CalledProcessError: Command ['zstd', '-d', '-c', '-q', '…/extract/v0/RomFS.img/AI/…'] returned non-zero exit status 1.)`. → [The zstd command given a path inside the image](../reference/packing.md#the-zstd-command-given-a-path-inside-the-image)
16+
- a game's DLC works only when packed inside its IPA, although its base RomFS can be deployed separately. After pushing a smaller DLC set, removed indices can remain reported as owned and mounted. → [DLC in Documents is ignored or removed DLC remains installed](../reference/packing.md#dlc-in-documents-is-ignored-or-removed-dlc-remains-installed)
1617
- starting a Mac app through a front end with unchanged settings enables the encode thread, and can disable Metal 4 pipelines and the pipeline archive; starting the same app from Finder keeps the host's defaults. → [A Mac front end's default settings change Metal execution paths](../reference/packing.md#a-mac-front-ends-default-settings-change-metal-execution-paths)
1718
- with the NSP folder on an exFAT or FAT drive, the build leaves out an update whose name has no `[v…]` tag (the folder seems to hold two), or a stage stops with `FileNotFoundError` on a `._<name>` path inside `<id>_build/` and the next run fails on the half-deleted folder. → [A game folder on an exFAT drive reads one update as two, or fails to remove a folder](../reference/packing.md#a-game-folder-on-an-exfat-drive-reads-one-update-as-two-or-fails-to-remove-a-folder)
1819
- with the build folder on an exFAT or FAT drive, the shader step compiles every library and then stops in `c1_guard.py` with `UnicodeDecodeError: 'utf-8' codec can't decode byte …` (dmsh_build.py: `[RED] c1_guard.py failed`), reading a `._<key>_b.metal`. → [The c1 guard stops on an AppleDouble file after the shader build](../reference/packing.md#the-c1-guard-stops-on-an-appledouble-file-after-the-shader-build)

0 commit comments

Comments
 (0)