Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions dm/ios/Sources/main.m
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// 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.
// 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 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.
#import <UIKit/UIKit.h>
#include <pthread.h>
#include <signal.h>
Expand Down Expand Up @@ -76,6 +76,20 @@ static int romfs_identity_accepts(NSString *img) {
if ([fm fileExistsAtPath:[d stringByAppendingPathComponent:@DM_GAME_ROMFS_MARKER]]) return d; // only a directory containing the game profile's romfs_marker path counts (Mario: System/Resource, the resource size table)
return nil;
}
// Add-on content (DLC): the RomFS of each DLC NSP at <dir>/<index>/ (build_ipa.sh, scripts/push_romfs.sh). Like the game files, Documents/aoc (put there without reinstalling) comes before <App>/aoc.
// 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)
static void aoc_locate(void) {
if (getenv("DM_AOC_DIR")) return;
NSFileManager *fm = NSFileManager.defaultManager;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
for (NSString *d in @[[doc stringByAppendingPathComponent:@"aoc"], [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"aoc"]]) {
BOOL dir = NO;
if (![fm fileExistsAtPath:d isDirectory:&dir] || !dir) continue;
setenv("DM_AOC_DIR", d.fileSystemRepresentation, 0);
fprintf(stderr, "boot: DLC from %s\n", d.fileSystemRepresentation);
return;
}
}

