diff --git a/Sources/KMPBuildSupport/GradleFrameworkProducer.swift b/Sources/KMPBuildSupport/GradleFrameworkProducer.swift index 7c392231..1b90620b 100644 --- a/Sources/KMPBuildSupport/GradleFrameworkProducer.swift +++ b/Sources/KMPBuildSupport/GradleFrameworkProducer.swift @@ -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 diff --git a/Sources/PackLib/AppleBuildDestination.swift b/Sources/PackLib/AppleBuildDestination.swift index de7a48d0..7cd2ae0b 100644 --- a/Sources/PackLib/AppleBuildDestination.swift +++ b/Sources/PackLib/AppleBuildDestination.swift @@ -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 { @@ -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 ) } @@ -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] } @@ -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 { @@ -174,6 +189,7 @@ public struct AppleBuildDestination: Sendable, Codable, Equatable { return ResolvedSDKPaths( sdkRoot: sdkRoot, toolsetBin: toolsetBin, + swiftResources: swiftResources, swiftPlatformLib: swiftPlatformLib ) } @@ -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 @@ -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 diff --git a/Sources/PackLib/BundleAssembler.swift b/Sources/PackLib/BundleAssembler.swift index a68b1de4..dd7cf21f 100644 --- a/Sources/PackLib/BundleAssembler.swift +++ b/Sources/PackLib/BundleAssembler.swift @@ -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 } @@ -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. diff --git a/Sources/PackLib/HostToolEnvironment.swift b/Sources/PackLib/HostToolEnvironment.swift new file mode 100644 index 00000000..1f9bcccf --- /dev/null +++ b/Sources/PackLib/HostToolEnvironment.swift @@ -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 + } +} diff --git a/Sources/PackLib/MachOUUID.swift b/Sources/PackLib/MachOUUID.swift new file mode 100644 index 00000000..801bd331 --- /dev/null +++ b/Sources/PackLib/MachOUUID.swift @@ -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() + var result: [Slice] = [] + for _ in 0..= 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..= 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) } + } + } +} diff --git a/Sources/PackLib/NativeResourceCompiler.swift b/Sources/PackLib/NativeResourceCompiler.swift index 73600d8a..fbca8a42 100644 --- a/Sources/PackLib/NativeResourceCompiler.swift +++ b/Sources/PackLib/NativeResourceCompiler.swift @@ -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), diff --git a/Sources/PackLib/OriginalHostCompiler.swift b/Sources/PackLib/OriginalHostCompiler.swift index 3ebac5ce..c09c2c95 100644 --- a/Sources/PackLib/OriginalHostCompiler.swift +++ b/Sources/PackLib/OriginalHostCompiler.swift @@ -20,6 +20,7 @@ public struct OriginalHostCompiler: Sendable { public let linkedLibraries: [String] public let extraSwiftFlags: [String] public let extraLinkerFlags: [String] + package var symbolObjectsDirectory: URL? public let outputExecutableURL: URL public init( @@ -83,7 +84,12 @@ public struct OriginalHostCompiler: Sendable { "-module-name", request.moduleName, "-swift-version", request.swiftLanguageMode, "-parse-as-library", + "-Xfrontend", "-enable-cross-import-overlays", ] + // The SDK's Swift resource directory supplies the target's Clang importer resources. + if let swiftResourcesPath = request.destination.swiftResourcesPath { + args += ["-resource-dir", swiftResourcesPath] + } args += request.configuration == .release ? ["-O"] : ["-Onone", "-g"] if let bridgingHeader = request.bridgingHeader { args += ["-import-objc-header", bridgingHeader.path] @@ -140,6 +146,10 @@ public struct OriginalHostCompiler: Sendable { withIntermediateDirectories: true ) + if let directory = request.symbolObjectsDirectory { + return try await linkWithDebugObjects(request, sdkRoot: sdkRoot, directory: directory) + } + var objcObjects: [URL] = [] if !request.objcSources.isEmpty { let objDir = try TemporaryDirectory(name: "xtool-objc-objs") @@ -154,6 +164,49 @@ public struct OriginalHostCompiler: Sendable { return try await linkHost(request: request, sdkRoot: sdkRoot, objcObjects: []) } + private func linkWithDebugObjects(_ request: Request, sdkRoot: String, directory: URL) async throws -> URL { + guard !request.swiftSources.isEmpty else { + throw StringError("Objective-C-only host linking is not yet implemented; supply Swift host sources.") + } + let swiftc = try await BuildSettings.swiftcURL() + let swiftObject = directory.appendingPathComponent("host-swift.o") + var compileArgs = Self.baseCompilerFlags(for: request, sdkRoot: sdkRoot) + for framework in request.frameworks { + compileArgs += ["-F", framework.frameworkURL.deletingLastPathComponent().path] + } + compileArgs += request.extraSwiftFlags + ["-g", "-whole-module-optimization", "-emit-object"] + compileArgs += request.swiftSources.map(\.path) + ["-o", swiftObject.path] + try await Subprocess.run( + .path(swiftc), + arguments: .init(compileArgs), + environment: HostToolEnvironment.child(), + output: .currentStandardOutput, + error: .currentStandardError + ).checkSuccess() + + var objects = [swiftObject.path] + for (index, source) in request.objcSources.enumerated() { + let object = directory.appendingPathComponent("host-objc-\(index).o") + try await compileObjCSource(source, to: object, request: request, sdkRoot: sdkRoot) + objects.append(object.path) + } + var linkArgs = ["-sdk", sdkRoot, "-target", request.destination.clangTriple] + if let swiftResourcesPath = request.destination.swiftResourcesPath { + linkArgs += ["-resource-dir", swiftResourcesPath] + } + linkArgs += Self.frameworkAndLinkerFlags(for: request, sdkRoot: sdkRoot) + linkArgs += request.extraSwiftFlags + request.extraLinkerFlags.flatMap { ["-Xlinker", $0] } + linkArgs += objects + ["-o", request.outputExecutableURL.path] + try await Subprocess.run( + .path(swiftc), + arguments: .init(linkArgs), + environment: HostToolEnvironment.child(), + output: .currentStandardOutput, + error: .currentStandardError + ).checkSuccess() + return request.outputExecutableURL + } + private func compileObjCSource( _ source: URL, to objectURL: URL, @@ -174,11 +227,13 @@ public struct OriginalHostCompiler: Sendable { for fw in request.frameworks { args += ["-F", fw.frameworkURL.deletingLastPathComponent().path] } + if request.symbolObjectsDirectory != nil { args.append("-g") } args += ["-c", source.path, "-o", objectURL.path] try await Subprocess.run( .name("clang"), arguments: .init(args), + environment: HostToolEnvironment.child(), output: .currentStandardOutput, error: .currentStandardError ) @@ -198,6 +253,7 @@ public struct OriginalHostCompiler: Sendable { try await Subprocess.run( .path(swiftcPath), arguments: .init(args), + environment: HostToolEnvironment.child(), output: .currentStandardOutput, error: .currentStandardError ) diff --git a/Sources/PackLib/PackSchema.swift b/Sources/PackLib/PackSchema.swift index 2cc8a5c7..450c99b7 100644 --- a/Sources/PackLib/PackSchema.swift +++ b/Sources/PackLib/PackSchema.swift @@ -35,6 +35,7 @@ public struct PackSchemaBase: Codable, Sendable { public var deploymentTarget: String? public var marketingVersion: String? public var buildVersion: String? + public var emitDSYM: Bool? public var swiftLanguageMode: String? public var swiftDefines: [String]? public var linkedFrameworks: [String]? @@ -58,6 +59,7 @@ public struct PackSchemaBase: Codable, Sendable { deploymentTarget: String? = nil, marketingVersion: String? = nil, buildVersion: String? = nil, + emitDSYM: Bool? = nil, swiftLanguageMode: String? = nil, swiftDefines: [String]? = nil, linkedFrameworks: [String]? = nil, @@ -80,6 +82,7 @@ public struct PackSchemaBase: Codable, Sendable { self.deploymentTarget = deploymentTarget self.marketingVersion = marketingVersion self.buildVersion = buildVersion + self.emitDSYM = emitDSYM self.swiftLanguageMode = swiftLanguageMode self.swiftDefines = swiftDefines self.linkedFrameworks = linkedFrameworks diff --git a/Sources/PackLib/ReleaseSymbols.swift b/Sources/PackLib/ReleaseSymbols.swift new file mode 100644 index 00000000..55e7aed4 --- /dev/null +++ b/Sources/PackLib/ReleaseSymbols.swift @@ -0,0 +1,37 @@ +import Foundation +import Subprocess +import XUtils + +package enum ReleaseSymbols { + package static func tool(for destination: AppleBuildDestination) -> URL? { + let path = ProcessInfo.processInfo.environment["PATH"] ?? "" + let directories = [destination.toolsetBinPath].compactMap { $0 } + path.split(separator: ":").map(String.init) + return directories.lazy.map { + URL(fileURLWithPath: $0).appendingPathComponent("dsymutil") + }.first { FileManager.default.isExecutableFile(atPath: $0.path) } + } + + package static func publish(for executable: URL, bundle: URL, tool: URL?) async throws { + let output = bundle.deletingLastPathComponent().appendingPathComponent(bundle.lastPathComponent + ".dSYM") + let manager = FileManager.default + guard let tool else { + if manager.fileExists(atPath: output.path) { try manager.removeItem(at: output) } + return + } + let work = bundle.deletingLastPathComponent().appendingPathComponent(UUID().uuidString) + try manager.createDirectory(at: work, withIntermediateDirectories: false) + defer { try? manager.removeItem(at: work) } + let staged = work.appendingPathComponent(output.lastPathComponent) + try await Subprocess.run( + .path(.init(tool.path)), + arguments: [executable.path, "-o", staged.path], + environment: HostToolEnvironment.child(), + output: .currentStandardOutput, + error: .currentStandardError + ).checkSuccess() + let dwarf = staged.appendingPathComponent("Contents/Resources/DWARF").appendingPathComponent(executable.lastPathComponent) + try MachOUUID.verify(executable: MachOUUID.read(from: executable), symbols: MachOUUID.read(from: dwarf)) + if manager.fileExists(atPath: output.path) { try manager.removeItem(at: output) } + try manager.moveItem(at: staged, to: output) + } +} diff --git a/Sources/XToolSupport/OriginalHostBuildOperation.swift b/Sources/XToolSupport/OriginalHostBuildOperation.swift index c3a555bd..f6a9486e 100644 --- a/Sources/XToolSupport/OriginalHostBuildOperation.swift +++ b/Sources/XToolSupport/OriginalHostBuildOperation.swift @@ -76,7 +76,12 @@ struct OriginalHostBuildOperation: Sendable { d.out.print("Compiling original host '\(moduleName)' for \(destination.clangTriple)...") let compiler = OriginalHostCompiler() let bridgingHeader = host.bridgingHeader.map { resolveURL($0, relativeTo: workingDir) } - _ = try await compiler.compile(.init( + let symbolTool = host.emitDSYM == true && configuration == .release + ? ReleaseSymbols.tool(for: destination) : nil + if host.emitDSYM == true && configuration == .release && symbolTool == nil { + d.out.print("Skipping release dSYM because dsymutil was not found.") + } + var request = OriginalHostCompiler.Request( moduleName: moduleName, executableName: executableName, destination: destination, @@ -92,7 +97,13 @@ struct OriginalHostBuildOperation: Sendable { extraSwiftFlags: host.extraSwiftFlags ?? [], extraLinkerFlags: host.extraLinkerFlags ?? [], outputExecutableURL: compiledExecutable - )) + ) + let objectDir = buildTmp.url.appendingPathComponent(UUID().uuidString) + if symbolTool != nil { + try FileManager.default.createDirectory(at: objectDir, withIntermediateDirectories: false) + request.symbolObjectsDirectory = objectDir + } + _ = try await compiler.compile(request) return try await assembleAndSign( product: product, @@ -101,6 +112,7 @@ struct OriginalHostBuildOperation: Sendable { appBundleID: appBundleID, destination: destination, compiledExecutable: compiledExecutable, + symbolTool: symbolTool, host: host, hostSourcePaths: (swiftSources + objcSources).map(\.path), stagedFrameworks: stagedFrameworks, @@ -117,6 +129,7 @@ struct OriginalHostBuildOperation: Sendable { appBundleID: String, destination: AppleBuildDestination, compiledExecutable: URL, + symbolTool: URL?, host: PackSchema.OriginalHost, hostSourcePaths: [String], stagedFrameworks: [StagedFramework], @@ -157,8 +170,13 @@ struct OriginalHostBuildOperation: Sendable { workingDir: workingDir ) + let executable = bundleURL.appendingPathComponent(executableName) + try await ReleaseSymbols.publish(for: executable, bundle: bundleURL, tool: symbolTool) if let receiptPath { - try writeReceipt(receipt, to: resolveURL(receiptPath, relativeTo: workingDir)) + var detailed = receipt + try detailed.recordUUIDs(in: bundleURL, executable: executable) + detailed.dSYMBundleName = symbolTool.map { _ in bundleURL.lastPathComponent + ".dSYM" } + try writeReceipt(detailed, to: resolveURL(receiptPath, relativeTo: workingDir)) } return bundleURL @@ -257,7 +275,7 @@ struct OriginalHostBuildOperation: Sendable { at: url.deletingLastPathComponent(), withIntermediateDirectories: true ) - try data.write(to: url) + try data.write(to: url, options: .atomic) } private func resolveURL(_ raw: String, relativeTo base: URL) -> URL { diff --git a/Tests/XToolTests/HostToolEnvironmentTests.swift b/Tests/XToolTests/HostToolEnvironmentTests.swift new file mode 100644 index 00000000..64cde9f0 --- /dev/null +++ b/Tests/XToolTests/HostToolEnvironmentTests.swift @@ -0,0 +1,29 @@ +import PackLib +import Testing + +@Test(arguments: ["/host/lib:/opt/lib", ""]) +func restoresSavedHostPathExactly(_ saved: String) { + let source = [ + "LD_LIBRARY_PATH": "/app/usr/lib", "XTOOL_HOST_LD_LIBRARY_PATH": saved, + "OPTION_A_HOST_LD_LIBRARY_PATH": "legacy", "XTOOL_ACTOOL": "/tools/assets", + ] + var expected = source + expected["LD_LIBRARY_PATH"] = saved + #expect(HostToolEnvironment.sanitized(source) == expected) +} + +@Test func stripsOnlyTheAppImageLibraryDirectory() { + let source = [ + "LD_LIBRARY_PATH": ":/app/usr/lib:/usr/lib:/app/usr/lib64:/app/usr/lib:", "APPDIR": "/app", + "XTOOL_IBTOOL": "custom", "PATH": "/tools", + ] + var expected = source + expected["LD_LIBRARY_PATH"] = ":/usr/lib:/app/usr/lib64:" + #expect(HostToolEnvironment.sanitized(source) == expected) + #expect(HostToolEnvironment.sanitized(["APPDIR": "/app", "LD_LIBRARY_PATH": "/app/usr/lib"]) == ["APPDIR": "/app"]) + let ordinary = ["LD_LIBRARY_PATH": "/opt/app/usr/lib"] + #expect(HostToolEnvironment.sanitized(ordinary) == ordinary) + #expect(HostToolEnvironment.sanitized(ordinary, extractedRoot: "/opt/app").isEmpty) + let legacy = ["OPTION_A_HOST_LD_LIBRARY_PATH": "/saved"] + #expect(HostToolEnvironment.sanitized(legacy) == ["OPTION_A_HOST_LD_LIBRARY_PATH": "/saved", "LD_LIBRARY_PATH": "/saved"]) +} diff --git a/Tests/XToolTests/MachOUUIDTests.swift b/Tests/XToolTests/MachOUUIDTests.swift new file mode 100644 index 00000000..ae0ce15d --- /dev/null +++ b/Tests/XToolTests/MachOUUIDTests.swift @@ -0,0 +1,117 @@ +import Foundation +import PackLib +import Testing +import XUtils + +private let arm: UInt32 = 0x0100000c +private let intel: UInt32 = 0x01000007 + +private func word(_ value: UInt32, little: Bool = false) -> Data { + withUnsafeBytes(of: little ? value.littleEndian : value.bigEndian) { Data($0) } +} + +private func binary(cpu: UInt32, uuid: Bool = true, seed: UInt8 = 0) -> Data { + let header: [UInt32] = [0xfeedfacf, cpu, cpu == intel ? 3 : 0, 2, uuid ? 1 : 0, uuid ? 24 : 0, 0, 0] + var data = header.reduce(into: Data()) { $0.append(word($1, little: true)) } + if uuid { + data += word(0x1b, little: true) + word(24, little: true) + Data((0..<16).map { seed + UInt8($0) }) + } + return data +} + +private func universal(wide: Bool) -> Data { + let armSlice = binary(cpu: arm) + let intelSlice = binary(cpu: intel, seed: 16) + var offset = UInt32(8 + 2 * (wide ? 32 : 20)) + var data = word(wide ? 0xcafebabf : 0xcafebabe) + word(2) + for (cpu, slice) in [(arm, armSlice), (intel, intelSlice)] { + data += word(cpu) + word(cpu == intel ? 3 : 0) + if wide { data += word(0) } + data += word(offset) + if wide { data += word(0) } + data += word(UInt32(slice.count)) + word(0) + if wide { data += word(0) } + offset += UInt32(slice.count) + } + return data + armSlice + intelSlice +} + +@Test(arguments: [arm, intel]) +func readsThinUUID(_ cpu: UInt32) throws { + let slices = try MachOUUID.read(binary(cpu: cpu)) + #expect(slices.map(\.cpuType) == [cpu]) + #expect(slices.map(\.uuid?.uuidString) == ["00010203-0405-0607-0809-0A0B0C0D0E0F"]) +} + +@Test(arguments: [true, false]) +func readsBothUniversalSlices(_ wide: Bool) throws { + let slices = try MachOUUID.read(universal(wide: wide)) + #expect(slices.map(\.cpuType) == [arm, intel]) + #expect(slices.map(\.uuid?.uuidString) == [ + "00010203-0405-0607-0809-0A0B0C0D0E0F", "10111213-1415-1617-1819-1A1B1C1D1E1F", + ]) + try MachOUUID.verify(executable: slices, symbols: Array(slices.reversed())) + #expect(throws: (any Error).self) { + try MachOUUID.read(Data(universal(wide: wide).dropLast())) + } +} + +@Test func rejectsMissingAndMismatchedSymbolUUIDs() throws { + let missing = try MachOUUID.read(binary(cpu: arm, uuid: false)) + #expect(missing.count == 1) + #expect(missing[0].uuid == nil) + let host = try MachOUUID.read(binary(cpu: arm)) + let other = try MachOUUID.read(binary(cpu: arm, seed: 1)) + #expect(throws: (any Error).self) { try MachOUUID.verify(executable: missing, symbols: missing) } + #expect(throws: (any Error).self) { try MachOUUID.verify(executable: host, symbols: other) } +} + +@Test func rejectsCommandThatCrossesTheSliceBoundary() { + var truncated = universal(wide: false) + // The first slice is followed by valid data, but its own extent excludes the UUID's last byte. + truncated.replaceSubrange(20..<24, with: word(55)) + #expect(throws: (any Error).self) { try MachOUUID.read(truncated) } +} + +@Test func rejectsUUIDsAssignedToTheWrongArchitecture() throws { + let host = try MachOUUID.read(universal(wide: false)) + let wrongArm = try MachOUUID.read(binary(cpu: arm, seed: 16)) + let wrongIntel = try MachOUUID.read(binary(cpu: intel)) + #expect(throws: (any Error).self) { + try MachOUUID.verify(executable: host, symbols: wrongArm + wrongIntel) + } +} + +@Test func publishesOnlyAVerifiedCompanion() async throws { + let directory = try TemporaryDirectory(name: "release symbols") + let manager = FileManager.default + let bundle = directory.url.appendingPathComponent("Demo.app", isDirectory: true) + try manager.createDirectory(at: bundle, withIntermediateDirectories: false) + let host = bundle.appendingPathComponent("Runner") + try binary(cpu: arm).write(to: host) + + let tool = directory.url.appendingPathComponent("dsymutil") + let script = """ + #!/bin/sh + set -eu + test "$2" = -o + mkdir -p "$3/Contents/Resources/DWARF" + cp "$1.fixture" "$3/Contents/Resources/DWARF/\(host.lastPathComponent)" + """ + try Data(script.utf8).write(to: tool) + try manager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: tool.path) + let fixture = host.appendingPathExtension("fixture") + let companion = directory.url.appendingPathComponent("Demo.app.dSYM") + try binary(cpu: intel).write(to: fixture) + await #expect(throws: Error.self) { + try await ReleaseSymbols.publish(for: host, bundle: bundle, tool: tool) + } + #expect(!manager.fileExists(atPath: companion.path)) + + try binary(cpu: arm).write(to: fixture) + try await ReleaseSymbols.publish(for: host, bundle: bundle, tool: tool) + let dwarf = companion.appendingPathComponent("Contents/Resources/DWARF/Runner") + let emitted = try MachOUUID.read(from: dwarf) + let expected = try MachOUUID.read(from: host) + #expect(emitted == expected) +} diff --git a/Tests/XToolTests/NativeResourceTests.swift b/Tests/XToolTests/NativeResourceTests.swift index ef61b46a..bce48b7e 100644 --- a/Tests/XToolTests/NativeResourceTests.swift +++ b/Tests/XToolTests/NativeResourceTests.swift @@ -105,6 +105,7 @@ private func makeThinDylib(cpuType: UInt32 = 0x0100000C, platform: UInt32 = 2) - return url } let assetTool = try tool("asset tool", """ + if [ "$(uname -s)" = Linux ]; then test "$LD_LIBRARY_PATH" = /option-a-test-host; fi test "$1" = --compile test "$3" = --output-partial-info-plist printf car > "$2/Assets.car" @@ -112,6 +113,7 @@ private func makeThinDylib(cpuType: UInt32 = 0x0100000C, platform: UInt32 = 2) - printf '%s' 'CFBundleIconNamePrimary' > "$4" """) let ibTool = try tool("ib tool", """ + if [ "$(uname -s)" = Linux ]; then test "$LD_LIBRARY_PATH" = /option-a-test-host; fi test "$X86SIM_IBTOOL_STRICT" = 1 test "$5" = --compilation-directory mkdir "$6/Launch.storyboardc" @@ -129,6 +131,7 @@ private func makeThinDylib(cpuType: UInt32 = 0x0100000C, platform: UInt32 = 2) - storyboards: ["Base.lproj/Launch.storyboard"] ) let compiler = NativeResourceCompiler(destination: destination, module: "Demo", environment: [ + "XTOOL_HOST_LD_LIBRARY_PATH": "/option-a-test-host", "XTOOL_ACTOOL": assetTool.path, "XTOOL_IBTOOL": ibTool.path, ]) let result = try await compiler.compile(host, workingDir: root, temporaryDir: root) diff --git a/Tests/XToolTests/OptionAOriginalHostTests.swift b/Tests/XToolTests/OptionAOriginalHostTests.swift index 5f6e8690..888c5cc8 100644 --- a/Tests/XToolTests/OptionAOriginalHostTests.swift +++ b/Tests/XToolTests/OptionAOriginalHostTests.swift @@ -194,6 +194,13 @@ import Yams outputParentDir: tmp.appendingPathComponent("out", isDirectory: true) )) + var detailed = receipt + try detailed.recordUUIDs(in: appURL, executable: appURL.appendingPathComponent("Parlor")) + #expect(detailed.hostMachOUUIDs?.first?.cpuType == 0x0100000c) + #expect(detailed.frameworks.first?.machOUUIDs == detailed.hostMachOUUIDs) + let encoded = try JSONEncoder().encode(detailed) + let decoded = try JSONDecoder().decode(BuildReceipt.self, from: encoded) + #expect(decoded == detailed) #expect(receipt.bundleID == "me.parlor.ios.debug") #expect(receipt.frameworks.count == 1) #expect(receipt.frameworks.first?.embedded == true) diff --git a/Tests/XToolTests/SDKBuilderTests.swift b/Tests/XToolTests/SDKBuilderTests.swift index 89672e84..0d73b591 100644 --- a/Tests/XToolTests/SDKBuilderTests.swift +++ b/Tests/XToolTests/SDKBuilderTests.swift @@ -1,5 +1,6 @@ import Dependencies import Foundation +import PackLib import Testing import XCLIUtils import XUtils @@ -29,6 +30,71 @@ struct SDKBuilderTests { #expect(destination == "../../../../../Library/Frameworks/XCTest.framework") } + @Test func originalHostUsesSlimSDKSwiftResources() async throws { + let fixture = try Fixture() + defer { fixture.remove() } + try fixture.addSDK("iPhoneOS") + try fixture.addSDK("iPhoneSimulator") + + let resourcePath = "Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift" + let shims = fixture.app.appending(path: "Contents/\(resourcePath)/shims") + let moduleMap = Data("module SwiftShims { header \"SwiftShims.h\" export * }".utf8) + try FileManager.default.createDirectory(at: shims, withIntermediateDirectories: true) + try moduleMap.write(to: shims.appending(path: "module.modulemap")) + try Data("typedef int SwiftShimsFixture;\n".utf8).write(to: shims.appending(path: "SwiftShims.h")) + + let definition = try await fixture.importDeveloper(mode: .buildSlim) + try JSONEncoder().encode(definition).write(to: fixture.output.appending(path: "swift-sdk.json")) + try FileManager.default.removeItem(at: fixture.app) + + let sdk = try #require(DarwinSDK(bundle: fixture.output)) + let destination = try AppleBuildDestination.resolve( + triple: "arm64-apple-ios-simulator", + minimumOS: "17.0", + darwinSDK: sdk + ) + let sdkRoot = try #require(destination.sdkRootPath) + let resources = fixture.output.appending(path: resourcePath) + let installedModuleMap = try Data(contentsOf: resources.appending(path: "shims/module.modulemap")) + #expect(installedModuleMap == moduleMap) + #expect(FileManager.default.isReadableFile(atPath: resources.appending(path: "shims/SwiftShims.h").path)) + + let request = OriginalHostCompiler.Request( + moduleName: "Fixture", + executableName: "Fixture", + destination: destination, + configuration: .debug, + swiftSources: [fixture.root.appending(path: "Host.swift")], + outputExecutableURL: fixture.root.appending(path: "Fixture") + ) + let args = OriginalHostCompiler.buildSwiftcArguments(for: request, sdkRoot: sdkRoot, objcObjects: []) + let flag = try #require(args.firstIndex(of: "-resource-dir")) + #expect(args.dropFirst(flag + 1).first == resources.standardizedFileURL.path) + + let customResources = fixture.output.appending(path: "CustomSwiftResources") + try FileManager.default.createDirectory(at: customResources, withIntermediateDirectories: true) + var overridden = definition + for (triple, var entry) in overridden.targetTriples { + entry.swiftResourcesPath = "CustomSwiftResources" + overridden.targetTriples[triple] = entry + } + try JSONEncoder().encode(overridden).write(to: fixture.output.appending(path: "swift-sdk.json")) + let customDest = try AppleBuildDestination.resolve( + triple: "arm64-apple-ios-simulator", + minimumOS: "17.0", + darwinSDK: sdk + ) + #expect(customDest.swiftResourcesPath == customResources.standardizedFileURL.path) + + try FileManager.default.removeItem(at: fixture.output.appending(path: "swift-sdk.json")) + let fallbackDest = try AppleBuildDestination.resolve( + triple: "arm64-apple-ios-simulator", + minimumOS: "17.0", + darwinSDK: sdk + ) + #expect(fallbackDest.swiftResourcesPath == resources.standardizedFileURL.path) + } + @Test(arguments: [SDKBuilder.Mode.buildSlim, .buildNormal]) func fullImportKeepsMacOSTriples(mode: SDKBuilder.Mode) async throws { let fixture = try Fixture()