From 941e7fb61e042caa754c15fcdc9003008abdaaee Mon Sep 17 00:00:00 2001 From: Gui Rambo Date: Tue, 24 Nov 2026 17:36:34 -0300 Subject: [PATCH] Add versioning to scheme bindings, refer to VirtualBuddy components by a stable symlinked location, store scheme URLs so that app can potentially migrate schemes in the future --- .../Sources/MacDebugHost/DebugBindings.swift | 18 +++++- .../Sources/MacDebugHost/DebugBroker.swift | 6 ++ .../MacDebugHost/DebugHostCommand.swift | 10 +-- .../MacDebugHost/DebugHostConfiguration.swift | 32 +++++++++- .../Sources/MacDebugHost/DebugScheme.swift | 46 ++++++++++++-- .../MacDebugHostTests/DebugBindingTests.swift | 14 ++++- .../MacDebugHostTests/DebugBrokerTests.swift | 2 +- .../MacDebugHostTests/DebugSchemeTests.swift | 61 ++++++++++++++++++- Packages/README.md | 2 +- README-Developers.md | 2 +- .../Debugging/VirtualBuddyDebugging.swift | 5 +- VirtualCore/Source/Settings/VBSettings.swift | 19 ++++-- .../DeveloperFeaturesSettingsTests.swift | 22 ++++--- 13 files changed, 201 insertions(+), 38 deletions(-) diff --git a/Packages/MacDebugHost/Sources/MacDebugHost/DebugBindings.swift b/Packages/MacDebugHost/Sources/MacDebugHost/DebugBindings.swift index 3dd19bb..3cf419a 100644 --- a/Packages/MacDebugHost/Sources/MacDebugHost/DebugBindings.swift +++ b/Packages/MacDebugHost/Sources/MacDebugHost/DebugBindings.swift @@ -9,11 +9,15 @@ public struct DebugBinding: Codable, Equatable, Sendable { public let id: UUID public let destination: UUID public let target: String + /// Where the scheme was created. The developer can move or rename it afterwards, so a Run + /// action never depends on this. It lets the app tell the developer which schemes it approved. + public let scheme: URL - public init(id: UUID, destination: UUID, target: String) { + public init(id: UUID, destination: UUID, target: String, scheme: URL) { self.id = id self.destination = destination self.target = target + self.scheme = scheme } } @@ -29,8 +33,13 @@ public protocol DebugBindingStore: Sendable { /// app's authentication key without the user's permission, so it cannot forge a record. public final class KeychainDebugBindingStore: DebugBindingStore { private struct Record: Codable { + /// Names the layout of the binding and of the authenticated payload. + /// A record with another version is not an approval. + var version = Record.currentVersion let binding: DebugBinding let code: Data + + static let currentVersion = 1 } private let service: String @@ -45,7 +54,8 @@ public final class KeychainDebugBindingStore: DebugBindingStore { public func binding(for id: UUID) throws -> DebugBinding? { guard let data = try read(account: id.uuidString), - let record = try? JSONDecoder().decode(Record.self, from: data), record.binding.id == id, + let record = try? JSONDecoder().decode(Record.self, from: data), + record.version == Record.currentVersion, record.binding.id == id, HMAC.isValidAuthenticationCode(record.code, authenticating: Self.payload(record.binding), using: try key()) else { return nil } @@ -53,7 +63,9 @@ public final class KeychainDebugBindingStore: DebugBindingStore { } private static func payload(_ binding: DebugBinding) -> Data { - Data([binding.id.uuidString, binding.destination.uuidString, binding.target].joined(separator: "\n").utf8) + // The scheme location goes last because it is the only field that can contain a newline. + Data([String(Record.currentVersion), binding.id.uuidString, binding.destination.uuidString, binding.target, + binding.scheme.path].joined(separator: "\n").utf8) } private func key() throws -> SymmetricKey { diff --git a/Packages/MacDebugHost/Sources/MacDebugHost/DebugBroker.swift b/Packages/MacDebugHost/Sources/MacDebugHost/DebugBroker.swift index 082ad38..0afd19e 100644 --- a/Packages/MacDebugHost/Sources/MacDebugHost/DebugBroker.swift +++ b/Packages/MacDebugHost/Sources/MacDebugHost/DebugBroker.swift @@ -107,6 +107,12 @@ public final class DebugBroker { public func start() throws { guard listenerTask == nil else { return } try DebugSocket.prepareRuntime(at: configuration.runtimeDirectory) + do { + try configuration.refreshLinks() + } catch { + // Links from an earlier launch may still be right, so keep accepting runs. + logger.error("Could not update the links used by Xcode schemes: \(error.localizedDescription)") + } let path = configuration.endpoint(pid: getpid()) unlink(path.path) // Only the helper shipped in this app may request runs. It is the same signed diff --git a/Packages/MacDebugHost/Sources/MacDebugHost/DebugHostCommand.swift b/Packages/MacDebugHost/Sources/MacDebugHost/DebugHostCommand.swift index 7316562..0fe1b32 100644 --- a/Packages/MacDebugHost/Sources/MacDebugHost/DebugHostCommand.swift +++ b/Packages/MacDebugHost/Sources/MacDebugHost/DebugHostCommand.swift @@ -8,20 +8,20 @@ public enum DebugHostCommand { case "extract" where arguments.count == 4: try DebugSymbolCache.extract(tool: URL(fileURLWithPath: arguments[1]), primary: URL(fileURLWithPath: arguments[2]), output: URL(fileURLWithPath: arguments[3])) case "prepare" where arguments.count == 2: - try await prepare(URL(fileURLWithPath: arguments[1]), configuration: configuration) + guard let binding = UUID(uuidString: arguments[1]) else { throw MacDebugError("Set up the Xcode scheme again.") } + try await prepare(binding, configuration: configuration) default: throw MacDebugError("Run the debug helper from a generated Xcode scheme.") } } - private static func prepare(_ scheme: URL, configuration: DebugHostConfiguration) async throws { + private static func prepare(_ id: UUID, configuration: DebugHostConfiguration) async throws { try DebugSocket.prepareRuntime(at: configuration.runtimeDirectory) - let xml = try XMLDocument(contentsOf: scheme, options: [.nodeLoadExternalEntitiesNever]) - guard let binding = DebugScheme.binding(in: xml) else { throw MacDebugError("Set up the Xcode scheme again.") } - let handoff = configuration.runtimeDirectory.appendingPathComponent(binding.scheme.uuidString + ".json") + let handoff = configuration.runtimeDirectory.appendingPathComponent(id.uuidString + ".json") func record(_ reply: DebugBuildReply) throws { try JSONEncoder().encode(reply).write(to: handoff, options: .atomic) } try record(.failure("This Run action did not finish preparing the target.")) do { let settings = ProcessInfo.processInfo.environment + let (xml, binding) = try DebugScheme.installed(binding: id, settings: settings) guard CustomLLDBCommands.isEnabled else { throw MacDebugError("Enable Custom LLDB Commands in Xcode debugging setup, then relaunch Xcode.") } guard settings["PLATFORM_NAME"] == "macosx", let directory = settings["TARGET_BUILD_DIR"], let name = settings["FULL_PRODUCT_NAME"], name.hasSuffix(".app"), let path = settings["EXECUTABLE_PATH"], diff --git a/Packages/MacDebugHost/Sources/MacDebugHost/DebugHostConfiguration.swift b/Packages/MacDebugHost/Sources/MacDebugHost/DebugHostConfiguration.swift index 81f8677..734f84c 100644 --- a/Packages/MacDebugHost/Sources/MacDebugHost/DebugHostConfiguration.swift +++ b/Packages/MacDebugHost/Sources/MacDebugHost/DebugHostConfiguration.swift @@ -1,4 +1,5 @@ import Foundation +import MacDebugProtocol /// Locations owned by the adopting app. Use a short per-user socket directory /// because Darwin limits the length of Unix-domain socket addresses. @@ -6,14 +7,43 @@ public struct DebugHostConfiguration: Sendable { public let applicationURL: URL public let helperURL: URL public let runtimeDirectory: URL + /// A per-user directory that stays in place when the app is updated, moved or renamed. + /// Generated schemes live in the developer's projects, where the app cannot find them + /// again, so they refer to the links in this directory and never to the app bundle. + public let linksDirectory: URL - public init(applicationURL: URL, helperURL: URL, runtimeDirectory: URL) { + public init(applicationURL: URL, helperURL: URL, runtimeDirectory: URL, linksDirectory: URL) { self.applicationURL = applicationURL self.helperURL = helperURL self.runtimeDirectory = runtimeDirectory + self.linksDirectory = linksDirectory } func endpoint(pid: pid_t) -> URL { runtimeDirectory.appendingPathComponent("host-\(pid).sock") } + + // Existing schemes contain these two paths. Keep the names when changing anything else. + var helperLink: URL { linksDirectory.appendingPathComponent("helper") } + var moduleLink: URL { linksDirectory.appendingPathComponent("mac_debug.py") } + + /// Points the links at this copy of the app. Call when the app starts accepting runs + /// and before generating a scheme, so schemes follow the app wherever it is installed. + public func refreshLinks() throws { + guard let module = Bundle.module.url(forResource: "mac_debug", withExtension: "py") else { + throw MacDebugError("Could not find the packaged LLDB module.") + } + try DebugTools.directory(linksDirectory) + for (link, target) in [(helperLink, helperURL), (moduleLink, module)] { + guard (try? FileManager.default.destinationOfSymbolicLink(atPath: link.path)) != target.path else { continue } + // Renaming over the old link leaves no moment when a Run action finds it missing. + let replacement = linksDirectory.appendingPathComponent("." + UUID().uuidString) + try FileManager.default.createSymbolicLink(atPath: replacement.path, withDestinationPath: target.path) + guard rename(replacement.path, link.path) == 0 else { + let failure = POSIXError(.init(rawValue: errno) ?? .EIO) + try? FileManager.default.removeItem(at: replacement) + throw failure + } + } + } } diff --git a/Packages/MacDebugHost/Sources/MacDebugHost/DebugScheme.swift b/Packages/MacDebugHost/Sources/MacDebugHost/DebugScheme.swift index 277f20b..232edd6 100644 --- a/Packages/MacDebugHost/Sources/MacDebugHost/DebugScheme.swift +++ b/Packages/MacDebugHost/Sources/MacDebugHost/DebugScheme.swift @@ -117,6 +117,31 @@ public struct DebugScheme { return Binding(destination: destination, scheme: scheme, target: target) } + /// Finds the scheme of a running pre-action from the build settings Xcode gives it. + /// Xcode keeps the binding when the developer renames or duplicates a scheme, so prefer the + /// file named after the scheme that is running: its Run arguments are the ones to use. + static func installed(binding id: UUID, settings: [String: String]) throws -> (document: XMLDocument, binding: Binding) { + var containers = [URL]() + if let workspace = settings["WORKSPACE_PATH"].map({ URL(fileURLWithPath: $0) }) { + // A project opened on its own reports the workspace embedded in it. + containers.append(workspace.lastPathComponent == "project.xcworkspace" ? workspace.deletingLastPathComponent() : workspace) + } + if let project = settings["PROJECT_FILE_PATH"] { containers.append(URL(fileURLWithPath: project)) } + var found: (document: XMLDocument, binding: Binding)? + for container in containers { + for dir in ["xcuserdata/\(NSUserName()).xcuserdatad/xcschemes", "xcshareddata/xcschemes"] { + for file in (try? FileManager.default.contentsOfDirectory(at: container.appendingPathComponent(dir), includingPropertiesForKeys: nil)) ?? [] where file.pathExtension == "xcscheme" { + guard let xml = try? XMLDocument(contentsOf: file, options: [.nodeLoadExternalEntitiesNever]), + let binding = binding(in: xml), binding.scheme == id else { continue } + if file.deletingPathExtension().lastPathComponent == settings["SCHEME_NAME"] { return (xml, binding) } + if found == nil { found = (xml, binding) } + } + } + } + guard let found else { throw MacDebugError("Could not find the scheme for this Run action. Set up Xcode debugging for it again.") } + return found + } + static func shellQuote(_ s: String) -> String { "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'" } /// Call when the developer asks for the scheme. The binding is recorded as their approval @@ -153,9 +178,20 @@ public struct DebugScheme { let pre = launch.elements(forName: "PreActions").first ?? Self.element("PreActions") if pre.parent == nil { launch.insertChild(pre, at: 0) } let action = Self.element("ExecutionAction", ["ActionType": "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction"]) - let cli = configuration.helperURL guard targetID.range(of: "^[a-zA-Z0-9_.-]+$", options: .regularExpression) != nil else { throw MacDebugError("The selected app has an invalid Xcode target identifier.") } - let script = "# MacDebug \(destination.uuidString) \(id.uuidString) \(targetID)\nexec " + Self.shellQuote(cli.path) + " prepare " + Self.shellQuote(output.path) + "\n" + // The script names neither the app bundle nor this file, so the scheme keeps working after + // the app is updated or moved, and after the developer renames the scheme or moves the project. + // Run the helper by its real path: it finds the app from its own location. + try configuration.refreshLinks() + let script = """ + # MacDebug \(destination.uuidString) \(id.uuidString) \(targetID) + helper=$(/usr/bin/readlink \(Self.shellQuote(configuration.helperLink.path))) || { + echo "The app that created this scheme is not set up for Xcode debugging. Open it, then run again." >&2 + exit 1 + } + exec "$helper" prepare \(id.uuidString) + + """ let content = Self.element("ActionContent", ["title": "Prepare app on " + destinationName, "scriptText": script]) let environment = Self.element("EnvironmentBuildable") environment.addChild(reference.copy() as! XMLNode) @@ -177,14 +213,12 @@ public struct DebugScheme { set(launch, "selectedDebuggerIdentifier", "Xcode.DebuggerFoundation.Debugger.LLDB") set(launch, "selectedLauncherIdentifier", "Xcode.DebuggerFoundation.Launcher.LLDB") set(launch, "customLaunchCommandPauseAfterCommands", "NO") - guard let module = Bundle.module.url(forResource: "mac_debug", withExtension: "py")?.path else { - throw MacDebugError("Could not find the packaged LLDB module.") - } + let module = configuration.moduleLink.path guard !module.contains("`"), !module.contains("\n") else { throw MacDebugError("The LLDB module path contains an unsupported character.") } let escaped = module.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") let runtime = Data(configuration.runtimeDirectory.path.utf8).base64EncodedString() set(launch, "customLaunchCommand", "command script import \"\(escaped)\"\nmac-debug-connect \(id.uuidString) \(runtime)") - try bindings.register(DebugBinding(id: id, destination: destination, target: targetID)) + try bindings.register(DebugBinding(id: id, destination: destination, target: targetID, scheme: output)) try DebugTools.directory(directory) // Foundation emits literal newlines in attributes. XML readers normalize // those to spaces, collapsing both custom LLDB commands into one. diff --git a/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugBindingTests.swift b/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugBindingTests.swift index b2bb01f..b25d45b 100644 --- a/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugBindingTests.swift +++ b/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugBindingTests.swift @@ -20,7 +20,7 @@ struct DebugBindingTests { } @Test func aRunUsesTheApprovedDestinationAndLocalAppPaths() throws { - let binding = DebugBinding(id: UUID(), destination: UUID(), target: "APP") + let binding = DebugBinding(id: UUID(), destination: UUID(), target: "APP", scheme: URL(fileURLWithPath: "/Projects/App.xcodeproj/xcuserdata/App.xcscheme")) let app = "file:///Build/Products/Debug/Example.app" let build = try DebugBuild(request(binding: binding.id, product: app, executable: app + "/Contents/MacOS/Example"), binding: binding) #expect(build.destination == binding.destination) @@ -44,7 +44,7 @@ struct DebugBindingTests { let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service] defer { while SecItemDelete(query as CFDictionary) == errSecSuccess {} } - let binding = DebugBinding(id: UUID(), destination: UUID(), target: "APP") + let binding = DebugBinding(id: UUID(), destination: UUID(), target: "APP", scheme: URL(fileURLWithPath: "/Projects/App.xcodeproj/xcuserdata/App.xcscheme")) #expect(try store.binding(for: binding.id) == nil) try store.register(binding) #expect(try store.binding(for: binding.id) == binding) @@ -65,5 +65,15 @@ struct DebugBindingTests { let update = [kSecValueData as String: try JSONSerialization.data(withJSONObject: record)] #expect(SecItemUpdate(item as CFDictionary, update as CFDictionary) == errSecSuccess) #expect(try store.binding(for: binding.id) == nil) + + // A record in a layout this version does not know is not an approval either. + try store.register(binding) + #expect(SecItemCopyMatching(query.merging([kSecAttrAccount as String: binding.id.uuidString, kSecReturnData as String: true]) { $1 } as CFDictionary, &result) == errSecSuccess) + let current = try #require(result as? Data) + var newer = try #require(try JSONSerialization.jsonObject(with: current) as? [String: Any]) + #expect(newer["version"] as? Int == 1) + newer["version"] = 2 + #expect(SecItemUpdate(item as CFDictionary, [kSecValueData as String: try JSONSerialization.data(withJSONObject: newer)] as CFDictionary) == errSecSuccess) + #expect(try store.binding(for: binding.id) == nil) } } diff --git a/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugBrokerTests.swift b/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugBrokerTests.swift index 0a49041..7fe981d 100644 --- a/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugBrokerTests.swift +++ b/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugBrokerTests.swift @@ -18,7 +18,7 @@ struct DebugBrokerTests { private func broker() -> DebugBroker { let helper = root.appendingPathComponent("helper") return DebugBroker( - configuration: .init(applicationURL: root, helperURL: helper, runtimeDirectory: root), + configuration: .init(applicationURL: root, helperURL: helper, runtimeDirectory: root, linksDirectory: root.appendingPathComponent("Links")), cache: DebugSymbolCache(root: root.appendingPathComponent("Symbols"), helperURL: helper), provisioning: .init(cacheDirectory: root.appendingPathComponent("Profiles"), interaction: UnusedInteraction()), bindings: MemoryBindingStore(), diff --git a/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugSchemeTests.swift b/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugSchemeTests.swift index 15dca69..9206d8d 100644 --- a/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugSchemeTests.swift +++ b/Packages/MacDebugHost/Tests/MacDebugHostTests/DebugSchemeTests.swift @@ -15,7 +15,9 @@ struct DebugSchemeTests { let choice = try #require(try DebugScheme.choices(in: ws).first) let vm = UUID() let app = URL(fileURLWithPath: "/Applications/VirtualBuddy.app") - let configuration = DebugHostConfiguration(applicationURL: app, helperURL: app.appendingPathComponent("Contents/MacOS/helper"), runtimeDirectory: root) + let links = root.appendingPathComponent("Stable Links") + let helper = app.appendingPathComponent("Contents/MacOS/helper") + let configuration = DebugHostConfiguration(applicationURL: app, helperURL: helper, runtimeDirectory: root, linksDirectory: links) let bindings = MemoryBindingStore() let file = try choice.install(destination: vm, named: "My VM", configuration: configuration, bindings: bindings) let xml = try XMLDocument(contentsOf: file, options: []) @@ -36,7 +38,62 @@ struct DebugSchemeTests { #expect(throws: (any Error).self) { try choice.install(destination: UUID(), named: "My VM", configuration: configuration, bindings: bindings) } let bindingID = try #require(id.flatMap(UUID.init(uuidString:))) let approved = try #require(bindings.binding(for: bindingID)) - #expect(approved.destination == vm && approved.target == "APP") + #expect(approved.destination == vm && approved.target == "APP" && approved.scheme == file) + + // The scheme refers to the links only, so the app can move and the scheme can be renamed. + let text = try String(contentsOf: file, encoding: .utf8) + #expect(!text.contains(app.path) && !text.contains(file.lastPathComponent) && !text.contains(".bundle")) + #expect(try FileManager.default.destinationOfSymbolicLink(atPath: links.appendingPathComponent("helper").path) == helper.path) + let module = try FileManager.default.destinationOfSymbolicLink(atPath: links.appendingPathComponent("mac_debug.py").path) + #expect(FileManager.default.fileExists(atPath: module)) + #expect(launch.attribute(forName: "customLaunchCommand")?.stringValue?.hasPrefix("command script import \"\(links.path)/mac_debug.py\"\n") == true) + + let moved = URL(fileURLWithPath: "/Applications/Renamed.app/Contents/MacOS/helper") + try DebugHostConfiguration(applicationURL: app, helperURL: moved, runtimeDirectory: root, linksDirectory: links).refreshLinks() + #expect(try FileManager.default.destinationOfSymbolicLink(atPath: links.appendingPathComponent("helper").path) == moved.path) + #expect(try FileManager.default.contentsOfDirectory(atPath: links.path).sorted() == ["helper", "mac_debug.py"]) + + // The pre-action prints the helper it resolved through the link, followed by its arguments. + let script = try #require(try xml.nodes(forXPath: "//PreActions/ExecutionAction/ActionContent/@scriptText").first?.stringValue) + let echo = root.appendingPathComponent("echo helper") + try "#!/bin/sh\necho \"$0\" \"$@\"\n".write(to: echo, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: echo.path) + try DebugHostConfiguration(applicationURL: app, helperURL: echo, runtimeDirectory: root, linksDirectory: links).refreshLinks() + func run() throws -> (status: Int32, output: String) { + let shell = Process(), output = Pipe() + shell.executableURL = URL(fileURLWithPath: "/bin/sh") + shell.arguments = ["-c", script] + shell.standardOutput = output + shell.standardError = Pipe() + try shell.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + shell.waitUntilExit() + return (shell.terminationStatus, String(decoding: data, as: UTF8.self)) + } + #expect(try run() == (0, "\(echo.path) prepare \(bindingID.uuidString)\n")) + try FileManager.default.removeItem(at: links) + #expect(try run().status == 1) + + // Xcode keeps the binding when the developer renames or duplicates the scheme. + let schemes = file.deletingLastPathComponent() + let renamed = schemes.appendingPathComponent("Renamed.xcscheme") + try FileManager.default.moveItem(at: file, to: renamed) + let copy = try XMLDocument(contentsOf: renamed, options: []) + let arguments = XMLElement(name: "CommandLineArguments") + let argument = XMLElement(name: "CommandLineArgument") + argument.setAttributesWith(["argument": "-copy", "isEnabled": "YES"]) + arguments.addChild(argument) + (try copy.nodes(forXPath: "//LaunchAction").first as? XMLElement)?.addChild(arguments) + try copy.xmlData.write(to: schemes.appendingPathComponent("Copy.xcscheme")) + func options(_ settings: [String: String]) throws -> [String] { + let found = try DebugScheme.installed(binding: bindingID, settings: settings) + #expect(found.binding.destination == vm) + return try DebugScheme.launchOptions(from: found.document, settings: settings).arguments + } + #expect(try options(["WORKSPACE_PATH": ws.path, "SCHEME_NAME": "Renamed"]) == []) + #expect(try options(["WORKSPACE_PATH": ws.path, "SCHEME_NAME": "Copy"]) == ["-copy"]) + #expect(throws: (any Error).self) { try options(["WORKSPACE_PATH": project.appendingPathComponent("project.xcworkspace").path]) } + #expect(throws: (any Error).self) { try DebugScheme.installed(binding: UUID(), settings: ["WORKSPACE_PATH": ws.path]) } } @Test func argumentsAndBuildSettingsAreData() throws { diff --git a/Packages/README.md b/Packages/README.md index d3d4057..151d61c 100644 --- a/Packages/README.md +++ b/Packages/README.md @@ -11,7 +11,7 @@ VirtualBuddy uses local Swift packages for Xcode deployment and debugging on App ### Host integration -Create a `DebugHostConfiguration` with the app URL, helper executable, and a short, private per-user socket directory. The generated scheme loads the LLDB module from the package's resource bundle. Forward the helper's arguments to `DebugHostCommand.run`. Create one `DebugSymbolCache` with the app's chosen cache directory and helper, and share it between the broker and cache management UI. +Create a `DebugHostConfiguration` with the app URL, helper executable, a short, private per-user socket directory, and a links directory. Generated schemes run the helper and load the LLDB module through links in that directory, which `start()` and `install` point at the running app, so schemes keep working when the app is updated or moved. Choose a per-user location outside the app bundle and never change it: schemes that already exist refer to it. Forward the helper's arguments to `DebugHostCommand.run`. Create one `DebugSymbolCache` with the app's chosen cache directory and helper, and share it between the broker and cache management UI. Start a `DebugBroker` with an authorization check and a closure that resolves a stable destination UUID to a `RemoteDebugSession`. Use `DebugScheme.choices(in:)` and `install(destination:named:configuration:bindings:)` to create the user's Xcode scheme. Call `start()` while debugging is enabled and `stopListening()` when the user turns it off, so the socket exists only while it is needed; runs that are already debugging continue. Call `stop()` when the app shuts down. diff --git a/README-Developers.md b/README-Developers.md index 27a7010..34957c1 100644 --- a/README-Developers.md +++ b/README-Developers.md @@ -4,7 +4,7 @@ VirtualBuddy can help you set up an Xcode project so that you can run and debug ## Requirements -On the first launch with this feature, VirtualBuddy turns on developer features if Xcode is installed. You can change this under **VirtualBuddy Settings → Developer → Enable Developer Features**. +Developer features are on when Xcode is installed, until you choose otherwise under **VirtualBuddy Settings → Developer → Enable Developer Features**. After that, VirtualBuddy keeps your choice. The guest needs the current VirtualBuddyGuest app running in a logged-in desktop session and Apple’s Command Line Tools or Xcode installed. Build a signed arm64 macOS app with the Debug configuration and the `com.apple.security.get-task-allow` entitlement, which is added by default in debug builds with Xcode. diff --git a/VirtualCore/Source/Debugging/VirtualBuddyDebugging.swift b/VirtualCore/Source/Debugging/VirtualBuddyDebugging.swift index bcec460..b8d20ef 100644 --- a/VirtualCore/Source/Debugging/VirtualBuddyDebugging.swift +++ b/VirtualCore/Source/Debugging/VirtualBuddyDebugging.swift @@ -5,7 +5,10 @@ public enum VirtualBuddyDebugging { public static let host = DebugHostConfiguration( applicationURL: Bundle.main.bundleURL, helperURL: Bundle.main.bundleURL.appendingPathComponent("Contents/MacOS/vbdebug"), - runtimeDirectory: URL(fileURLWithPath: "/private/tmp/vbdebug-\(getuid())", isDirectory: true) + runtimeDirectory: URL(fileURLWithPath: "/private/tmp/vbdebug-\(getuid())", isDirectory: true), + // Xcode schemes created by earlier versions refer to this directory. Do not move it. + linksDirectory: FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appendingPathComponent("codes.rambo.VirtualBuddy/XcodeDebugging", isDirectory: true) ) public static let bindings = KeychainDebugBindingStore( diff --git a/VirtualCore/Source/Settings/VBSettings.swift b/VirtualCore/Source/Settings/VBSettings.swift index 8b53675..851ce1b 100644 --- a/VirtualCore/Source/Settings/VBSettings.swift +++ b/VirtualCore/Source/Settings/VBSettings.swift @@ -55,7 +55,16 @@ public struct VBSettings: Hashable, Sendable { public var enableTSSCheck: Bool /// The user's choice, preserved even when a profile disables developer features. - public var developerFeaturesEnabled = false + /// Until the user makes one, developer features follow whether Xcode is installed. + public var developerFeaturesEnabled: Bool { + get { developerFeaturesChoice ?? developerFeaturesDefault } + set { developerFeaturesChoice = newValue } + } + + /// Only an explicit choice is saved, so the default stays free to follow the Mac's setup + /// and to change in a later version without overriding what the user picked. + private var developerFeaturesChoice: Bool? + private var developerFeaturesDefault = false /// Show desktop picture from guest VM in thumbnails instead of the blur hash version. /// Currently not exposed in the UI. @@ -136,10 +145,8 @@ extension VBSettings { self.version = defaults.integer(forKey: Keys.version) self.enableTSSCheck = defaults.bool(forKey: Keys.enableTSSCheck) - if defaults.object(forKey: Keys.developerFeaturesEnabled) == nil { - defaults.set(isXcodeInstalled(), forKey: Keys.developerFeaturesEnabled) - } - self.developerFeaturesEnabled = defaults.bool(forKey: Keys.developerFeaturesEnabled) + self.developerFeaturesChoice = defaults.object(forKey: Keys.developerFeaturesEnabled) as? Bool + self.developerFeaturesDefault = developerFeaturesChoice == nil && isXcodeInstalled() self.showDesktopPictureThumbnails = defaults.bool(forKey: Keys.showDesktopPictureThumbnails) self.bootDiskImagesUseASIF = defaults.bool(forKey: Keys.bootDiskImagesUseASIF) self.closeBehavior = defaults.string(forKey: Keys.closeBehavior).flatMap(VMCloseBehavior.init(rawValue:)) ?? Self.defaultCloseBehavior @@ -188,7 +195,7 @@ extension VBSettings { defaults.set(libraryURL.path, forKey: Keys.libraryPath) defaults.set(updateChannel.id, forKey: Keys.updateChannel) defaults.set(enableTSSCheck, forKey: Keys.enableTSSCheck) - defaults.set(developerFeaturesEnabled, forKey: Keys.developerFeaturesEnabled) + if let developerFeaturesChoice { defaults.set(developerFeaturesChoice, forKey: Keys.developerFeaturesEnabled) } defaults.set(showDesktopPictureThumbnails, forKey: Keys.showDesktopPictureThumbnails) defaults.set(bootDiskImagesUseASIF, forKey: Keys.bootDiskImagesUseASIF) defaults.set(closeBehavior.rawValue, forKey: Keys.closeBehavior) diff --git a/VirtualCoreTests/DeveloperFeaturesSettingsTests.swift b/VirtualCoreTests/DeveloperFeaturesSettingsTests.swift index dab250a..ef98422 100644 --- a/VirtualCoreTests/DeveloperFeaturesSettingsTests.swift +++ b/VirtualCoreTests/DeveloperFeaturesSettingsTests.swift @@ -5,7 +5,7 @@ import Testing struct DeveloperFeaturesSettingsTests { @Test(arguments: [true, false]) - func detectsXcodeOnceAndPreservesUserChoice(xcodeInstalled: Bool) throws { + func followsXcodeUntilTheUserChooses(xcodeInstalled: Bool) throws { let suiteName = "DeveloperFeaturesSettingsTests.\(UUID().uuidString)" let defaults = try #require(UserDefaults(suiteName: suiteName)) defer { defaults.removePersistentDomain(forName: suiteName) } @@ -19,20 +19,24 @@ struct DeveloperFeaturesSettingsTests { } } - let firstLaunch = try readSettings(xcodeInstalled: xcodeInstalled) + var firstLaunch = try readSettings(xcodeInstalled: xcodeInstalled) #expect(firstLaunch.developerFeaturesEnabled == xcodeInstalled) #expect(firstLaunch.closeBehavior == .saveState) - #expect(checks == 1) + + // Saving another setting must not turn the detected default into a choice. + firstLaunch.enableTSSCheck.toggle() + try firstLaunch.write(to: defaults) + #expect(defaults.object(forKey: "developerFeaturesEnabled") == nil) var nextLaunch = try readSettings(xcodeInstalled: !xcodeInstalled) - #expect(nextLaunch.developerFeaturesEnabled == xcodeInstalled) - #expect(checks == 1) + #expect(nextLaunch.developerFeaturesEnabled == !xcodeInstalled) + #expect(checks == 2) - nextLaunch.developerFeaturesEnabled.toggle() + nextLaunch.developerFeaturesEnabled = xcodeInstalled try nextLaunch.write(to: defaults) - let afterToggle = try readSettings(xcodeInstalled: xcodeInstalled) - #expect(afterToggle.developerFeaturesEnabled == !xcodeInstalled) - #expect(checks == 1) + let afterChoice = try readSettings(xcodeInstalled: !xcodeInstalled) + #expect(afterChoice.developerFeaturesEnabled == xcodeInstalled) + #expect(checks == 2) } @Test func availabilityFollowsTheSettingAndTheRestriction() throws {