// Boot prerequisites (done before UIApplicationMain): directories / environment variables / log -- the host's early load reads these
// 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
Expand All @@ -96,7 +110,7 @@ static int boot_env(void) {
NSString *res = NSBundle.mainBundle.resourcePath;
for (NSString *d in @[@"save", @"temp"]) [fm createDirectoryAtPath:[doc stringByAppendingPathComponent:d] withIntermediateDirectories:YES attributes:nil error:nil];
// 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
for (NSString *d in [@[@"romfs", @"temp"] arrayByAddingObjectsFromArray:[romfs_document_images(doc) valueForKey:@"lastPathComponent"]]) {
for (NSString *d in [@[@"romfs", @"aoc", @"temp"] arrayByAddingObjectsFromArray:[romfs_document_images(doc) valueForKey:@"lastPathComponent"]]) {
NSURL *u = [NSURL fileURLWithPath:[doc stringByAppendingPathComponent:d]]; NSError *e = nil;
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);
}
Expand Down Expand Up @@ -149,8 +163,7 @@ static int boot_env(void) {
setenv("DM_NVN_SHMAP", [dm stringByAppendingPathComponent:@"shader_map.tsv"].fileSystemRepresentation, 0);
setenv("DM_MSL_DIR", [res stringByAppendingPathComponent:@"msl"].fileSystemRepresentation, 0);
setenv("DM_FONT_DIR", [dm stringByAppendingPathComponent:@"font"].fileSystemRepresentation, 0); // Shared-font stand-ins (standard.ttf / nintendo_ext.ttf): iOS lacks the macOS font path
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>/
if ([fm fileExistsAtPath:aoc]) setenv("DM_AOC_DIR", aoc.fileSystemRepresentation, 0);
aoc_locate(); // add-on content: Documents/aoc, else <App>/aoc (build_ipa.sh puts the RomFS extracted from the player's DLC NSPs there as <index>/)
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
if ([fm fileExistsAtPath:pso]) setenv("DM_PSO_BUNDLE", pso.fileSystemRepresentation, 0);
chdir(doc.fileSystemRepresentation);
Expand Down
62 changes: 62 additions & 0 deletions dm/ios/tests/test_aoc_startup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Run the actual iOS DLC locator (main.m aoc_locate) on macOS/Foundation with private Documents and App folders (no device or game files)."""
from pathlib import Path
import os
import subprocess
import sys
import tempfile
import unittest

REPO = Path(__file__).resolve().parents[3]


@unittest.skipUnless(sys.platform == 'darwin', 'Foundation required')
class AocStartup(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tools = tempfile.TemporaryDirectory(); cls.addClassCleanup(cls.tools.cleanup)
root = Path(cls.tools.name)
main = (REPO / 'dm/ios/Sources/main.m').read_text()
locator = main[main.index('static void aoc_locate'):main.index('// Boot prerequisites')]
source = root / 'aoc.m'
source.write_text('#import <Foundation/Foundation.h>\n#include <stdio.h>\n#include <stdlib.h>\n'
'static NSString *fixture_doc, *fixture_bundle;\n'
'@interface FixtureBundle : NSObject\n+ (instancetype)mainBundle;\n- (NSString *)resourcePath;\n@end\n'
'@implementation FixtureBundle\n+ (instancetype)mainBundle { return [self new]; }\n'
'- (NSString *)resourcePath { return fixture_bundle; }\n@end\n#define NSBundle FixtureBundle\n'
'#define NSSearchPathForDirectoriesInDomains(a,b,c) @[fixture_doc]\n' + locator +
'\nint main(int argc, char **argv) { @autoreleasepool { if (argc < 3) return 2;\n'
'fixture_doc = @(argv[1]); fixture_bundle = @(argv[2]); aoc_locate();\n'
'const char *e = getenv("DM_AOC_DIR"); puts(e ? e : "(none)"); return 0; }}\n')
cls.locator = root / 'aoc'
subprocess.run(['clang', '-fobjc-arc', '-Wall', '-Werror', str(source), '-framework', 'Foundation', '-o', str(cls.locator)], check=True)

def locate(self, doc, app, env=None):
e = {k: v for k, v in os.environ.items() if k != 'DM_AOC_DIR'}; e.update(env or {})
r = subprocess.run([str(self.locator), str(doc), str(app)], capture_output=True, text=True, env=e)
self.assertEqual(r.returncode, 0, r.stderr); return r.stdout.strip(), r.stderr

def test_order_documents_then_bundle_and_none(self):
with tempfile.TemporaryDirectory() as t:
doc = Path(t) / 'Documents'; app = Path(t) / 'App'; doc.mkdir(); app.mkdir()
self.assertEqual(self.locate(doc, app), ('(none)', ''))
(app / 'aoc').mkdir()
out, log = self.locate(doc, app)
self.assertEqual(out, str(app / 'aoc')); self.assertIn(f'boot: DLC from {app / "aoc"}', log)
(doc / 'aoc').mkdir()
out, log = self.locate(doc, app)
self.assertEqual(out, str(doc / 'aoc')); self.assertIn(f'boot: DLC from {doc / "aoc"}', log)

def test_a_file_named_aoc_does_not_count(self):
with tempfile.TemporaryDirectory() as t:
doc = Path(t) / 'Documents'; app = Path(t) / 'App'; doc.mkdir(); app.mkdir()
(doc / 'aoc').write_text('x'); (app / 'aoc').mkdir()
self.assertEqual(self.locate(doc, app)[0], str(app / 'aoc'))

def test_preset_variable_wins(self):
with tempfile.TemporaryDirectory() as t:
doc = Path(t) / 'Documents'; app = Path(t) / 'App'; (doc / 'aoc').mkdir(parents=True); (app / 'aoc').mkdir(parents=True)
out, log = self.locate(doc, app, {'DM_AOC_DIR': '/elsewhere'})
self.assertEqual(out, '/elsewhere'); self.assertNotIn('DLC from', log)


if __name__ == '__main__': unittest.main()
2 changes: 1 addition & 1 deletion dm/ios/tests/test_romfs_startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def setUpClass(cls):
cls.tools = tempfile.TemporaryDirectory(); cls.addClassCleanup(cls.tools.cleanup)
root = Path(cls.tools.name)
main = (REPO / 'dm/ios/Sources/main.m').read_text()
locator = main[main.index('static int romfs_image_complete'):main.index('// Boot prerequisites')]
locator = main[main.index('static int romfs_image_complete'):main.index('// Add-on content (DLC)')]
source = root / 'locator.m'
source.write_text('#import <Foundation/Foundation.h>\n#include <stdio.h>\n#include "romfs_image.h"\n#include "romfs_identity.h"\n'
'static NSString *fixture_doc, *fixture_tmp, *fixture_bundle;\n#define DM_GAME_ROMFS_MARKER "marker"\n'
Expand Down
2 changes: 1 addition & 1 deletion docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ Each prepared game is a scheme in the shared workspace (by default `NxNative.xcw

A full install sends the whole app, about 11 GB for Animal Crossing: New Horizons (3 to 4 minutes). The game files can stay on the phone instead:

1. Once per game, with an app built with image support installed: `scripts/push_romfs.sh <device UDID> <bundle ID> "<NSP folder>/<title ID>_build/xcode/Gen/resources.env"`. It validates and copies the extracted image directly to `Documents/romfs.img`. A legacy folder source is packed first; its `.inputs.json` stamp tracks source names and metadata, the packer and image identity, and `--repack` forces that legacy conversion again. The host reads file ranges through one descriptor, with `DM_ROMFS_OVERLAY` folders taking precedence. iOS startup and the host share the complete index validator: an invalid or interrupted image leaves the folder fallback intact. Only after validation is an old `Documents/romfs` moved aside and deleted in the background. Rerun the push after a failed transfer. The Mac also accepts `DM_ROMFS=<image>` (in `~/Library/Application Support/nxnative/<title ID>/env.txt`). See [RomFS images](reference/packing.md#romfs-folder-transfers-fail-or-leave-stale-game-files) for the format, failure modes and validation limits.
1. Once per game, with an app built with image support installed: `scripts/push_romfs.sh <device UDID> <bundle ID> "<NSP folder>/<title ID>_build/xcode/Gen/resources.env"`. It validates and copies the extracted image directly to `Documents/romfs.img`. A legacy folder source is packed first; its `.inputs.json` stamp tracks source names and metadata, the packer and image identity, and `--repack` forces that legacy conversion again. The host reads file ranges through one descriptor, with `DM_ROMFS_OVERLAY` folders taking precedence. iOS startup and the host share the complete index validator: an invalid or interrupted image leaves the folder fallback intact. Only after validation is an old `Documents/romfs` moved aside and deleted in the background. Rerun the push after a failed transfer. The same script copies the game's add-on content (`aoc/`, when the build has one) to `Documents/aoc`; the app uses it before `<App>/aoc` and logs `boot: DLC from <path>`, and a `DM_AOC_DIR` in `env.txt` wins. The Mac also accepts `DM_ROMFS=<image>` (in `~/Library/Application Support/nxnative/<title ID>/env.txt`). See [RomFS images](reference/packing.md#romfs-folder-transfers-fail-or-leave-stale-game-files) for the format, failure modes and validation limits.
2. Build with `DM_COPY_ROMFS=NO` (a build setting read by `stage_resources.sh`, for example `xcodebuild ... DM_COPY_ROMFS=NO`). The shaders, add-on content and pipeline archive still go into the app.

PR #368 reports Animal Crossing's app shrinking from 11 GB to 1.2 GB, with reinstalls in 30 to 60 seconds. Deleting the app deletes its `Documents`, so push the game files again after a delete. The copy needs one `devicectl` transfer at a time.
Expand Down
7 changes: 6 additions & 1 deletion scripts/push_romfs.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/bin/bash
# Copy a game's files to its iPhone app's Documents/romfs.img once, so later installs built with DM_COPY_ROMFS=NO skip them (see docs/development.md, Quick reinstalls).
# Copy a game's files to its iPhone app's Documents/romfs.img (and its DLC to Documents/aoc, when it has any) once, so later installs built with DM_COPY_ROMFS=NO skip them (see docs/development.md, Quick reinstalls).
# The files go as one RomFS image (dm/tools/romfs_image.py), packed next to the RomFS folder on first use: one file copies at full speed, where a folder of a few hundred
# thousand files ran the phone's file service out of open files (Tears of the Kingdom: 304,000). main.m only takes a complete image, so a copy cut off halfway is never used.
# Usage: push_romfs.sh <device UDID> <bundle ID> <game>_build/xcode/Gen/resources.env [--repack]
Expand All @@ -20,4 +20,9 @@ fi
python3 -I "$(dirname "$0")/../dm/tools/romfs.py" "$img" "${DM_RESOURCE_MARKER:-}"
echo "identity: $(python3 -I "$(dirname "$0")/../dm/tools/romfs_image.py" --identity "$img")"
xcrun devicectl device copy to --device "$dev" --domain-type appDataContainer --domain-identifier "$id" --source "$img" --destination Documents/romfs.img -q
# Add-on content (DLC): the folder of <index>/ RomFS trees, small beside the game; main.m prefers Documents/aoc to <App>/aoc
if [ -n "${DM_RESOURCE_AOC:-}" ] && [ -d "$DM_RESOURCE_AOC" ]; then
xcrun devicectl device copy to --device "$dev" --domain-type appDataContainer --domain-identifier "$id" --source "$DM_RESOURCE_AOC" --destination Documents/aoc -q
echo "DLC on the phone: $id"
fi
echo "game files on the phone: $id"