Skip to content

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

launcher: read RomFS image directories as type 0 and guard header arithmetic (#668)

v0lumehic5572033ef61
diff --git a/frontend-ios/Sources/ShellHost/RomfsLanguages.swift b/frontend-ios/Sources/ShellHost/RomfsLanguages.swift
index 60dcbc1a..99334244 100644
--- a/frontend-ios/Sources/ShellHost/RomfsLanguages.swift
+++ b/frontend-ios/Sources/ShellHost/RomfsLanguages.swift
@@ -112,7 +112,7 @@ enum RomfsLanguages {
guard head[0..<8].elementsEqual("DMROMFS1".utf8) else { return [] }
let idxOff = u64(head, 8), idxSize = u64(head, 16), count = u64(head, 24)
guard idxOff >= 32, idxOff <= fileSize, idxSize == fileSize - idxOff,
- idxSize <= 64 * 1024 * 1024, count >= 1, count * 24 <= idxSize,
+ idxSize <= 64 * 1024 * 1024, count >= 1, count <= idxSize / 24,
(try? handle.seek(toOffset: idxOff)) != nil,
let idxData = try? handle.read(upToCount: Int(idxSize)), idxData.count == Int(idxSize) else { return [] }
let idx = [UInt8](idxData)
@@ -133,7 +133,7 @@ enum RomfsLanguages {
return Entry(a: u64(idx, o), b: u64(idx, o + 8), name: name, type: idx[o + 22])
}
func children(of dirIndex: Int) -> [Int] {
- guard let dir = entry(dirIndex), dir.type == 2,
+ guard let dir = entry(dirIndex), dir.type == 0, // the writer (romfs_image.py) stores a directory as type 0 and a file as type 1
dir.a <= count, dir.b <= count - dir.a else { return [] }
return Array(Int(dir.a)..<Int(dir.a + dir.b))
}
@@ -144,7 +144,7 @@ enum RomfsLanguages {
if let sys = findChild(in: 0, named: "System"),
let maskIdx = findChild(in: sys, named: "RegionLangMask.txt"),
let mask = entry(maskIdx), mask.type == 1, mask.b > 0, mask.b <= 65536,
- mask.a + mask.b <= idxOff,
+ mask.a >= 32, mask.b <= idxOff, mask.a <= idxOff - mask.b,
(try? handle.seek(toOffset: mask.a)) != nil,
let maskData = try? handle.read(upToCount: Int(mask.b)),
let text = String(data: maskData, encoding: .utf8) {
diff --git a/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift b/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift
new file mode 100644
index 00000000..e6d3cd21
--- /dev/null
+++ b/frontend-ios/Tests/ShellHostTests/RomfsLanguagesTests.swift
@@ -0,0 +1,113 @@
+import Foundation
+import Testing
+@testable import ShellHost
+
+/// `RomfsLanguages` reads the `DMROMFS1` index a game's `romfs.img` ends with (LNPANDY/NX2Apple#668).
+@Suite struct RomfsLanguagesTests {
+ /// A node of a RomFS tree: a directory (children) or a file (bytes).
+ private indirect enum Node {
+ case dir([String: Node])
+ case file([UInt8])
+ }
+
+ /// Packs `root` the way `dm/tools/romfs_image.py` does: a 32-byte header, the file data, then 24-byte entries and one name pool.
+ /// Entry 0 is the root, children are consecutive and sorted by name bytes, directories are numbered breadth-first,
+ /// a directory has type 0 and a file type 1.
+ private static func image(_ root: Node) -> Data {
+ struct Item { var name: [UInt8]; var node: Node; var a: UInt64 = 0; var b: UInt64 = 0 }
+ var items = [Item(name: [], node: root)]
+ var i = 0
+ while i < items.count {
+ if case .dir(let kids) = items[i].node {
+ let sorted = kids.map { (Array($0.key.utf8), $0.value) }.sorted { $0.0.lexicographicallyPrecedes($1.0) }
+ items[i].a = UInt64(items.count)
+ items[i].b = UInt64(sorted.count)
+ items.append(contentsOf: sorted.map { Item(name: $0.0, node: $0.1) })
+ }
+ i += 1
+ }
+ var data = [UInt8](), offset: UInt64 = 32
+ for k in items.indices {
+ if case .file(let bytes) = items[k].node {
+ items[k].a = offset
+ items[k].b = UInt64(bytes.count)
+ offset += UInt64(bytes.count)
+ data += bytes
+ }
+ }
+ func le(_ v: UInt64, _ n: Int) -> [UInt8] { (0..<n).map { UInt8((v >> (8 * UInt64($0))) & 0xff) } }
+ var idx = [UInt8](), pool = [UInt8]()
+ for item in items {
+ let isDir: Bool
+ if case .dir = item.node { isDir = true } else { isDir = false }
+ idx += le(item.a, 8) + le(item.b, 8) + le(UInt64(pool.count), 4) + le(UInt64(item.name.count), 2) + [isDir ? 0 : 1, 0]
+ pool += item.name
+ }
+ let head = [UInt8]("DMROMFS1".utf8) + le(offset, 8) + le(UInt64(idx.count + pool.count), 8) + le(UInt64(items.count), 8)
+ return Data(head + data + idx + pool)
+ }
+
+ private func folder(with img: Data) throws -> URL {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("romfs-lang-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ try img.write(to: dir.appendingPathComponent("romfs.img"))
+ return dir
+ }
+
+ private func codes(_ img: Data) throws -> [String] {
+ RomfsLanguages.options(in: try folder(with: img)).map { $0[0] }
+ }
+
+ private func mask(_ text: String) -> Node {
+ .dir(["System": .dir(["RegionLangMask.txt": .file(Array(text.utf8))]), "Other": .file([1, 2, 3])])
+ }
+
+ @Test func aRealLayoutImageGivesTheMaskLanguages() throws {
+ #expect(try codes(Self.image(mask("JPja USen CNzh TWzh EUfr\n01111\n"))) == ["en-US", "ja", "fr", "zh-Hant", "zh-Hans"])
+ }
+
+ @Test func theMalsFolderIsUsedWhenThereIsNoMask() throws {
+ let tree = Node.dir(["Mals": .dir(["USen.Product.100.sarc.zs": .file([0]), "JPja.Product.100.sarc.zs": .file([0]),
+ "Readme.txt": .file([0])])])
+ #expect(try codes(Self.image(tree)) == ["en-US", "ja"])
+ }
+
+ @Test func aSingleLanguageGivesNoRow() throws {
+ #expect(try codes(Self.image(mask("USen\n"))) == [])
+ }
+
+ @Test func unknownTagsAreIgnored() throws {
+ #expect(try codes(Self.image(mask("ZZxx QQqq USen\n"))) == [])
+ #expect(try codes(Self.image(mask("ZZxx USen JPja\n"))) == ["en-US", "ja"])
+ }
+
+ @Test func aBadMagicGivesNoRow() throws {
+ var img = Self.image(mask("USen JPja\n"))
+ img[0] = UInt8(ascii: "X")
+ #expect(try codes(img) == [])
+ }
+
+ @Test func aTruncatedFileGivesNoRow() throws {
+ let img = Self.image(mask("USen JPja\n"))
+ #expect(try codes(img.prefix(img.count - 10)) == [])
+ #expect(try codes(img.prefix(20)) == [])
+ #expect(try codes(Data()) == [])
+ }
+
+ @Test func aCraftedHeaderDoesNotTrap() throws {
+ func patched(_ offset: Int, _ value: UInt64, in base: Data? = nil) -> Data {
+ var d = base ?? Self.image(mask("USen JPja\n"))
+ for i in 0..<8 { d[offset + i] = UInt8((value >> (8 * UInt64(i))) & 0xff) }
+ return d
+ }
+ #expect(try codes(patched(24, .max)) == [], "a huge entry count must not overflow count * 24")
+ #expect(try codes(patched(24, UInt64.max / 24 + 1)) == [])
+ #expect(try codes(patched(8, .max)) == [])
+ #expect(try codes(patched(16, .max)) == [])
+ let img = Self.image(mask("USen JPja\n"))
+ let idxOff = Int(img[8]) | Int(img[9]) << 8
+ // Entries sorted by name: Other is entry 1 and System entry 2, whose child RegionLangMask.txt is entry 3.
+ #expect(try codes(patched(idxOff + 3 * 24, .max, in: img)) == [], "a mask offset near UInt64.max must not overflow offset + size")
+ #expect(try codes(patched(idxOff + 3 * 24 + 8, .max, in: img)) == [])
+ }
+}
diff --git a/frontend/Sources/NXCore/RomFSLanguages.swift b/frontend/Sources/NXCore/RomFSLanguages.swift
index 9e513416..412f8259 100644
--- a/frontend/Sources/NXCore/RomFSLanguages.swift
+++ b/frontend/Sources/NXCore/RomFSLanguages.swift
@@ -156,7 +156,7 @@ package enum RomFSLanguages {
guard head[0..<8].elementsEqual("DMROMFS1".utf8) else { return [] }
let idxOff = u64(head, 8), idxSize = u64(head, 16), count = u64(head, 24)
guard idxOff >= 32, idxOff <= fileSize, idxSize == fileSize - idxOff,
- idxSize <= 64 * 1024 * 1024, count >= 1, count * 24 <= idxSize,
+ idxSize <= 64 * 1024 * 1024, count >= 1, count <= idxSize / 24,
(try? handle.seek(toOffset: idxOff)) != nil,
let idxData = try? handle.read(upToCount: Int(idxSize)), idxData.count == Int(idxSize) else { return [] }
let idx = [UInt8](idxData)
@@ -177,7 +177,7 @@ package enum RomFSLanguages {
return Entry(a: u64(idx, o), b: u64(idx, o + 8), name: name, type: idx[o + 22])
}
func children(of dirIndex: Int) -> [Int] {
- guard let dir = entry(dirIndex), dir.type == 2,
+ guard let dir = entry(dirIndex), dir.type == 0, // the writer (romfs_image.py) stores a directory as type 0 and a file as type 1
dir.a <= count, dir.b <= count - dir.a else { return [] }
return Array(Int(dir.a)..<Int(dir.a + dir.b))
}
@@ -188,7 +188,7 @@ package enum RomFSLanguages {
if let sys = findChild(in: 0, named: "System"),
let maskIdx = findChild(in: sys, named: "RegionLangMask.txt"),
let mask = entry(maskIdx), mask.type == 1, mask.b > 0, mask.b <= 65536,
- mask.a + mask.b <= idxOff,
+ mask.a >= 32, mask.b <= idxOff, mask.a <= idxOff - mask.b,
(try? handle.seek(toOffset: mask.a)) != nil,
let maskData = try? handle.read(upToCount: Int(mask.b)),
let text = String(data: maskData, encoding: .utf8) {
diff --git a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
index 705df641..66d88db1 100644
--- a/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
+++ b/frontend/Tests/NX2AppleTests/MacAppLanguageTests.swift
@@ -134,12 +134,55 @@ final class MacAppLanguageTests: IsolatedDefaultsTestCase {
XCTAssertEqual(parsed.settings.first { $0.env == "DM_LANG" }?.options?.map { $0[0] }, ["en-US", "ja", "fr", "zh-Hant", "zh-Hans"])
}
- /// Minimal DMROMFS1 image with `/System/RegionLangMask.txt` containing `mask`.
+ private func writeImage(_ data: Data) throws -> String {
+ let url = temporary.appendingPathComponent("img-\(UUID().uuidString).img")
+ try data.write(to: url)
+ return url.path
+ }
+
+ func testRomFSImageWithFewerThanTwoKnownLanguagesGivesNoRow() throws {
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(Self.makeDMROMFSImage(mask: "USen\n"))), [])
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(Self.makeDMROMFSImage(mask: "USen ZZxx QQqq\n"))), [])
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(Self.makeDMROMFSImage(mask: "USen JPja\n"))).map { $0[0] }, ["en-US", "ja"])
+ }
+
+ func testRomFSImageWithBadMagicOrCutOffGivesNoRow() throws {
+ var bad = Self.makeDMROMFSImage(mask: "USen JPja\n")
+ bad[0] = UInt8(ascii: "X")
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(bad)), [])
+ let good = Self.makeDMROMFSImage(mask: "USen JPja\n")
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(good.prefix(good.count - 10))), [], "the index must end at the end of the file")
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(good.prefix(20))), [])
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(Data())), [])
+ }
+
+ func testRomFSImageWithCraftedHeaderDoesNotTrap() throws {
+ func patched(at offset: Int, _ value: UInt64) -> Data {
+ var d = Self.makeDMROMFSImage(mask: "USen JPja\n")
+ for i in 0..<8 { d[offset + i] = UInt8((value >> (8 * UInt64(i))) & 0xff) }
+ return d
+ }
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(patched(at: 24, UInt64.max))), [], "a huge entry count must not overflow count * 24")
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(patched(at: 24, UInt64.max / 24 + 1))), [])
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(patched(at: 8, UInt64.max))), [])
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(patched(at: 16, UInt64.max))), [])
+ // The mask file's size field is the second u64 of entry 2, which starts 48 bytes into the index.
+ var d = Self.makeDMROMFSImage(mask: "USen JPja\n")
+ let idxOff = Int(d[8]) | Int(d[9]) << 8
+ for i in 0..<8 { d[idxOff + 48 + 8 + i] = i == 7 ? 0x7f : 0xff }
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(d)), [])
+ // A mask offset near UInt64.max must not overflow offset + size.
+ var e = Self.makeDMROMFSImage(mask: "USen JPja\n")
+ for i in 0..<8 { e[idxOff + 48 + i] = 0xff }
+ XCTAssertEqual(RomFSLanguages.options(in: try writeImage(e)), [])
+ }
+
+ /// DMROMFS1 image with `/System/RegionLangMask.txt` containing `mask`, laid out as `dm/tools/romfs_image.py` writes it
+ /// (header, data, then 24-byte entries and one name pool, breadth-first, a directory is type 0 and a file is type 1).
private static func makeDMROMFSImage(mask: String) -> Data {
let payload = [UInt8](mask.utf8)
let dataOff: UInt64 = 32
- let paddedLen = (payload.count + 7) & ~7
- let idxOff = dataOff + UInt64(paddedLen)
+ let idxOff = dataOff + UInt64(payload.count)
let names = [UInt8]("SystemRegionLangMask.txt".utf8)
func le64(_ v: UInt64) -> [UInt8] { (0..<8).map { UInt8((v >> (8 * UInt64($0))) & 0xff) } }
func le32(_ v: UInt32) -> [UInt8] { (0..<4).map { UInt8((v >> (8 * UInt32($0))) & 0xff) } }
@@ -147,12 +190,12 @@ final class MacAppLanguageTests: IsolatedDefaultsTestCase {
func entry(_ a: UInt64, _ b: UInt64, _ nOff: UInt32, _ nLen: UInt16, _ type: UInt8) -> [UInt8] {
le64(a) + le64(b) + le32(nOff) + le16(nLen) + [type, 0]
}
- let entries = entry(1, 1, 0, 0, 2)
- + entry(2, 1, 0, 6, 2)
+ let entries = entry(1, 1, 0, 0, 0)
+ + entry(2, 1, 0, 6, 0)
+ entry(dataOff, UInt64(payload.count), 6, 18, 1)
let idx = entries + names
let head = [UInt8]("DMROMFS1".utf8) + le64(idxOff) + le64(UInt64(idx.count)) + le64(3)
- return Data(head + payload + [UInt8](repeating: 0, count: paddedLen - payload.count) + idx)
+ return Data(head + payload + idx)
}
/// settings.py output, as described above.