Skip to content
Merged
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
23 changes: 16 additions & 7 deletions Sources/KMPBuildSupport/GradleFrameworkProducer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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) {
Expand Down
52 changes: 52 additions & 0 deletions Sources/KMPBuildSupport/XCFrameworkSlice.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
113 changes: 101 additions & 12 deletions Sources/PackLib/BundleAssembler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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("!<arch>\n".utf8)
let thinMagic = Data("!<thin>\n".utf8)
if sliceHeader.starts(with: archiveMagic) || sliceHeader.starts(with: thinMagic) {
Expand All @@ -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..<ncmds {
guard offset + 8 <= cmdData.count else {
throw StringError("Framework Mach-O binary '\(path)' has truncated load command header.")
}
let cmd = isLE ? readUInt32LE(cmdData, at: offset) : readUInt32BE(cmdData, at: offset)
let cmdSize = Int(isLE ? readUInt32LE(cmdData, at: offset + 4) : readUInt32BE(cmdData, at: offset + 4))
guard cmdSize >= 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)
Expand Down Expand Up @@ -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)'.")
}

Expand Down Expand Up @@ -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
Expand Down
Loading