Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Read a Switch 2 game folder in NXCore

v0lumehi11486001a132
diff --git a/frontend/Sources/NXCore/GameFolder.swift b/frontend/Sources/NXCore/GameFolder.swift
new file mode 100644
index 00000000..1fef7f6e
--- /dev/null
+++ b/frontend/Sources/NXCore/GameFolder.swift
@@ -0,0 +1,134 @@
+import Foundation
+
+/// A game that comes as a folder of its files instead of NSP or XCI packages (LNPANDY/NX2Apple#512, #445). Switch 2 games come
+/// this way. The engine builds such a folder with `scripts/pack_dump.py`, called by `build_ipa_from_nsp.py` when it is given the
+/// folder, and needs no `prod.keys` for it: the files are not encrypted. The layout, as pack_dump.py reads it:
+///
+/// <folder>/base/exefs/ main, main.npdm, sdk, rtld, subsdk*
+/// <folder>/base/romfs/
+/// <folder>/updates/<version>/exefs/, romfs/ optional, the version as a decimal number, the patched RomFS
+/// <folder>/dlc/<DLC title ID>/<n>/romfs/ optional, the DLC title ID in hex
+///
+/// The rules here are pack_dump.py's `is_dump` and `scan`, and build_ipa_from_nsp.py's `dump_folder`, so the launcher refuses
+/// what the script would refuse, and names the missing piece instead of "no NSP in this folder". Reads only names, and the
+/// first bytes of main.npdm: never the game's data.
+package enum GameFolder {
+ /// What a game folder holds.
+ package struct Contents: Equatable {
+ package let folder: String
+ /// The program ID in base/exefs/main.npdm, which the script takes as the title ID.
+ package let titleID: UInt64
+ /// The update folders by version, oldest first.
+ package let updates: [(version: Int, path: String)]
+ /// The DLC folders (dlc/<title ID>) with their title IDs, sorted by title ID.
+ package let dlc: [(titleID: UInt64, path: String)]
+
+ package var titleIDHex: String { String(format: "%016llX", titleID) }
+ package var basePath: String { folder + "/base" }
+ /// The script packs the newest update (the version to pack defaults to the newest in the folder).
+ package var newestUpdate: (version: Int, path: String)? { updates.last }
+
+ package static func == (a: Self, b: Self) -> Bool {
+ a.folder == b.folder && a.titleID == b.titleID
+ && a.updates.map(\.version) == b.updates.map(\.version) && a.updates.map(\.path) == b.updates.map(\.path)
+ && a.dlc.map(\.titleID) == b.dlc.map(\.titleID) && a.dlc.map(\.path) == b.dlc.map(\.path)
+ }
+ }
+
+ /// Why a folder that is meant as a game folder cannot be built.
+ package enum Problem: Error, Equatable {
+ /// `base/exefs/main.npdm`, or a RomFS (`base/romfs`, or one in `updates/<version>/`), is not there. The piece is named.
+ case missing(String)
+ /// `exefs/` and `romfs/` sit in the folder itself: they belong in a folder named `base`.
+ case noBaseFolder
+ /// main.npdm is not an NPDM, or has no ACI0 section with a program ID.
+ case unreadableNPDM
+ /// The program ID is not a base game's (its low 12 bits are not zero).
+ case notBaseTitle(UInt64)
+ /// A game package sits beside the folders: the script would build the package and ignore the folders.
+ case packageBeside(String)
+ /// A folder under dlc/ whose name is not a title ID in hex.
+ case dlcName(String)
+ /// A folder under dlc/ whose title ID is not add-on content of this game.
+ case notDLC(String, UInt64)
+ /// A DLC folder without exactly one `<n>/romfs` (or `romfs`) folder: the name and how many there were.
+ case dlcRomFS(String, Int)
+ }
+
+ /// Packages that make the script take the folder as a folder of packages. A `.nup` (a newer engine reads one) is taken first too.
+ private static let packages: Set<String> = ["nsp", "xci", "nsz", "xcz", "nup"]
+
+ /// Whether the folder is meant as a game folder: it has `base/exefs/main.npdm`, or `exefs/main.npdm` with no `base/` (the
+ /// files one level too high). Cheap: the folder picker asks this before it walks a folder that may hold 80,000 files.
+ package static func isCandidate(_ folder: String) -> Bool {
+ let fm = FileManager.default
+ if isFile(folder + "/base/exefs/main.npdm") { return true }
+ return isFile(folder + "/exefs/main.npdm") && !fm.fileExists(atPath: folder + "/base")
+ }
+
+ /// What the folder holds, or the first reason it cannot be built, in the order the script finds them.
+ package static func scan(_ folder: String) -> Result<Contents, Problem> {
+ let fm = FileManager.default
+ func isDir(_ p: String) -> Bool { var d: ObjCBool = false; return fm.fileExists(atPath: p, isDirectory: &d) && d.boolValue }
+ func dirs(_ p: String) -> [String] {
+ ((try? fm.contentsOfDirectory(atPath: p)) ?? []).filter { !$0.hasPrefix(".") && isDir(p + "/" + $0) }.sorted()
+ }
+ let top = ((try? fm.contentsOfDirectory(atPath: folder)) ?? []).sorted()
+ if let pkg = top.first(where: { !$0.hasPrefix("._") && packages.contains(($0 as NSString).pathExtension.lowercased()) && isFile(folder + "/" + $0) }) {
+ return .failure(.packageBeside(pkg))
+ }
+ let npdm = folder + "/base/exefs/main.npdm"
+ if !isFile(npdm) {
+ if isFile(folder + "/exefs/main.npdm") && !fm.fileExists(atPath: folder + "/base") { return .failure(.noBaseFolder) }
+ return .failure(.missing("base/exefs/main.npdm"))
+ }
+ let versions = isDir(folder + "/updates") ? dirs(folder + "/updates").filter { !$0.isEmpty && $0.allSatisfy(\.isASCIIDigit) } : []
+ // A newer engine takes a folder whose base has no RomFS when an update has one (pack_dump.py at seedds/nxnative 641d148).
+ guard isDir(folder + "/base/romfs") || versions.contains(where: { isDir(folder + "/updates/" + $0 + "/romfs") }) else {
+ return .failure(.missing("base/romfs"))
+ }
+ guard let data = fm.contents(atPath: npdm), let app = programID(npdm: data) else { return .failure(.unreadableNPDM) }
+ if app & 0xFFF != 0 { return .failure(.notBaseTitle(app)) }
+ let updates = versions.compactMap { v in Int(v).map { (version: $0, path: folder + "/updates/" + v) } }.sorted { $0.version < $1.version }
+ var dlc: [(titleID: UInt64, path: String)] = []
+ for name in isDir(folder + "/dlc") ? dirs(folder + "/dlc") : [] {
+ let path = folder + "/dlc/" + name
+ guard name.count <= 16, let tid = UInt64(name, radix: 16) else { return .failure(.dlcName(name)) }
+ guard tid > app + 0x1000, tid - app - 0x1000 <= 2000 else { return .failure(.notDLC(name, tid)) }
+ let numbered = dirs(path).filter { isDir(path + "/" + $0 + "/romfs") }
+ let count = numbered.isEmpty ? (isDir(path + "/romfs") ? 1 : 0) : numbered.count
+ guard count == 1 else { return .failure(.dlcRomFS(name, count)) }
+ dlc.append((titleID: tid, path: path))
+ }
+ return .success(Contents(folder: folder, titleID: app, updates: updates, dlc: dlc.sorted { $0.titleID < $1.titleID }))
+ }
+
+ /// The ACI0 program ID of an NPDM (pack_dump.py `program_id`): the ACI0 offset and size at 0x70, the ID at ACI0 + 0x10.
+ package static func programID(npdm d: Data) -> UInt64? {
+ let b = [UInt8](d)
+ func u32(_ o: Int) -> Int? { o + 4 <= b.count ? Int(b[o]) | Int(b[o + 1]) << 8 | Int(b[o + 2]) << 16 | Int(b[o + 3]) << 24 : nil }
+ guard b.count >= 0x78, b[0..<4].elementsEqual("META".utf8), let off = u32(0x70), let size = u32(0x74),
+ size >= 0x18, off + 0x18 <= b.count, b[off..<off + 4].elementsEqual("ACI0".utf8) else { return nil }
+ return (0..<8).reduce(UInt64(0)) { $0 | UInt64(b[off + 0x10 + $1]) << (8 * UInt64($1)) }
+ }
+
+ /// Whether the engine builds game folders: it has `scripts/pack_dump.py` (seedds/nxnative 99947471, in the pin since v1.0.1).
+ package static func engineBuildsFolders(_ engineRoot: String) -> Bool {
+ !engineRoot.isEmpty && FileManager.default.fileExists(atPath: engineRoot + "/scripts/pack_dump.py")
+ }
+
+ /// Whether the engine has a profile for the game. The script packs a game folder only for a game with a profile: the survey
+ /// that makes a provisional one reads NSPs.
+ package static func engineHasProfile(_ titleID: UInt64, engineRoot: String) -> Bool {
+ !engineRoot.isEmpty && FileManager.default.fileExists(atPath: engineRoot + "/dm/games/" + String(format: "%016llX", titleID) + "/game.tsv")
+ }
+
+ private static func isFile(_ path: String) -> Bool {
+ var d: ObjCBool = false
+ return FileManager.default.fileExists(atPath: path, isDirectory: &d) && !d.boolValue
+ }
+}
+
+private extension Character {
+ var isASCIIDigit: Bool { ("0"..."9").contains(self) }
+}
diff --git a/frontend/Tests/NXCoreTests/GameFolderTests.swift b/frontend/Tests/NXCoreTests/GameFolderTests.swift
new file mode 100644
index 00000000..e3de64b8
--- /dev/null
+++ b/frontend/Tests/NXCoreTests/GameFolderTests.swift
@@ -0,0 +1,136 @@
+import XCTest
+@testable import NXCore
+
+/// LNPANDY/NX2Apple#512 and #445: a Switch 2 game comes as a folder of its files (pack_dump.py's layout). The rules are the
+/// script's, checked here on synthetic folders: an NPDM with only a program ID, empty RomFS folders, no game data.
+final class GameFolderTests: XCTestCase {
+ private var root = ""
+
+ override func setUpWithError() throws {
+ root = NSTemporaryDirectory() + "gamefolder-" + UUID().uuidString
+ try FileManager.default.createDirectory(atPath: root, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws { try? FileManager.default.removeItem(atPath: root) }
+
+ /// A minimal main.npdm: "META", the ACI0 offset and size at 0x70, "ACI0" with the program ID at +0x10.
+ static func npdm(programID: UInt64) -> Data {
+ var d = [UInt8](repeating: 0, count: 0x100)
+ d.replaceSubrange(0..<4, with: Array("META".utf8))
+ let off = 0x80, size = 0x40
+ for i in 0..<4 { d[0x70 + i] = UInt8(off >> (8 * i) & 0xFF); d[0x74 + i] = UInt8(size >> (8 * i) & 0xFF) }
+ d.replaceSubrange(off..<off + 4, with: Array("ACI0".utf8))
+ for i in 0..<8 { d[off + 0x10 + i] = UInt8(programID >> (8 * UInt64(i)) & 0xFF) }
+ return Data(d)
+ }
+
+ private func mkdir(_ rel: String) { try? FileManager.default.createDirectory(atPath: root + "/" + rel, withIntermediateDirectories: true) }
+ private func write(_ rel: String, _ data: Data = Data([1])) {
+ mkdir((rel as NSString).deletingLastPathComponent)
+ FileManager.default.createFile(atPath: root + "/" + rel, contents: data)
+ }
+
+ /// Donkey Kong Bananza's layout (#512): base, one update, one DLC.
+ private func makeGame(_ app: UInt64 = 0x040074A01BF12000) {
+ write("base/exefs/main.npdm", Self.npdm(programID: app)); write("base/exefs/main"); mkdir("base/romfs")
+ write("updates/458752/exefs/main.npdm", Self.npdm(programID: app)); mkdir("updates/458752/romfs")
+ mkdir("dlc/040074a01bf13001/0/romfs")
+ }
+
+ func testTheLayoutOfTheScriptIsReadWithItsTitleIDUpdatesAndDLC() throws {
+ makeGame()
+ mkdir("updates/65536/romfs")
+ XCTAssertTrue(GameFolder.isCandidate(root))
+ let c = try GameFolder.scan(root).get()
+ XCTAssertEqual(c.titleIDHex, "040074A01BF12000")
+ XCTAssertEqual(c.updates.map(\.version), [65536, 458752])
+ XCTAssertEqual(c.newestUpdate?.path, root + "/updates/458752")
+ XCTAssertEqual(c.dlc.map(\.titleID), [0x040074A01BF13001])
+ XCTAssertEqual(c.dlc.first?.path, root + "/dlc/040074a01bf13001")
+ XCTAssertEqual(c.basePath, root + "/base")
+ }
+
+ func testAFolderOfPackagesIsNoCandidate() {
+ write("Game [010015100B514000][v0].nsp")
+ XCTAssertFalse(GameFolder.isCandidate(root))
+ }
+
+ func testTheMissingPieceIsNamed() {
+ write("base/exefs/main.npdm", Self.npdm(programID: 0x040074A01BF12000))
+ XCTAssertEqual(GameFolder.scan(root).failureValue, .missing("base/romfs"))
+ try? FileManager.default.removeItem(atPath: root + "/base/exefs/main.npdm")
+ mkdir("base/romfs")
+ XCTAssertEqual(GameFolder.scan(root).failureValue, .missing("base/exefs/main.npdm"))
+ }
+
+ /// pack_dump.py at seedds/nxnative 641d148 takes a base without a RomFS when an update has its whole RomFS (Pokémon Pokopia).
+ func testAnUpdateRomFSStandsInForTheBaseOne() throws {
+ write("base/exefs/main.npdm", Self.npdm(programID: 0x0400A3A01EE4C000))
+ mkdir("updates/655360/romfs")
+ XCTAssertEqual(try GameFolder.scan(root).get().updates.map(\.version), [655360])
+ }
+
+ func testFilesOneLevelTooHighAskForABaseFolder() {
+ write("exefs/main.npdm", Self.npdm(programID: 0x04007EF01F8AE000)); mkdir("romfs")
+ XCTAssertTrue(GameFolder.isCandidate(root))
+ XCTAssertEqual(GameFolder.scan(root).failureValue, .noBaseFolder)
+ }
+
+ /// build_ipa_from_nsp.py `dump_folder`: a package beside the folders is what the script builds, so the launcher refuses the mix.
+ func testAPackageBesideTheFoldersIsNamed() {
+ makeGame()
+ write("Bananza.nsp")
+ write("._Other.nsp") // an AppleDouble file does not count
+ XCTAssertEqual(GameFolder.scan(root).failureValue, .packageBeside("Bananza.nsp"))
+ }
+
+ func testAnNPDMWithoutAProgramIDIsRefused() {
+ write("base/exefs/main.npdm", Data("not an npdm".utf8)); mkdir("base/romfs")
+ XCTAssertEqual(GameFolder.scan(root).failureValue, .unreadableNPDM)
+ XCTAssertNil(GameFolder.programID(npdm: Data()))
+ }
+
+ func testAnUpdateProgramIDIsNoBase() {
+ write("base/exefs/main.npdm", Self.npdm(programID: 0x040074A01BF12800)); mkdir("base/romfs")
+ XCTAssertEqual(GameFolder.scan(root).failureValue, .notBaseTitle(0x040074A01BF12800))
+ }
+
+ /// pack_dump.py `scan`: a DLC title ID in hex, above the base by 0x1001 to 0x1000 + 2000, one <n>/romfs folder.
+ func testDLCFoldersFollowTheScriptsRules() {
+ makeGame()
+ mkdir("dlc/extra/0/romfs")
+ XCTAssertEqual(GameFolder.scan(root).failureValue, .dlcName("extra"))
+ try? FileManager.default.removeItem(atPath: root + "/dlc/extra")
+ mkdir("dlc/010015100B515001/0/romfs")
+ XCTAssertEqual(GameFolder.scan(root).failureValue, .notDLC("010015100B515001", 0x010015100B515001))
+ try? FileManager.default.removeItem(atPath: root + "/dlc/010015100B515001")
+ mkdir("dlc/040074a01bf13002/0/romfs"); mkdir("dlc/040074a01bf13002/1/romfs")
+ XCTAssertEqual(GameFolder.scan(root).failureValue, .dlcRomFS("040074a01bf13002", 2))
+ try? FileManager.default.removeItem(atPath: root + "/dlc/040074a01bf13002/1")
+ XCTAssertEqual((try? GameFolder.scan(root).get())?.dlc.count, 2)
+ // a romfs folder straight in dlc/<title ID> is taken too
+ mkdir("dlc/040074A01BF13003/romfs")
+ XCTAssertEqual((try? GameFolder.scan(root).get())?.dlc.map(\.titleID), [0x040074A01BF13001, 0x040074A01BF13002, 0x040074A01BF13003])
+ }
+
+ func testUpdateFoldersWithoutADecimalNameAreLeftOut() throws {
+ makeGame()
+ mkdir("updates/latest/romfs")
+ XCTAssertEqual(try GameFolder.scan(root).get().updates.map(\.version), [458752])
+ }
+
+ func testTheEngineChecksLookForThePackerAndTheProfile() {
+ let engine = root + "/engine"
+ XCTAssertFalse(GameFolder.engineBuildsFolders(engine))
+ XCTAssertFalse(GameFolder.engineBuildsFolders(""))
+ write("engine/scripts/pack_dump.py")
+ XCTAssertTrue(GameFolder.engineBuildsFolders(engine))
+ XCTAssertFalse(GameFolder.engineHasProfile(0x040074A01BF12000, engineRoot: engine))
+ write("engine/dm/games/040074A01BF12000/game.tsv")
+ XCTAssertTrue(GameFolder.engineHasProfile(0x040074A01BF12000, engineRoot: engine))
+ }
+}
+
+extension Result {
+ var failureValue: Failure? { if case .failure(let e) = self { return e }; return nil }
+}