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
1 change: 1 addition & 0 deletions Sources/KMPBuildSupport/GradleFrameworkProducer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ public struct GradleFrameworkProducer: Sendable {
try await Subprocess.run(
.path(FilePath(wrapperURL.path)),
arguments: .init(args),
environment: HostToolEnvironment.child(),
workingDirectory: FilePath(projectRoot.path),
output: .currentStandardOutput,
error: .currentStandardError
Expand Down
37 changes: 27 additions & 10 deletions Sources/PackLib/AppleBuildDestination.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public struct AppleBuildDestination: Sendable, Codable, Equatable {
public let gradleTarget: String
public let sdkRootPath: String?
public let toolsetBinPath: String?
public let swiftResourcesPath: String?
public let swiftPlatformLibPath: String?

public var isSimulator: Bool {
Expand Down Expand Up @@ -92,6 +93,7 @@ public struct AppleBuildDestination: Sendable, Codable, Equatable {
gradleTarget: gradleTarget,
sdkRootPath: paths.sdkRoot?.path,
toolsetBinPath: paths.toolsetBin?.path,
swiftResourcesPath: paths.swiftResources?.path,
swiftPlatformLibPath: paths.swiftPlatformLib?.path
)
}
Expand All @@ -118,12 +120,14 @@ public struct AppleBuildDestination: Sendable, Codable, Equatable {
private struct ResolvedSDKPaths {
let sdkRoot: URL?
let toolsetBin: URL?
let swiftResources: URL?
let swiftPlatformLib: URL?
}

private struct SwiftSDKManifest: Decodable {
struct TripleEntry: Decodable {
let sdkRootPath: String?
let swiftResourcesPath: String?
}
let targetTriples: [String: TripleEntry]
}
Expand All @@ -137,18 +141,29 @@ public struct AppleBuildDestination: Sendable, Codable, Equatable {
#if os(macOS)
return resolveMacOSHostSDKPaths(platform: platform)
#else
return ResolvedSDKPaths(sdkRoot: nil, toolsetBin: nil, swiftPlatformLib: nil)
return ResolvedSDKPaths(sdkRoot: nil, toolsetBin: nil, swiftResources: nil, swiftPlatformLib: nil)
#endif
}
let bundle = darwinSDK.bundle
let manifestURL = bundle.appendingPathComponent("swift-sdk.json")
var sdkRoot: URL?
if let data = try? Data(contentsOf: manifestURL),
let manifest = try? JSONDecoder().decode(SwiftSDKManifest.self, from: data),
let relative = manifest.targetTriples[sdkKey]?.sdkRootPath {
let candidate = URL(fileURLWithPath: relative, relativeTo: bundle).standardizedFileURL
let manifest = (try? Data(contentsOf: manifestURL))
.flatMap { try? JSONDecoder().decode(SwiftSDKManifest.self, from: $0) }
let entry = manifest?.targetTriples[sdkKey]
let manifestSDK = entry?.sdkRootPath.map {
bundle.appendingPathComponent($0, isDirectory: true).standardizedFileURL
}
let manifestResources = entry?.swiftResourcesPath.map {
bundle.appendingPathComponent($0, isDirectory: true).standardizedFileURL
}
var sdkRoot = manifestSDK.flatMap { $0.dirExists ? $0 : nil }
var swiftResources = manifestResources.flatMap { $0.dirExists ? $0 : nil }
if swiftResources == nil {
let candidate = bundle.appendingPathComponent(
"Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift",
isDirectory: true
)
if candidate.dirExists {
sdkRoot = candidate
swiftResources = candidate
}
}
if sdkRoot == nil {
Expand All @@ -174,6 +189,7 @@ public struct AppleBuildDestination: Sendable, Codable, Equatable {
return ResolvedSDKPaths(
sdkRoot: sdkRoot,
toolsetBin: toolsetBin,
swiftResources: swiftResources,
swiftPlatformLib: swiftPlatformLib
)
}
Expand All @@ -191,12 +207,12 @@ public struct AppleBuildDestination: Sendable, Codable, Equatable {
try proc.run()
proc.waitUntilExit()
guard proc.terminationStatus == 0 else {
return ResolvedSDKPaths(sdkRoot: nil, toolsetBin: nil, swiftPlatformLib: nil)
return ResolvedSDKPaths(sdkRoot: nil, toolsetBin: nil, swiftResources: nil, swiftPlatformLib: nil)
}
let out = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
.trimmingCharacters(in: .whitespacesAndNewlines)
guard !out.isEmpty else {
return ResolvedSDKPaths(sdkRoot: nil, toolsetBin: nil, swiftPlatformLib: nil)
return ResolvedSDKPaths(sdkRoot: nil, toolsetBin: nil, swiftResources: nil, swiftPlatformLib: nil)
}
let sdkURL = URL(fileURLWithPath: out, isDirectory: true)
let devDir = sdkURL
Expand All @@ -209,10 +225,11 @@ public struct AppleBuildDestination: Sendable, Codable, Equatable {
return ResolvedSDKPaths(
sdkRoot: sdkURL.dirExists ? sdkURL : nil,
toolsetBin: nil,
swiftResources: nil,
swiftPlatformLib: swiftLib.dirExists ? swiftLib : nil
)
} catch {
return ResolvedSDKPaths(sdkRoot: nil, toolsetBin: nil, swiftPlatformLib: nil)
return ResolvedSDKPaths(sdkRoot: nil, toolsetBin: nil, swiftResources: nil, swiftPlatformLib: nil)
}
}
#endif
Expand Down
14 changes: 13 additions & 1 deletion Sources/PackLib/BundleAssembler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public struct BuildReceipt: Sendable, Codable, Equatable {
public let name: String
public let bundleID: String
public let linkage: DetectedFrameworkLinkage
package var machOUUIDs: [MachOUUID.Slice]?
public let embedded: Bool
}

Expand All @@ -57,9 +58,20 @@ public struct BuildReceipt: Sendable, Codable, Equatable {
public let bundleID: String
public let destination: AppleBuildDestination
public let hostSources: [String]
public let frameworks: [FrameworkEntry]
package var hostMachOUUIDs: [MachOUUID.Slice]?
package var dSYMBundleName: String?
public internal(set) var frameworks: [FrameworkEntry]
public let stagedResourceCount: Int
public let appBundlePath: String

package mutating func recordUUIDs(in bundle: URL, executable: URL) throws {
hostMachOUUIDs = try MachOUUID.read(from: executable)
for index in frameworks.indices where frameworks[index].embedded {
let name = frameworks[index].name
let binary = bundle.appendingPathComponent("Frameworks/\(name).framework/\(name)")
frameworks[index].machOUUIDs = try MachOUUID.read(from: binary)
}
}
}

/// Shared bundle assembly engine for Option A original-host iOS apps.
Expand Down
38 changes: 38 additions & 0 deletions Sources/PackLib/HostToolEnvironment.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import Foundation
import Subprocess

package enum HostToolEnvironment {
package static func sanitized(_ source: [String: String], extractedRoot: String? = nil) -> [String: String] {
var result = source
if let saved = source["XTOOL_HOST_LD_LIBRARY_PATH"] ?? source["OPTION_A_HOST_LD_LIBRARY_PATH"] {
result["LD_LIBRARY_PATH"] = saved
} else if let root = source["APPDIR"] ?? extractedRoot, root.hasPrefix("/"),
let current = source["LD_LIBRARY_PATH"] {
let directory = URL(fileURLWithPath: root).standardizedFileURL
guard directory.path != "/" else { return result }
let library = directory.appendingPathComponent("usr/lib").path
let paths = current.components(separatedBy: ":")
let kept = paths.filter {
!$0.hasPrefix("/") || URL(fileURLWithPath: $0).standardizedFileURL.path != library
}
if paths.count != kept.count {
result["LD_LIBRARY_PATH"] = kept.isEmpty ? nil : kept.joined(separator: ":")
}
}
return result
}

package static func child(_ source: [String: String] = ProcessInfo.processInfo.environment) -> Environment {
#if os(Linux)
let executable = URL(fileURLWithPath: "/proc/self/exe").resolvingSymlinksInPath()
let root = executable.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
let packaged = root.appendingPathComponent("usr/bin/xtool").path == executable.path
&& FileManager.default.isExecutableFile(atPath: root.appendingPathComponent("AppRun").path)
let libraryPath = sanitized(source, extractedRoot: packaged ? root.path : nil)["LD_LIBRARY_PATH"]
if libraryPath != source["LD_LIBRARY_PATH"] {
return .inherit.updating(["LD_LIBRARY_PATH": libraryPath])
}
#endif
return .inherit
}
}
126 changes: 126 additions & 0 deletions Sources/PackLib/MachOUUID.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import Foundation
import XUtils

/// CPU type and subtype identify a slice even when a universal binary is reordered.
package enum MachOUUID {
package struct Slice: Codable, Equatable, Sendable {
package let cpuType: UInt32
package let cpuSubtype: UInt32
package let uuid: UUID?
}

package static func read(from url: URL) throws -> [Slice] {
try read(Data(contentsOf: url, options: .mappedIfSafe))
}

package static func verify(executable: [Slice], symbols: [Slice]) throws {
guard !executable.isEmpty, executable.allSatisfy({ $0.uuid != nil }),
executable.count == symbols.count, executable.allSatisfy(symbols.contains) else {
throw StringError("dSYM UUIDs do not match the executable.")
}
}

package static func read(_ data: Data) throws -> [Slice] {
var header = Cursor(data)
switch try header.number(4) {
case 0xcafebabe: return try universal(&header, wide: false)
case 0xcafebabf: return try universal(&header, wide: true)
case 0xbebafeca, 0xbfbafeca:
header.little = true
return try universal(&header, wide: data.first == 0xbf)
default: return [try thin(data)]
}
}

private static func universal(_ header: inout Cursor, wide: Bool) throws -> [Slice] {
let count = try header.number(4)
let entrySize = wide ? 32 : 20
guard count > 0, count <= UInt64(header.remaining.count / entrySize) else {
throw StringError("Invalid universal Mach-O table.")
}
let firstSlice = 8 + Int(count) * entrySize
var architectures = Set<UInt64>()
var result: [Slice] = []
for _ in 0..<count {
let cpu = try header.number(4)
let subtype = try header.number(4)
let offset = try header.number(wide ? 8 : 4)
let size = try header.number(wide ? 8 : 4)
_ = try header.take(wide ? 8 : 4)
guard let start = Int(exactly: offset), start >= firstSlice, start <= header.data.count,
size <= UInt64(header.data.count - start) else {
throw StringError("Universal Mach-O slice exceeds file bounds.")
}
let bytes = header.data.dropFirst(start).prefix(Int(size))
let slice = try thin(bytes)
guard slice.cpuType == cpu, slice.cpuSubtype == subtype,
architectures.insert(cpu << 32 | subtype).inserted else {
throw StringError("Inconsistent universal Mach-O architecture.")
}
result.append(slice)
}
return result
}

private static func thin(_ data: Data) throws -> Slice {
var header = Cursor(data)
let magic = try header.number(4)
let is64Bit: Bool
switch magic {
case 0xcffaedfe, 0xcefaedfe:
header.little = true
is64Bit = magic == 0xcffaedfe
case 0xfeedfacf, 0xfeedface:
is64Bit = magic == 0xfeedfacf
default: throw StringError("Expected a Mach-O header.")
}
let cpu = UInt32(try header.number(4))
let subtype = UInt32(try header.number(4))
_ = try header.take(4)
let count = try header.number(4)
let length = try header.number(4)
_ = try header.take(is64Bit ? 8 : 4)
let alignment: UInt64 = is64Bit ? 8 : 4
var commands = Cursor(try header.take(Int(length)), little: header.little)
var uuid: UUID?
for _ in 0..<count {
let kind = try commands.number(4)
let size = try commands.number(4)
guard size >= 8, size.isMultiple(of: alignment) else {
throw StringError("Invalid Mach-O command size.")
}
let payload = try commands.take(Int(size) - 8)
if kind == 0x1b {
guard size == 24, uuid == nil else { throw StringError("Invalid LC_UUID command.") }
uuid = payload.withUnsafeBytes { UUID(uuid: $0.loadUnaligned(as: uuid_t.self)) }
}
}
guard commands.remaining.isEmpty else { throw StringError("Invalid Mach-O load command count.") }
return Slice(cpuType: cpu, cpuSubtype: subtype, uuid: uuid)
}

private struct Cursor {
let data: Data
var remaining: Data
var little: Bool

init(_ data: Data, little: Bool = false) {
self.data = data
self.remaining = data
self.little = little
}

mutating func take(_ count: Int) throws -> Data {
guard count <= remaining.count else { throw StringError("Truncated Mach-O data.") }
let bytes = remaining.prefix(count)
remaining = remaining.dropFirst(count)
return bytes
}

mutating func number(_ width: Int) throws -> UInt64 {
let bytes = try take(width)
if little { return bytes.reversed().reduce(0) { $0 << 8 | UInt64($1) } }
return bytes.reduce(0) { $0 << 8 | UInt64($1) }
}
}
}
3 changes: 2 additions & 1 deletion Sources/PackLib/NativeResourceCompiler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ package struct NativeResourceCompiler {
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
let base = HostToolEnvironment.child(environment)
let childEnvironment = tool == .storyboard ? base.updating(["X86SIM_IBTOOL_STRICT": "1"]) : base
try await Subprocess.run(
executable,
arguments: .init(prefix + arguments),
Expand Down
Loading