diff --git a/Sources/KMPBuildSupport/GradleFrameworkProducer.swift b/Sources/KMPBuildSupport/GradleFrameworkProducer.swift index f086ac4a..7c392231 100644 --- a/Sources/KMPBuildSupport/GradleFrameworkProducer.swift +++ b/Sources/KMPBuildSupport/GradleFrameworkProducer.swift @@ -70,14 +70,22 @@ public struct GradleFrameworkProducer: Sendable { destination: AppleBuildDestination, workingDirectory: URL ) throws -> StagedFramework { - guard let rawPath = config.frameworkPath, !rawPath.isEmpty else { - throw StringError("Prebuilt framework '\(config.name)' requires frameworkPath.") + let frameworkURL: URL + if let path = config.xcframeworkPath { + frameworkURL = try XCFrameworkSlice.resolve( + in: resolvePath(path, relativeTo: workingDirectory), + name: config.name, + destination: destination + ) + } else if let path = config.frameworkPath, !path.isEmpty { + frameworkURL = resolvePath(path, relativeTo: workingDirectory) + } else { + throw StringError("Missing prebuilt framework path for '\(config.name)'.") } - let frameworkURL = resolvePath(rawPath, relativeTo: workingDirectory) let detected = try verifyMaterializedFramework( at: frameworkURL, name: config.name, - architecture: destination.architecture, + destination: destination, expected: config.linkage ) let resourcesURL = try validateComposeResources(config.composeResourcesPath, relativeTo: workingDirectory) @@ -154,7 +162,7 @@ public struct GradleFrameworkProducer: Sendable { let detected = try verifyMaterializedFramework( at: frameworkURL, name: config.name, - architecture: destination.architecture, + destination: destination, expected: config.linkage ) let resourcesURL = try validateComposeResources(config.composeResourcesPath, relativeTo: projectRoot) @@ -170,7 +178,7 @@ public struct GradleFrameworkProducer: Sendable { private func verifyMaterializedFramework( at frameworkURL: URL, name: String, - architecture: String, + destination: AppleBuildDestination, expected: PackSchemaBase.FrameworkLinkageMode? ) throws -> DetectedFrameworkLinkage { let fm = FileManager.default @@ -183,7 +191,8 @@ public struct GradleFrameworkProducer: Sendable { let detected = try BundleAssembler.detectFrameworkLinkage( at: frameworkURL, name: name, - architecture: architecture + architecture: destination.architecture, + expectedIsSimulator: destination.isSimulator ) if let expected { switch (expected, detected) { diff --git a/Sources/KMPBuildSupport/XCFrameworkSlice.swift b/Sources/KMPBuildSupport/XCFrameworkSlice.swift new file mode 100644 index 00000000..5a3a1a8a --- /dev/null +++ b/Sources/KMPBuildSupport/XCFrameworkSlice.swift @@ -0,0 +1,52 @@ +import Foundation +import PackLib +import XUtils + +struct XCFrameworkSlice: Decodable { + let libraryIdentifier: String + let libraryPath: String + let supportedArchitectures: [String] + let supportedPlatform: String + let supportedPlatformVariant: String? + + private enum CodingKeys: String, CodingKey { + case libraryIdentifier = "LibraryIdentifier" + case libraryPath = "LibraryPath" + case supportedArchitectures = "SupportedArchitectures" + case supportedPlatform = "SupportedPlatform" + case supportedPlatformVariant = "SupportedPlatformVariant" + } + + private struct Manifest: Decodable { + let libraries: [XCFrameworkSlice] + + enum CodingKeys: String, CodingKey { + case libraries = "AvailableLibraries" + } + } + + static func resolve(in container: URL, name: String, destination: AppleBuildDestination) throws -> URL { + let root = container.resolvingSymlinksInPath().standardizedFileURL + let plist = root.appendingPathComponent("Info.plist") + try ResourceOutput.requireFile(plist) + let manifest = try PropertyListDecoder().decode(Manifest.self, from: Data(contentsOf: plist)) + let variant: String? = destination.isSimulator ? "simulator" : nil + let matches = manifest.libraries.filter { + $0.supportedPlatform == "ios" && $0.supportedPlatformVariant == variant + && $0.supportedArchitectures.contains(destination.architecture) + } + guard matches.count == 1, let slice = matches.first else { + throw StringError("\(container.path): expected one slice for \(destination.clangTriple), found \(matches.count).") + } + let identifier = slice.libraryIdentifier + guard !["", ".", ".."].contains(identifier), !identifier.contains("/"), !identifier.contains("\\"), + slice.libraryPath == "\(name).framework" else { + throw StringError("Invalid framework layout in \(container.path) for \(name).") + } + let directory = root.appendingPathComponent(identifier) + try ResourceOutput.requireDirectory(directory) + let framework = directory.appendingPathComponent(slice.libraryPath) + try ResourceOutput.requireDirectory(framework) + return framework + } +} diff --git a/Sources/PackLib/BundleAssembler.swift b/Sources/PackLib/BundleAssembler.swift index 1e0a44da..a68b1de4 100644 --- a/Sources/PackLib/BundleAssembler.swift +++ b/Sources/PackLib/BundleAssembler.swift @@ -111,6 +111,8 @@ public struct BundleAssembler: Sendable { public let hostInfoPlistURL: URL? public let hostSourcePaths: [String] public let frameworks: [StagedFramework] + public let assetInfoURL: URL? + public let assetInfoData: Data? public let resources: [BundleResourceCopy] public let marketingVersion: String public let buildVersion: String @@ -126,6 +128,8 @@ public struct BundleAssembler: Sendable { hostSourcePaths: [String] = [], frameworks: [StagedFramework] = [], resources: [BundleResourceCopy] = [], + assetInfoURL: URL? = nil, + assetInfoData: Data? = nil, marketingVersion: String = "1.0.0", buildVersion: String = "1", outputParentDir: URL @@ -138,6 +142,8 @@ public struct BundleAssembler: Sendable { self.hostInfoPlistURL = hostInfoPlistURL self.hostSourcePaths = hostSourcePaths self.frameworks = frameworks + self.assetInfoURL = assetInfoURL + self.assetInfoData = assetInfoData self.resources = resources self.marketingVersion = marketingVersion self.buildVersion = buildVersion @@ -152,7 +158,8 @@ public struct BundleAssembler: Sendable { public static func detectFrameworkLinkage( at frameworkURL: URL, name: String, - architecture: String = "arm64" + architecture: String = "arm64", + expectedIsSimulator: Bool? = nil ) throws -> DetectedFrameworkLinkage { let binaryURL = frameworkURL.appendingPathComponent(name) guard FileManager.default.fileExists(atPath: binaryURL.path) else { @@ -180,7 +187,18 @@ public struct BundleAssembler: Sendable { guard let sliceHeader = try handle.read(upToCount: readLen), sliceHeader.count == readLen else { throw StringError("Framework binary '\(binaryURL.path)' has a truncated slice header.") } - return try classifySliceHeader(sliceHeader, path: binaryURL.path) + let linkage = try classifySliceHeader(sliceHeader, architecture: architecture, path: binaryURL.path) + if linkage == .dynamic, let expectedIsSimulator { + try validateMachOPlatform( + sliceHeader: sliceHeader, + handle: handle, + sliceOffset: sliceOffset, + sliceSize: sliceSize, + expectedIsSimulator: expectedIsSimulator, + path: binaryURL.path + ) + } + return linkage } private static func resolveFatSliceBoundsIfNeeded( @@ -228,7 +246,11 @@ public struct BundleAssembler: Sendable { throw StringError("Universal framework binary '\(path)' does not contain a '\(architecture)' slice.") } - private static func classifySliceHeader(_ sliceHeader: Data, path: String) throws -> DetectedFrameworkLinkage { + private static func classifySliceHeader( + _ sliceHeader: Data, + architecture: String, + path: String + ) throws -> DetectedFrameworkLinkage { let archiveMagic = Data("!\n".utf8) let thinMagic = Data("!\n".utf8) if sliceHeader.starts(with: archiveMagic) || sliceHeader.starts(with: thinMagic) { @@ -238,22 +260,73 @@ public struct BundleAssembler: Sendable { throw StringError("Framework Mach-O binary '\(path)' is shorter than a 64-bit Mach-O header.") } let magicBE = readUInt32BE(sliceHeader, at: 0) - let mhDylib: UInt32 = 6 - let fileType: UInt32 - if magicBE == 0xCFFAEDFE { - // 64-bit little-endian Mach-O: filetype is at byte offset 12 (little-endian). - fileType = readUInt32LE(sliceHeader, at: 12) - } else if magicBE == 0xFEEDFACF { - fileType = readUInt32BE(sliceHeader, at: 12) - } else { + let isLE = magicBE == 0xCFFAEDFE + guard isLE || magicBE == 0xFEEDFACF else { throw StringError("Framework binary '\(path)' has unrecognized binary magic.") } + let wantCPU: UInt32 = architecture == "x86_64" ? 0x01000007 : 0x0100000C + let cpuType = isLE ? readUInt32LE(sliceHeader, at: 4) : readUInt32BE(sliceHeader, at: 4) + guard cpuType == wantCPU else { + throw StringError("Framework Mach-O binary '\(path)' has cputype \(cpuType), expected '\(architecture)'.") + } + let mhDylib: UInt32 = 6 + let fileType = isLE ? readUInt32LE(sliceHeader, at: 12) : readUInt32BE(sliceHeader, at: 12) guard fileType == mhDylib else { throw StringError("Framework Mach-O binary '\(path)' has filetype \(fileType), expected MH_DYLIB (\(mhDylib)).") } return .dynamic } + private static func validateMachOPlatform( + sliceHeader: Data, + handle: FileHandle, + sliceOffset: UInt64, + sliceSize: UInt64, + expectedIsSimulator: Bool, + path: String + ) throws { + let isLE = readUInt32BE(sliceHeader, at: 0) == 0xCFFAEDFE + let ncmds = isLE ? readUInt32LE(sliceHeader, at: 16) : readUInt32BE(sliceHeader, at: 16) + let sizeofcmds = UInt64(isLE ? readUInt32LE(sliceHeader, at: 20) : readUInt32BE(sliceHeader, at: 20)) + guard sizeofcmds <= 4 * 1024 * 1024, 32 + sizeofcmds <= sliceSize else { + throw StringError("Framework Mach-O binary '\(path)' has invalid load command bounds.") + } + try handle.seek(toOffset: sliceOffset + 32) + guard let cmdData = try handle.read(upToCount: Int(sizeofcmds)), cmdData.count == Int(sizeofcmds) else { + throw StringError("Framework Mach-O binary '\(path)' has truncated load commands.") + } + let wantPlatform: UInt32 = expectedIsSimulator ? 7 : 2 + var offset = 0 + for _ in 0..= 8 && offset + cmdSize <= cmdData.count else { + throw StringError("Framework Mach-O binary '\(path)' has malformed load command size.") + } + if cmd == 0x32 && cmdSize >= 12 { + let platform = isLE ? readUInt32LE(cmdData, at: offset + 8) : readUInt32BE(cmdData, at: offset + 8) + guard platform == wantPlatform else { + throw StringError("Framework Mach-O binary '\(path)' targets platform \(platform), expected \(wantPlatform).") + } + return + } + if cmd == 0x25 { + // Legacy LC_VERSION_MIN_IPHONEOS: x86_64 indicates iOS Simulator, arm64 indicates iPhoneOS device. + let cpuType = isLE ? readUInt32LE(sliceHeader, at: 4) : readUInt32BE(sliceHeader, at: 4) + let legacyIsSimulator = cpuType == 0x01000007 + guard legacyIsSimulator == expectedIsSimulator else { + throw StringError("Framework Mach-O binary '\(path)' legacy platform does not match destination.") + } + return + } + offset += cmdSize + } + throw StringError("Framework Mach-O binary '\(path)' lacks an iOS platform load command.") + } + private static func readUInt32BE(_ data: Data, at offset: Int) -> UInt32 { (UInt32(data[offset]) << 24) | (UInt32(data[offset + 1]) << 16) @@ -379,7 +452,8 @@ public struct BundleAssembler: Sendable { } let cleaned = try Self.validateRelativeDestination(item.relativeDestination) let folded = cleaned.lowercased() - guard seen.insert(folded).inserted else { + guard !seen.contains(where: { folded.hasPrefix($0 + "/") || $0.hasPrefix(folded + "/") }), + seen.insert(folded).inserted else { throw StringError("Resource destination collision or reserved path at '\(cleaned)'.") } @@ -467,6 +541,21 @@ public struct BundleAssembler: Sendable { info["UILaunchScreen"] = [String: Any]() } + let assetPlistData: Data? + if let preloaded = request.assetInfoData { + assetPlistData = preloaded + } else if let url = request.assetInfoURL { + assetPlistData = try ResourceOutput.readRegularFile(url) + } else { + assetPlistData = nil + } + if let data = assetPlistData { + guard let partial = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { + throw StringError("Expected an actool partial plist dictionary.") + } + info.merge(partial) { _, compiled in compiled } + } + // Enforce destination invariants after merging host plist. info["CFBundleIdentifier"] = request.bundleID info["CFBundleExecutable"] = request.executableName diff --git a/Sources/PackLib/NativeResourceCompiler.swift b/Sources/PackLib/NativeResourceCompiler.swift new file mode 100644 index 00000000..73600d8a --- /dev/null +++ b/Sources/PackLib/NativeResourceCompiler.swift @@ -0,0 +1,123 @@ +import Foundation +import Subprocess +import XUtils + +package struct NativeResourceCompiler { + package struct Output { + package var copies: [BundleResourceCopy] = [] + package var partialInfoData: Data? + } + + package let destination: AppleBuildDestination + package let module: String + + private let environment: [String: String] + + package init( + destination: AppleBuildDestination, + module: String, + environment: [String: String] = ProcessInfo.processInfo.environment + ) { + self.environment = environment + self.destination = destination + self.module = module + } + + package func compile(_ host: PackSchema.OriginalHost, workingDir: URL, temporaryDir: URL) async throws -> Output { + var output = Output() + let catalogs = try (host.assetCatalogs ?? []).map { + try input($0, extension: "xcassets", directory: true, relativeTo: workingDir) + } + if !catalogs.isEmpty { + output = try await compileAssets(catalogs, icon: host.appIcon, in: temporaryDir) + } else if host.appIcon != nil { + throw StringError("host.appIcon requires host.assetCatalogs.") + } + for path in host.storyboards ?? [] { + let source = try input(path, extension: "storyboard", directory: false, relativeTo: workingDir) + output.copies.append(try await compileStoryboard(source, in: temporaryDir)) + } + return output + } + + private func input(_ path: String, extension suffix: String, directory: Bool, relativeTo base: URL) throws -> URL { + let url = URL(fileURLWithPath: path, relativeTo: base).standardizedFileURL + var isDir: ObjCBool = false + guard url.pathExtension == suffix, FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir), + isDir.boolValue == directory else { + throw StringError("Expected an existing .\(suffix) input at \(path).") + } + return url + } + + private func freshDirectory(in parent: URL) throws -> URL { + let url = parent.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false) + return url + } + + private func compileAssets(_ catalogs: [URL], icon: String?, in parent: URL) async throws -> Output { + let work = try freshDirectory(in: parent) + let products = try freshDirectory(in: work) + let partial = work.appendingPathComponent("partial.plist") + let args = ["--compile", products.path, "--output-partial-info-plist", partial.path, + "--platform", destination.platform.toolchainPlatformDir, "--minimum-deployment-target", destination.minimumOS, + "--target-device", "iphone", "--target-device", "ipad"] + let iconArgs = icon.map { ["--app-icon", $0] } ?? [] + try await run(.assets, args + iconArgs + catalogs.map(\.path)) + try ResourceOutput.requireDirectory(work) + let partialData = try ResourceOutput.readRegularFile(partial) + try ResourceOutput.requireDirectory(products) + try ResourceOutput.requireFile(products.appendingPathComponent("Assets.car")) + let copies = try ResourceOutput.children(products).map { url in + guard url.lastPathComponent == "Assets.car" || url.pathExtension.lowercased() == "png" else { + throw StringError("Unexpected actool output at \(url.path).") + } + try ResourceOutput.requireFile(url) + return BundleResourceCopy(source: url, relativeDestination: url.lastPathComponent) + } + return Output(copies: copies, partialInfoData: partialData) + } + + private func compileStoryboard(_ source: URL, in parent: URL) async throws -> BundleResourceCopy { + let work = try freshDirectory(in: parent) + let localization = source.deletingLastPathComponent() + let localized = localization.pathExtension == "lproj" + let directory = localized ? work.appendingPathComponent(localization.lastPathComponent) : work + if localized { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + try await run(.storyboard, [ + "--module", module, "--minimum-deployment-target", destination.minimumOS, + "--compilation-directory", directory.path, source.path, + ]) + try ResourceOutput.requireDirectory(work) + try ResourceOutput.requireDirectory(directory) + let name = source.deletingPathExtension().lastPathComponent + ".storyboardc" + let result = directory.appendingPathComponent(name) + try ResourceOutput.validateStoryboard(result) + let path = localized ? localization.lastPathComponent + "/" + name : name + return BundleResourceCopy(source: result, relativeDestination: path) + } + + private enum Tool { + case assets + case storyboard + } + + private func run(_ tool: Tool, _ arguments: [String]) async throws { + let key = tool == .assets ? "XTOOL_ACTOOL" : "XTOOL_IBTOOL" + let override = environment[key] + let name = override ?? (tool == .assets ? "actool" : "x86sim") + let executable: Executable = name.contains("/") ? .path(.init(name)) : .name(name) + let prefix = tool == .storyboard && override == nil ? ["tool", "ibtool"] : [] + let childEnvironment: Environment = tool == .storyboard ? .inherit.updating(["X86SIM_IBTOOL_STRICT": "1"]) : .inherit + try await Subprocess.run( + executable, + arguments: .init(prefix + arguments), + environment: childEnvironment, + output: .currentStandardOutput, + error: .currentStandardError + ).checkSuccess() + } +} diff --git a/Sources/PackLib/PackSchema.swift b/Sources/PackLib/PackSchema.swift index 9015a54a..2cc8a5c7 100644 --- a/Sources/PackLib/PackSchema.swift +++ b/Sources/PackLib/PackSchema.swift @@ -25,6 +25,9 @@ public struct PackSchemaBase: Codable, Sendable { public var moduleName: String? public var executableName: String? public var sources: [String]? + public var assetCatalogs: [String]? + public var appIcon: String? + public var storyboards: [String]? public var processedResourcesDirectory: String? public var bridgingHeader: String? public var infoPath: String? @@ -45,6 +48,9 @@ public struct PackSchemaBase: Codable, Sendable { moduleName: String? = nil, executableName: String? = nil, sources: [String]? = nil, + assetCatalogs: [String]? = nil, + appIcon: String? = nil, + storyboards: [String]? = nil, processedResourcesDirectory: String? = nil, bridgingHeader: String? = nil, infoPath: String? = nil, @@ -64,6 +70,9 @@ public struct PackSchemaBase: Codable, Sendable { self.moduleName = moduleName self.executableName = executableName self.sources = sources + self.assetCatalogs = assetCatalogs + self.appIcon = appIcon + self.storyboards = storyboards self.processedResourcesDirectory = processedResourcesDirectory self.bridgingHeader = bridgingHeader self.infoPath = infoPath @@ -88,6 +97,7 @@ public struct PackSchemaBase: Codable, Sendable { public var name: String public var bundleID: String? public var linkage: FrameworkLinkageMode? + public var xcframeworkPath: String? public var frameworkPath: String? public var gradleTask: String? public var gradleArgs: [String]? @@ -102,6 +112,7 @@ public struct PackSchemaBase: Codable, Sendable { name: String, bundleID: String? = nil, linkage: FrameworkLinkageMode? = nil, + xcframeworkPath: String? = nil, frameworkPath: String? = nil, gradleTask: String? = nil, gradleArgs: [String]? = nil, @@ -115,6 +126,7 @@ public struct PackSchemaBase: Codable, Sendable { self.name = name self.bundleID = bundleID self.linkage = linkage + self.xcframeworkPath = xcframeworkPath self.frameworkPath = frameworkPath self.gradleTask = gradleTask self.gradleArgs = gradleArgs @@ -238,25 +250,36 @@ public struct PackSchema: Sendable { throw StringError("xtool.yml (v2): 'host.sources' must include at least one Swift source file.") } + try validateFrameworks(base.frameworks ?? []) + for mapping in base.resourceMappings ?? [] { + _ = try BundleAssembler.validateRelativeDestination(mapping.destination) + } + } + + private static func validateFrameworkPath(_ fw: FrameworkConfig) throws { + if let path = fw.xcframeworkPath { + guard fw.producer == .prebuilt, fw.frameworkPath == nil, path.hasSuffix(".xcframework") else { + throw StringError("xcframeworkPath requires a prebuilt .xcframework and excludes frameworkPath.") + } + } else if fw.producer == .prebuilt && (fw.frameworkPath ?? "").isEmpty { + throw StringError("Prebuilt framework requires frameworkPath or xcframeworkPath.") + } + } + + private static func validateFrameworks(_ frameworks: [FrameworkConfig]) throws { var seenFrameworks: Set = [] - for fw in base.frameworks ?? [] { + for fw in frameworks { guard isSafeSingleComponent(fw.name) else { throw StringError("xtool.yml (v2): framework 'name' must be a single non-empty path component.") } guard seenFrameworks.insert(fw.name.lowercased()).inserted else { throw StringError("xtool.yml (v2): duplicate framework entry '\(fw.name)'.") } - if fw.producer == .prebuilt && (fw.frameworkPath ?? "").isEmpty { - throw StringError("xtool.yml (v2): prebuilt framework '\(fw.name)' requires 'frameworkPath'.") - } + try validateFrameworkPath(fw) if fw.producer == .gradle && (fw.module ?? "").isEmpty && (fw.gradleTask ?? "").isEmpty { throw StringError("xtool.yml (v2): gradle framework '\(fw.name)' requires 'module' or 'gradleTask'.") } } - - for mapping in base.resourceMappings ?? [] { - _ = try BundleAssembler.validateRelativeDestination(mapping.destination) - } } private static func isSafeSingleComponent(_ value: String) -> Bool { diff --git a/Sources/PackLib/ResourceOutput.swift b/Sources/PackLib/ResourceOutput.swift new file mode 100644 index 00000000..fff6229e --- /dev/null +++ b/Sources/PackLib/ResourceOutput.swift @@ -0,0 +1,71 @@ +import Foundation +import XUtils +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + +package enum ResourceOutput { + private static func metadata(_ url: URL) throws -> stat { + var result = stat() + guard lstat(url.path, &result) == 0 else { + throw StringError("Cannot inspect required output at \(url.path).") + } + return result + } + + package static func requireFile(_ url: URL) throws { + let entry = try metadata(url) + guard entry.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG), entry.st_size > 0 else { + throw StringError("Expected a nonempty regular file at \(url.path).") + } + } + + package static func readRegularFile(_ url: URL) throws -> Data { + let fd = open(url.path, O_RDONLY | O_NOFOLLOW) + guard fd >= 0 else { + throw StringError("Cannot open required regular file at \(url.path).") + } + var entry = stat() + guard fstat(fd, &entry) == 0, + entry.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG), + entry.st_size > 0 else { + close(fd) + throw StringError("Expected a nonempty regular file at \(url.path).") + } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + guard let data = try handle.readToEnd(), !data.isEmpty else { + throw StringError("Failed to read regular file at \(url.path).") + } + return data + } + + package static func requireDirectory(_ url: URL) throws { + guard try metadata(url).st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) else { + throw StringError("Expected a directory at \(url.path).") + } + } + + package static func children(_ url: URL) throws -> [URL] { + try requireDirectory(url) + return try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil) + .sorted { $0.lastPathComponent < $1.lastPathComponent } + } + + package static func validateStoryboard(_ url: URL) throws { + try requireDirectory(url) + try requireFile(url.appendingPathComponent("Info.plist")) + var pending = try children(url) + var hasNib = false + while let child = pending.popLast() { + if try metadata(child).st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) { + pending += try children(child) + } else { + try requireFile(child) + hasNib = hasNib || child.pathExtension == "nib" + } + } + guard hasNib else { throw StringError("Missing compiled nib in \(url.path).") } + } +} diff --git a/Sources/XToolSupport/OriginalHostBuildOperation.swift b/Sources/XToolSupport/OriginalHostBuildOperation.swift index 93195641..c3a555bd 100644 --- a/Sources/XToolSupport/OriginalHostBuildOperation.swift +++ b/Sources/XToolSupport/OriginalHostBuildOperation.swift @@ -94,6 +94,37 @@ struct OriginalHostBuildOperation: Sendable { outputExecutableURL: compiledExecutable )) + return try await assembleAndSign( + product: product, + executableName: executableName, + moduleName: moduleName, + appBundleID: appBundleID, + destination: destination, + compiledExecutable: compiledExecutable, + host: host, + hostSourcePaths: (swiftSources + objcSources).map(\.path), + stagedFrameworks: stagedFrameworks, + workingDir: workingDir, + temporaryDir: buildTmp.url + ) + } + + // swiftlint:disable:next function_parameter_count + private func assembleAndSign( + product: String, + executableName: String, + moduleName: String, + appBundleID: String, + destination: AppleBuildDestination, + compiledExecutable: URL, + host: PackSchema.OriginalHost, + hostSourcePaths: [String], + stagedFrameworks: [StagedFramework], + workingDir: URL, + temporaryDir: URL + ) async throws -> URL { + let resources = try await NativeResourceCompiler(destination: destination, module: moduleName) + .compile(host, workingDir: workingDir, temporaryDir: temporaryDir) let resourceCopies = try buildResourceCopies( stagedFrameworks: stagedFrameworks, schema: schema, @@ -110,9 +141,10 @@ struct OriginalHostBuildOperation: Sendable { destination: destination, executableURL: compiledExecutable, hostInfoPlistURL: hostInfoPlist, - hostSourcePaths: (swiftSources + objcSources).map(\.path), + hostSourcePaths: hostSourcePaths, frameworks: stagedFrameworks, - resources: resourceCopies, + resources: resourceCopies + resources.copies, + assetInfoData: resources.partialInfoData, marketingVersion: host.marketingVersion ?? "1.0.0", buildVersion: host.buildVersion ?? "1", outputParentDir: workingDir.appendingPathComponent("xtool", isDirectory: true) diff --git a/Tests/XToolTests/NativeResourceTests.swift b/Tests/XToolTests/NativeResourceTests.swift new file mode 100644 index 00000000..ef61b46a --- /dev/null +++ b/Tests/XToolTests/NativeResourceTests.swift @@ -0,0 +1,262 @@ +import Foundation +import Testing +import XUtils +@testable import KMPBuildSupport +@testable import PackLib + +private func slice(_ id: String, platform: String = "ios", variant: String? = nil, arch: [String]) -> [String: Any] { + var result: [String: Any] = [ + "LibraryIdentifier": id, + "LibraryPath": "Kit.framework", + "SupportedPlatform": platform, + "SupportedArchitectures": arch, + ] + result["SupportedPlatformVariant"] = variant + return result +} + +private func makeThinDylib(cpuType: UInt32 = 0x0100000C, platform: UInt32 = 2) -> Data { + var data = Data() + func appendLE(_ value: UInt32) { + data.append(contentsOf: [ + UInt8(value & 0xFF), + UInt8((value >> 8) & 0xFF), + UInt8((value >> 16) & 0xFF), + UInt8((value >> 24) & 0xFF), + ]) + } + // 64-bit little-endian Mach-O header (32 bytes): 1 load command of 24 bytes (LC_BUILD_VERSION) + appendLE(0xFEEDFACF) // MH_MAGIC_64 (bytes: cf fa ed fe) + appendLE(cpuType) + appendLE(0) // cpusubtype + appendLE(6) // MH_DYLIB + appendLE(1) // ncmds + appendLE(24) // sizeofcmds + appendLE(0) // flags + appendLE(0) // reserved + // LC_BUILD_VERSION (24 bytes) + appendLE(0x32) // cmd = LC_BUILD_VERSION + appendLE(24) // cmdsize + appendLE(platform) // 2 = iOS, 7 = iOS Simulator + appendLE(0x00100000) // minos 16.0 + appendLE(0x00100000) // sdk 16.0 + appendLE(0) // ntools + return data +} + +@Test func selectOnlyTheExactXCFrameworkDestination() throws { + let directory = try TemporaryDirectory(name: "Kit.xcframework") + let root = directory.url + let sim = try AppleBuildDestination.resolve(triple: "arm64-apple-ios-simulator", minimumOS: "16.0") + let device = try AppleBuildDestination.resolve(triple: "arm64-apple-ios", minimumOS: "16.0") + let ios = slice("device", arch: ["arm64"]) + let universal = slice("universal", variant: "simulator", arch: ["x86_64", "arm64"]) + let other = [ + slice("intel", variant: "simulator", arch: ["x86_64"]), + slice("tv", platform: "tvos", variant: "simulator", arch: ["arm64"]), + slice("catalyst", variant: "maccatalyst", arch: ["arm64"]), + ] + func manifest(_ slices: [[String: Any]]) throws { + let data = try PropertyListSerialization.data(fromPropertyList: ["AvailableLibraries": slices], format: .binary, options: 0) + try data.write(to: root.appendingPathComponent("Info.plist")) + } + func resolve(_ destination: AppleBuildDestination) throws -> String { + try XCFrameworkSlice.resolve(in: root, name: "Kit", destination: destination).deletingLastPathComponent().lastPathComponent + } + for id in ["device", "universal", "tv", "intel", "catalyst"] { + let framework = root.appendingPathComponent("\(id)/Kit.framework") + try FileManager.default.createDirectory(at: framework, withIntermediateDirectories: true) + } + try manifest(other + [ios]) + #expect(throws: Error.self) { try resolve(sim) } + #expect(try resolve(device) == "device") + try manifest([ios, universal]) + #expect(try resolve(sim) == "universal") + try manifest([universal]) + #expect(throws: Error.self) { try resolve(device) } + try manifest([universal, universal]) + #expect(throws: Error.self) { try resolve(sim) } + try manifest([slice("..", variant: "simulator", arch: ["arm64"])]) + #expect(throws: Error.self) { try resolve(sim) } +} + +@Test func storyboardValidationRejectsNestedSymlinks() throws { + let directory = try TemporaryDirectory(name: "Launch.storyboardc") + let root = directory.url + try Data([1]).write(to: root.appendingPathComponent("Info.plist")) + #expect(throws: Error.self) { try ResourceOutput.validateStoryboard(root) } + let nib = root.appendingPathComponent("Scene.nib") + try Data([1]).write(to: nib) + try ResourceOutput.validateStoryboard(root) + let subdir = root.appendingPathComponent("nested") + try FileManager.default.createDirectory(at: subdir, withIntermediateDirectories: false) + try FileManager.default.createSymbolicLink(at: subdir.appendingPathComponent("alias"), withDestinationURL: nib) + #expect(throws: Error.self) { try ResourceOutput.validateStoryboard(root) } +} + +@Test func nativeToolsFeedBundleAssembly() async throws { + let directory = try TemporaryDirectory(name: "original host") + let root = directory.url + let fm = FileManager.default + func tool(_ name: String, _ body: String) throws -> URL { + let url = root.appendingPathComponent(name) + try Data(("#!/bin/sh\nset -eu\n" + body).utf8).write(to: url) + try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path) + return url + } + let assetTool = try tool("asset tool", """ + test "$1" = --compile + test "$3" = --output-partial-info-plist + printf car > "$2/Assets.car" + printf png > "$2/Primary.png" + printf '%s' 'CFBundleIconNamePrimary' > "$4" + """) + let ibTool = try tool("ib tool", """ + test "$X86SIM_IBTOOL_STRICT" = 1 + test "$5" = --compilation-directory + mkdir "$6/Launch.storyboardc" + printf nib > "$6/Launch.storyboardc/Scene.nib" + printf plist > "$6/Launch.storyboardc/Info.plist" + """) + for path in ["Assets.xcassets", "Base.lproj"] { + try fm.createDirectory(at: root.appendingPathComponent(path), withIntermediateDirectories: false) + } + try Data().write(to: root.appendingPathComponent("Base.lproj/Launch.storyboard")) + let destination = try AppleBuildDestination.resolve(triple: "arm64-apple-ios-simulator", minimumOS: "16.0") + let host = PackSchema.OriginalHost( + assetCatalogs: ["Assets.xcassets"], + appIcon: "Primary", + storyboards: ["Base.lproj/Launch.storyboard"] + ) + let compiler = NativeResourceCompiler(destination: destination, module: "Demo", environment: [ + "XTOOL_ACTOOL": assetTool.path, "XTOOL_IBTOOL": ibTool.path, + ]) + let result = try await compiler.compile(host, workingDir: root, temporaryDir: root) + let (app, receipt) = try BundleAssembler().assemble(.init( + product: "Demo", bundleID: "example.Demo", destination: destination, + executableURL: ibTool, resources: result.copies, assetInfoData: result.partialInfoData, outputParentDir: root + )) + #expect(receipt.stagedResourceCount == 3) + for path in ["Assets.car", "Primary.png", "Base.lproj/Launch.storyboardc/Scene.nib"] { + #expect(fm.fileExists(atPath: app.appendingPathComponent(path).path)) + } + let data = try Data(contentsOf: app.appendingPathComponent("Info.plist")) + let info = try #require(PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]) + #expect(info["CFBundleIconName"] as? String == "Primary") + let symlinkPlist = root.appendingPathComponent("partial-link.plist") + try fm.createSymbolicLink(at: symlinkPlist, withDestinationURL: app.appendingPathComponent("Info.plist")) + #expect(throws: Error.self) { try ResourceOutput.readRegularFile(symlinkPlist) } +} + +@Test(arguments: [DetectedFrameworkLinkage.static, .dynamic]) +func selectedFrameworkUsesDetectedLinkage(_ linkage: DetectedFrameworkLinkage) async throws { + let directory = try TemporaryDirectory(name: "vendor") + let root = directory.url + let xcframework = root.appendingPathComponent("Kit.xcframework") + let framework = xcframework.appendingPathComponent("device/Kit.framework") + let headers = framework.appendingPathComponent("Headers") + try FileManager.default.createDirectory(at: headers, withIntermediateDirectories: true) + try Data("// Kit".utf8).write(to: headers.appendingPathComponent("Kit.h")) + let binary = framework.appendingPathComponent("Kit") + let dylib = makeThinDylib(cpuType: 0x0100000C, platform: 2) + try (linkage == .dynamic ? dylib : Data("!\n".utf8)).write(to: binary) + let manifest = ["AvailableLibraries": [slice("device", arch: ["arm64"])]] + let data = try PropertyListSerialization.data(fromPropertyList: manifest, format: .xml, options: 0) + try data.write(to: xcframework.appendingPathComponent("Info.plist")) + let destination = try AppleBuildDestination.resolve(triple: "arm64-apple-ios", minimumOS: "16.0") + let staged = try await GradleFrameworkProducer().produce( + config: .init(producer: .prebuilt, name: "Kit", xcframeworkPath: "Kit.xcframework"), + bundleID: "example.Demo.Kit", + destination: destination, + configuration: .debug, + workingDirectory: root + ) + #expect(staged.linkage == linkage) + let (app, receipt) = try BundleAssembler().assemble(.init( + product: "Demo", bundleID: "example.Demo", destination: destination, + executableURL: binary, frameworks: [staged], outputParentDir: root + )) + let embedded = linkage == .dynamic + #expect(receipt.frameworks.first?.embedded == embedded) + #expect(FileManager.default.fileExists(atPath: app.appendingPathComponent("Frameworks/Kit.framework/Kit").path) == embedded) +} + +private func makeLegacyThinDylib(cpuType: UInt32) -> Data { + var data = Data() + func appendLE(_ value: UInt32) { + data.append(contentsOf: [ + UInt8(value & 0xFF), + UInt8((value >> 8) & 0xFF), + UInt8((value >> 16) & 0xFF), + UInt8((value >> 24) & 0xFF), + ]) + } + appendLE(0xFEEDFACF) // MH_MAGIC_64 + appendLE(cpuType) + appendLE(0) + appendLE(6) // MH_DYLIB + appendLE(1) // ncmds + appendLE(16) // sizeofcmds + appendLE(0) + appendLE(0) + // LC_VERSION_MIN_IPHONEOS (16 bytes) + appendLE(0x25) + appendLE(16) + appendLE(0x000E0000) // version 14.0 + appendLE(0x000E0000) // sdk 14.0 + return data +} + +@Test func rejectsMislabeledThinXCFrameworkSlice() async throws { + let directory = try TemporaryDirectory(name: "mislabeled") + let root = directory.url + let xcframework = root.appendingPathComponent("Kit.xcframework") + let framework = xcframework.appendingPathComponent("device/Kit.framework") + let headers = framework.appendingPathComponent("Headers") + try FileManager.default.createDirectory(at: headers, withIntermediateDirectories: true) + try Data("// Kit".utf8).write(to: headers.appendingPathComponent("Kit.h")) + let binary = framework.appendingPathComponent("Kit") + let manifest = ["AvailableLibraries": [slice("device", arch: ["arm64"])]] + try PropertyListSerialization.data(fromPropertyList: manifest, format: .xml, options: 0) + .write(to: xcframework.appendingPathComponent("Info.plist")) + let deviceDest = try AppleBuildDestination.resolve(triple: "arm64-apple-ios", minimumOS: "16.0") + // Wrong CPU architecture (x86_64 binary inside arm64 slice) + try makeThinDylib(cpuType: 0x01000007, platform: 2).write(to: binary) + await #expect(throws: Error.self) { + _ = try await GradleFrameworkProducer().produce( + config: .init(producer: .prebuilt, name: "Kit", xcframeworkPath: "Kit.xcframework"), + bundleID: "example.Demo.Kit", + destination: deviceDest, + configuration: .debug, + workingDirectory: root + ) + } + // Wrong platform (iOS Simulator LC_BUILD_VERSION=7 inside iPhoneOS device slice) + try makeThinDylib(cpuType: 0x0100000C, platform: 7).write(to: binary) + await #expect(throws: Error.self) { + _ = try await GradleFrameworkProducer().produce( + config: .init(producer: .prebuilt, name: "Kit", xcframeworkPath: "Kit.xcframework"), + bundleID: "example.Demo.Kit", + destination: deviceDest, + configuration: .debug, + workingDirectory: root + ) + } + // Legacy x86_64 simulator dylib with LC_VERSION_MIN_IPHONEOS must be accepted for x86_64 simulator. + let simFramework = xcframework.appendingPathComponent("sim-x64/Kit.framework") + try FileManager.default.createDirectory(at: simFramework.appendingPathComponent("Headers"), withIntermediateDirectories: true) + try Data("// Kit".utf8).write(to: simFramework.appendingPathComponent("Headers/Kit.h")) + try makeLegacyThinDylib(cpuType: 0x01000007).write(to: simFramework.appendingPathComponent("Kit")) + let simManifest = ["AvailableLibraries": [slice("sim-x64", variant: "simulator", arch: ["x86_64"])]] + try PropertyListSerialization.data(fromPropertyList: simManifest, format: .xml, options: 0) + .write(to: xcframework.appendingPathComponent("Info.plist")) + let simX64Dest = try AppleBuildDestination.resolve(triple: "x86_64-apple-ios-simulator", minimumOS: "16.0") + let stagedLegacy = try await GradleFrameworkProducer().produce( + config: .init(producer: .prebuilt, name: "Kit", xcframeworkPath: "Kit.xcframework"), + bundleID: "example.Demo.Kit", + destination: simX64Dest, + configuration: .debug, + workingDirectory: root + ) + #expect(stagedLegacy.linkage == .dynamic) +}